repo
string
commit
string
message
string
diff
string
robertbrook/findyourmp
2816a60313b5ed4108e3beca08cf78827ad02727
fixing version of cap in gemfile
diff --git a/Capfile b/Capfile index a80b79d..00f53d7 100644 --- a/Capfile +++ b/Capfile @@ -1,6 +1,6 @@ -load 'deploy' if respond_to?(:namespace) # cap2 differentiator +load './deploy' if respond_to?(:namespace) # cap2 differentiator Dir['vendor/plugins/*/recipes/*.rb'].each { |plugin| load(plugin) } -load 'config/deploy' -load 'config/serverbuild' -load 'config/servertest' -load 'config/passenger' +load './config/deploy' +load './config/serverbuild' +load './config/servertest' +load './config/passenger' diff --git a/Gemfile b/Gemfile index 7be03ee..4b8eaa3 100644 --- a/Gemfile +++ b/Gemfile @@ -1,29 +1,33 @@ source "http://rubygems.org" gem 'rake' gem 'rails', '2.3.17' gem 'rdoc' gem 'haml', '3.1.8' gem 'authlogic', '2.1.9' gem 'friendly_id', '2.3.4', :require => "friendly_id" gem 'xss_terminate' gem 'hpricot' gem 'nokogiri' gem 'aws-s3' gem 'mysql2', '0.2.6' gem 'unicode' gem 'resource_controller' gem 'rest-client' gem 'newrelic_rpm' group :test do gem 'test-unit', '1.2.3' gem 'webrat' gem 'simplecov' gem 'rspec', '1.3.2' gem 'rspec-rails', '1.3.2' gem "capybara", "1.1.1" gem "gherkin", "2.5.0" gem 'cucumber', '1.1.0' gem 'cucumber-rails', '0.3.2' end + +group :development do + gem 'capistrano', '2.15.5' +end diff --git a/script/server b/script/server old mode 100644 new mode 100755
robertbrook/findyourmp
5511302d4042b8f4ad78351f22e87b5c97c6b649
adding new_relic to Gemfile
diff --git a/Gemfile b/Gemfile index c232124..7be03ee 100644 --- a/Gemfile +++ b/Gemfile @@ -1,28 +1,29 @@ source "http://rubygems.org" gem 'rake' gem 'rails', '2.3.17' gem 'rdoc' gem 'haml', '3.1.8' gem 'authlogic', '2.1.9' gem 'friendly_id', '2.3.4', :require => "friendly_id" gem 'xss_terminate' gem 'hpricot' gem 'nokogiri' gem 'aws-s3' gem 'mysql2', '0.2.6' gem 'unicode' gem 'resource_controller' gem 'rest-client' +gem 'newrelic_rpm' group :test do gem 'test-unit', '1.2.3' gem 'webrat' gem 'simplecov' gem 'rspec', '1.3.2' gem 'rspec-rails', '1.3.2' gem "capybara", "1.1.1" gem "gherkin", "2.5.0" gem 'cucumber', '1.1.0' gem 'cucumber-rails', '0.3.2' end diff --git a/Gemfile.lock b/Gemfile.lock index e3de174..cac26ad 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,136 +1,138 @@ GEM remote: http://rubygems.org/ specs: actionmailer (2.3.17) actionpack (= 2.3.17) actionpack (2.3.17) activesupport (= 2.3.17) rack (~> 1.1.0) activerecord (2.3.17) activesupport (= 2.3.17) activeresource (2.3.17) activesupport (= 2.3.17) activesupport (2.3.17) authlogic (2.1.9) activerecord (~> 2.3.0) activesupport (~> 2.3.0) aws-s3 (0.6.3) builder mime-types xml-simple builder (3.2.2) capybara (1.1.1) mime-types (>= 1.16) nokogiri (>= 1.3.3) rack (>= 1.0.0) rack-test (>= 0.5.4) selenium-webdriver (~> 2.0) xpath (~> 0.1.4) chardet (0.9.0) childprocess (0.3.9) ffi (~> 1.0, >= 1.0.11) cucumber (1.1.0) builder (>= 2.1.2) diff-lcs (>= 1.1.2) gherkin (~> 2.5.0) json (>= 1.4.6) term-ansicolor (>= 1.0.6) cucumber-rails (0.3.2) cucumber (>= 0.8.0) diff-lcs (1.2.5) docile (1.1.1) ffi (1.9.3) friendly_id (2.3.4) activerecord (>= 2.2) activesupport (>= 2.2) gherkin (2.5.0) json (>= 1.4.6) haml (3.1.8) hoe (3.7.1) rake (>= 0.8, < 11.0) hpricot (0.8.6) html5 (0.10.0) chardet (>= 0.9.0) hoe (>= 1.2.0) json (1.8.1) mime-types (2.0) mini_portile (0.5.2) multi_json (1.8.2) mysql2 (0.2.6) + newrelic_rpm (3.7.2.195) nokogiri (1.6.0) mini_portile (~> 0.5.0) rack (1.1.6) rack-test (0.6.2) rack (>= 1.0) rails (2.3.17) actionmailer (= 2.3.17) actionpack (= 2.3.17) activerecord (= 2.3.17) activeresource (= 2.3.17) activesupport (= 2.3.17) rake (>= 0.8.3) rake (10.1.0) rdoc (4.0.1) json (~> 1.4) resource_controller (0.6.6) rest-client (1.6.7) mime-types (>= 1.16) rspec (1.3.2) rspec-rails (1.3.2) rack (>= 1.0.0) rspec (>= 1.3.0) rubyzip (1.0.0) selenium-webdriver (2.37.0) childprocess (>= 0.2.5) multi_json (~> 1.0) rubyzip (~> 1.0.0) websocket (~> 1.0.4) simplecov (0.8.2) docile (~> 1.1.0) multi_json simplecov-html (~> 0.8.0) simplecov-html (0.8.0) term-ansicolor (1.2.2) tins (~> 0.8) test-unit (1.2.3) hoe (>= 1.5.1) tins (0.13.1) unicode (0.4.4) webrat (0.7.3) nokogiri (>= 1.2.0) rack (>= 1.0) rack-test (>= 0.5.3) websocket (1.0.7) xml-simple (1.1.2) xpath (0.1.4) nokogiri (~> 1.3) xss_terminate (0.22) html5 (>= 0.10.0) PLATFORMS ruby DEPENDENCIES authlogic (= 2.1.9) aws-s3 capybara (= 1.1.1) cucumber (= 1.1.0) cucumber-rails (= 0.3.2) friendly_id (= 2.3.4) gherkin (= 2.5.0) haml (= 3.1.8) hpricot mysql2 (= 0.2.6) + newrelic_rpm nokogiri rails (= 2.3.17) rake rdoc resource_controller rest-client rspec (= 1.3.2) rspec-rails (= 1.3.2) simplecov test-unit (= 1.2.3) unicode webrat xss_terminate
robertbrook/findyourmp
f14cdfab8f8fc40fe62ff834955b82a2490b8a65
added button to pull member data from data.parliament.uk
diff --git a/Gemfile b/Gemfile index 9547754..c232124 100644 --- a/Gemfile +++ b/Gemfile @@ -1,27 +1,28 @@ source "http://rubygems.org" gem 'rake' gem 'rails', '2.3.17' gem 'rdoc' gem 'haml', '3.1.8' gem 'authlogic', '2.1.9' gem 'friendly_id', '2.3.4', :require => "friendly_id" gem 'xss_terminate' gem 'hpricot' +gem 'nokogiri' gem 'aws-s3' gem 'mysql2', '0.2.6' gem 'unicode' gem 'resource_controller' +gem 'rest-client' group :test do gem 'test-unit', '1.2.3' gem 'webrat' - gem 'nokogiri' gem 'simplecov' gem 'rspec', '1.3.2' gem 'rspec-rails', '1.3.2' gem "capybara", "1.1.1" gem "gherkin", "2.5.0" gem 'cucumber', '1.1.0' gem 'cucumber-rails', '0.3.2' end diff --git a/Gemfile.lock b/Gemfile.lock index d4e60e8..e3de174 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,133 +1,136 @@ GEM remote: http://rubygems.org/ specs: actionmailer (2.3.17) actionpack (= 2.3.17) actionpack (2.3.17) activesupport (= 2.3.17) rack (~> 1.1.0) activerecord (2.3.17) activesupport (= 2.3.17) activeresource (2.3.17) activesupport (= 2.3.17) activesupport (2.3.17) authlogic (2.1.9) activerecord (~> 2.3.0) activesupport (~> 2.3.0) aws-s3 (0.6.3) builder mime-types xml-simple builder (3.2.2) capybara (1.1.1) mime-types (>= 1.16) nokogiri (>= 1.3.3) rack (>= 1.0.0) rack-test (>= 0.5.4) selenium-webdriver (~> 2.0) xpath (~> 0.1.4) chardet (0.9.0) childprocess (0.3.9) ffi (~> 1.0, >= 1.0.11) cucumber (1.1.0) builder (>= 2.1.2) diff-lcs (>= 1.1.2) gherkin (~> 2.5.0) json (>= 1.4.6) term-ansicolor (>= 1.0.6) cucumber-rails (0.3.2) cucumber (>= 0.8.0) diff-lcs (1.2.5) docile (1.1.1) ffi (1.9.3) friendly_id (2.3.4) activerecord (>= 2.2) activesupport (>= 2.2) gherkin (2.5.0) json (>= 1.4.6) haml (3.1.8) hoe (3.7.1) rake (>= 0.8, < 11.0) hpricot (0.8.6) html5 (0.10.0) chardet (>= 0.9.0) hoe (>= 1.2.0) json (1.8.1) mime-types (2.0) mini_portile (0.5.2) multi_json (1.8.2) mysql2 (0.2.6) nokogiri (1.6.0) mini_portile (~> 0.5.0) rack (1.1.6) rack-test (0.6.2) rack (>= 1.0) rails (2.3.17) actionmailer (= 2.3.17) actionpack (= 2.3.17) activerecord (= 2.3.17) activeresource (= 2.3.17) activesupport (= 2.3.17) rake (>= 0.8.3) rake (10.1.0) rdoc (4.0.1) json (~> 1.4) resource_controller (0.6.6) + rest-client (1.6.7) + mime-types (>= 1.16) rspec (1.3.2) rspec-rails (1.3.2) rack (>= 1.0.0) rspec (>= 1.3.0) rubyzip (1.0.0) selenium-webdriver (2.37.0) childprocess (>= 0.2.5) multi_json (~> 1.0) rubyzip (~> 1.0.0) websocket (~> 1.0.4) simplecov (0.8.2) docile (~> 1.1.0) multi_json simplecov-html (~> 0.8.0) simplecov-html (0.8.0) term-ansicolor (1.2.2) tins (~> 0.8) test-unit (1.2.3) hoe (>= 1.5.1) tins (0.13.1) unicode (0.4.4) webrat (0.7.3) nokogiri (>= 1.2.0) rack (>= 1.0) rack-test (>= 0.5.3) websocket (1.0.7) xml-simple (1.1.2) xpath (0.1.4) nokogiri (~> 1.3) xss_terminate (0.22) html5 (>= 0.10.0) PLATFORMS ruby DEPENDENCIES authlogic (= 2.1.9) aws-s3 capybara (= 1.1.1) cucumber (= 1.1.0) cucumber-rails (= 0.3.2) friendly_id (= 2.3.4) gherkin (= 2.5.0) haml (= 3.1.8) hpricot mysql2 (= 0.2.6) nokogiri rails (= 2.3.17) rake rdoc resource_controller + rest-client rspec (= 1.3.2) rspec-rails (= 1.3.2) simplecov test-unit (= 1.2.3) unicode webrat xss_terminate diff --git a/app/controllers/constituency_lists_controller.rb b/app/controllers/constituency_lists_controller.rb index 63aae81..3f0800c 100644 --- a/app/controllers/constituency_lists_controller.rb +++ b/app/controllers/constituency_lists_controller.rb @@ -1,23 +1,32 @@ #encoding: utf-8 +require "./lib/members_names_data" + class ConstituencyListsController < ApplicationController before_filter :require_admin_user def edit @constituency_list = ConstituencyList.new end def update items = params['constituency_list']['items'] @constituency_list = ConstituencyList.new @constituency_list.items = items - + @changed_constituencies = @constituency_list.changed_constituencies @unchanged_constituencies = @constituency_list.unchanged_constituencies - + @invalid_constituencies = @constituency_list.invalid_constituencies @unrecognized_constituencies = @constituency_list.unrecognized_constituencies @ommitted_constituencies = @constituency_list.ommitted_constituencies end + + def load_latest + raw_data = MembersNamesData.new + tsv = raw_data.to_tsv + @constituency_list = ConstituencyList.new(tsv) + render :edit + end end diff --git a/app/models/constituency.rb b/app/models/constituency.rb index f38811c..a34e034 100644 --- a/app/models/constituency.rb +++ b/app/models/constituency.rb @@ -1,215 +1,226 @@ #encoding: utf-8 class Constituency < ActiveRecord::Base include ActionController::UrlWriter has_friendly_id :name, :use_slug => true, :strip_diacritics => true has_many :postcodes has_many :postcode_districts has_many :messages validate :valid_email? class << self def all_constituencies all.select{|c| c.name != 'Example'} end def remove_quotes text unless text text = "" end text.strip[/^"?([^"]+)"?$/,1] end - + def load_tsv_line line parts = line.split("\t") - + constituency_name = remove_quotes(parts[0]) member_name = remove_quotes(parts[1]) member_party = remove_quotes(parts[2]) member_bio_url = remove_quotes(parts[3]) member_contact = remove_quotes(parts[4]) member_website = remove_quotes(parts[5]) + member_visible = remove_quotes(parts[6]) if parts.size > 6 member_contact = "" unless member_contact - + case member_visible + when "False" + member_visible = false + when "True" + member_visible = true + else + member_visible = nil + end + existing = Constituency.find_by_constituency_name(constituency_name) + member_visible = existing.member_visible if member_visible.nil? new_constituency = nil - + if existing - non_matching = (existing.member_name != member_name || existing.member_party != member_party || existing.member_biography_url != member_bio_url) + non_matching = (existing.member_name != member_name || existing.member_party != member_party || existing.member_biography_url != member_bio_url || existing.member_visible != member_visible) non_matching = non_matching || ( member_contact[/http:\/\//] ? (existing.member_requested_contact_url.to_s.strip != member_contact.to_s.strip) : (existing.member_email.to_s.strip != member_contact.to_s.strip) ) if non_matching new_constituency = Constituency.new(existing.attributes) new_constituency.member_name = member_name new_constituency.member_party = member_party new_constituency.member_biography_url = member_bio_url if member_contact[/http:\/\//] new_constituency.member_requested_contact_url = member_contact else new_constituency.member_email = member_contact.chomp('.') end new_constituency.member_website = member_website + new_constituency.member_visible = member_visible end [existing, new_constituency] else [nil, nil] end end def find_all_constituency_and_member_matches term term = term.squeeze(' ').gsub('"','') constituencies = Constituency.find_all_name_or_member_name_matches(term) members = constituencies.clone if term[/[A-Z][a-z].*/] constituencies = constituencies.select { |c| c.name.include? term } members = members.select { |c| c.member_name.include? term } else constituencies = constituencies.select { |c| c.name.downcase.include? term.downcase } members = members.select { |c| c.member_name? && c.member_name.downcase.include?(term.downcase) } end constituencies = constituencies.sort_by(&:name) members = members.sort_by(&:member_name) return [constituencies, members] end def find_all_name_or_member_name_matches term term = term.squeeze(' ').gsub('"','') matches_name_or_member_name = %Q|name like "%#{term}%" or | + %Q|(member_name like "%#{term}%" and member_visible = 1)| constituencies = find(:all, :conditions => matches_name_or_member_name) constituencies.delete_if{|c| c.name == 'Example'} if case_sensitive(term) constituencies.delete_if do |c| !c.name.include?(term) && !c.member_name.include?(term) end end constituencies end def case_sensitive term term.gsub('"','')[/^([A-Z][a-z]+[ ]+)*([A-Z][a-z]+)$/] ? true : false end def find_by_constituency_name name name.gsub!(' - ','-') if name[/^(.+), City of$/] name = "City of #{$1}" end constituency = find_by_name(name) unless constituency name.gsub!('&', 'and') if name == "Regent's Park and Kensington North" name = "Regent's Park and North Kensington" end if name[/^(.+), The$/] name = "The #{$1}" end name.tr!('-', ' ') name.gsub!('ô','o') name.gsub!('and#244;', 'o') constituency = find_by_name(name) end unless constituency name.gsub!('St ', 'St. ') constituency = find_by_name(name) end unless constituency puts "" puts "not found: #{name}" end constituency end end def show_message_form? member_name? && member_email? && !member_requested_contact_url? end def code if ons_id.nil? '' elsif ons_id.length == 1 "00#{ons_id}" elsif ons_id.length == 2 "0#{ons_id}" else ons_id.to_s end end def no_sitting_member? (!member_name?) || (!member_visible) end def to_tsv_line %Q|"#{name}"\t"#{member_name}"\t"#{member_party}"\t"#{member_biography_url}"\t"#{member_email}"\t"#{member_website}"| end def to_json host, port if no_sitting_member? %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "No sitting member", "member_party": "", "member_biography_url": "", "member_website": "", "uri": "#{object_url(host, port, "json")}" } }| else %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "#{member_name}", "member_party": "#{member_party}", "member_biography_url": "#{member_biography_url}", "member_website": "#{member_website}", "uri": "#{object_url(host, port, "json")}" } }| end end def to_text host, port, format="txt" if no_sitting_member? %Q|constituency_name: #{name}\nmember_name: No sitting member\nmember_party: \nmember_biography_url: \nmember_website: \nuri: #{object_url(host, port, format)}| else %Q|constituency_name: #{name}\nmember_name: #{member_name}\nmember_party: #{member_party}\nmember_biography_url: #{member_biography_url}\nmember_website: #{member_website}\nuri: #{object_url(host, port, format)}| end end def to_csv host, port headers = 'constituency_name,member_name,member_party,member_biography_url,member_website,uri' values = to_csv_value(host, port) "#{headers}\n#{values}\n" end def to_csv_value host, port if no_sitting_member? %Q|"#{name}","No sitting member","","","","#{object_url(host, port, format, "csv")}"| else %Q|"#{name}","#{member_name}","#{member_party}","#{member_biography_url}","#{member_website}","#{object_url(host, port, "csv")}"| end end def to_output_yaml host, port "---\n#{to_text(host, port, "yaml")}" end def member_attribute_changed? attribute, constituency send(attribute).to_s.strip != constituency.send(attribute).to_s.strip end private def valid_email? unless member_email.blank? begin self.member_email = MessageMailer.parse_email(member_email).address rescue errors.add_to_base("Member email must be a valid email") end end end def object_url host, port, format=nil if port.to_s == "80" url_for :host=> host, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false else url_for :host=> host, :port=> port, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false end end end diff --git a/app/models/constituency_list.rb b/app/models/constituency_list.rb index 6250309..21b21c0 100644 --- a/app/models/constituency_list.rb +++ b/app/models/constituency_list.rb @@ -1,43 +1,53 @@ class ConstituencyList attr_reader :constituencies, :invalid_constituencies, :unchanged_constituencies, :changed_constituencies, :unrecognized_constituencies, :ommitted_constituencies + def initialize(text=nil) + if text + @lines = text + end + end + def items - Constituency.all_constituencies.collect(&:to_tsv_line).sort.join("\n") + if @lines + @lines + else + Constituency.all_constituencies.collect(&:to_tsv_line).sort.join("\n") + end end - + def items= text constituencies = ActiveSupport::OrderedHash.new constituency_list = [] lines = [] text.each_line do |line| line.strip! lines << line unless(line.blank? || line[/Constituency/]) end - + lines.sort.each do |line| loaded = Constituency.load_tsv_line(line) constituencies[line] = loaded constituency_list << ConstituencyItem.new(line, loaded[0], loaded[1]) end - + @unchanged_constituencies = constituency_list.select{|x| x.new_constituency.nil? && !x.old.nil? } @changed_constituencies = constituency_list.select{|x| x.new_constituency } @invalid_constituencies = @changed_constituencies.select{|x| !x.new_constituency.valid? } @changed_constituencies = @changed_constituencies - @invalid_constituencies @unrecognized_constituencies = constituency_list.select{|x| x.old.nil? && x.new_constituency.nil? } - + @ommitted_constituencies = Constituency.all_constituencies constituency_list.each { |x| @ommitted_constituencies.delete(x.old) if x.old } - + @constituencies = constituencies end end class ConstituencyItem attr_reader :line, :old, :new_constituency def initialize line, old, new_constituency @line, @old, @new_constituency = line, old, new_constituency end end diff --git a/app/views/constituency_lists/edit.haml b/app/views/constituency_lists/edit.haml index 85e35b8..adde74d 100644 --- a/app/views/constituency_lists/edit.haml +++ b/app/views/constituency_lists/edit.haml @@ -1,9 +1,13 @@ - @crumbtrail = link_to_admin_home - @title = 'Edit constituency list' +- form_tag('edit', :method=>:post) do + %p.text + = submit_tag "Load latest PICT data" + - form_tag('/constituency_list', :method=>:put) do %p.text = text_area :constituency_list, :items, :size=>'90x646' %p.text = submit_tag "Update constituencies" diff --git a/app/views/constituency_lists/update.haml b/app/views/constituency_lists/update.haml index 944203e..614a348 100644 --- a/app/views/constituency_lists/update.haml +++ b/app/views/constituency_lists/update.haml @@ -1,93 +1,101 @@ = javascript_include_tag :defaults - @crumbtrail = link_to_admin_home - @title= 'Constituencies' - unless @invalid_constituencies.empty? %h3 Invalid data .text{:style => "margin-bottom: 3em;"} - @invalid_constituencies.each do |item| %p= item.new_constituency.errors.full_messages.join("<br/>") %p.warn= item.line - unless @unrecognized_constituencies.empty? %h3 Unrecognized constituencies .text{:style => "margin-bottom: 3em;"} - @unrecognized_constituencies.each do |item| %p= item.line - unless @ommitted_constituencies.empty? %h3 Missing constituencies .text{:style => "margin-bottom: 3em;"} - @ommitted_constituencies.each do |constituency| %p.warn= constituency.name - unless @changed_constituencies.empty? %h3 Changed constituencies .text - @changed_constituencies.each do |item| - constituency = item.old - new_constituency = item.new_constituency - id = "constituency#{constituency.id}" %div{:id=>id} - remote_form_for(constituency, :update => id) do |f| %p= constituency.name - member_name_changed = constituency.member_attribute_changed?(:member_name, new_constituency) - member_party_changed = constituency.member_attribute_changed?(:member_party, new_constituency) - member_email_changed = constituency.member_attribute_changed?(:member_email, new_constituency) - member_biography_url_changed = constituency.member_attribute_changed?(:member_biography_url, new_constituency) - member_website_changed = constituency.member_attribute_changed?(:member_website, new_constituency) - member_requested_contact_url_changed = constituency.member_attribute_changed?(:member_requested_contact_url, new_constituency) + - member_visible_changed = constituency.member_attribute_changed?(:member_visible, new_constituency) %p - if member_name_changed = f.label :member_name, "#{constituency.member_name} -> " = f.text_field :member_name, :value => "#{new_constituency.member_name}", :size=>60 - else = f.label :member_name = f.text_field :member_name, :size=>60 %p - if member_party_changed = f.label :member_party, "#{constituency.member_party} -> " = f.text_field :member_party, :value => "#{new_constituency.member_party}", :size=>60 - else = f.label :member_party = f.text_field :member_party, :size=>60 %p - if member_email_changed = f.label :member_email, constituency.member_email.blank? ? 'Email' : "#{constituency.member_email} -> " = f.text_field :member_email, :value => "#{new_constituency.member_email}", :size=>60 - else = f.label :member_email, 'Email' = f.text_field :member_email, :size=>60 %p - if member_biography_url_changed = f.label :member_biography_url, constituency.member_biography_url.blank? ? 'Biography URL' : "#{constituency.member_biography_url} -> " = f.text_field :member_biography_url, :value => "#{new_constituency.member_biography_url}", :size=>60 - else = f.label :member_biography_url, 'Biography URL' = f.text_field :member_biography_url, :size=>60 %p - if member_website_changed = f.label :member_website, constituency.member_website.blank? ? 'Website' : "#{constituency.member_website} -> " = f.text_field :member_website, :value => "#{new_constituency.member_website}", :size=>60 - else = f.label :member_website, 'Website' = f.text_field :member_website, :size=>60 %p - if member_requested_contact_url_changed = f.label :member_requested_contact_url, constituency.member_requested_contact_url.blank? ? 'Requested contact URL' : "#{constituency.member_requested_contact_url} -> " = f.text_field :member_requested_contact_url, :value => "#{new_constituency.member_requested_contact_url}", :size=>60 - else = f.label :member_requested_contact_url, 'Requested contact URL' = f.text_field :member_requested_contact_url, :size=>60 + %p + - if member_visible_changed + = f.label :member_visible, "#{constituency.member_visible} -> " + = f.check_box :member_visible, :checked => new_constituency.member_visible + - else + = f.label :member_visible, 'Visible?' + = f.check_box :member_visible %p %label &nbsp; = f.submit "Update #{constituency.name}" %br - unless @unchanged_constituencies.empty? %h3 Unchanged constituencies %p.text - @unchanged_constituencies.each do |item| = item.old.name %br diff --git a/config/routes.rb b/config/routes.rb index d181b7a..98bb941 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,55 +1,58 @@ ActionController::Routing::Routes.draw do |map| map.resources :constituencies map.resource :account, :controller => "users" map.resources :users map.resource :user_session + map.connect '/constituency_list/edit', :conditions => { :method => :post }, :controller => 'constituency_lists', :action => 'load_latest' + map.connect '/constituency_list/edit', :controller => 'constituency_lists', :action => 'edit' + map.connect '/constituency_list/', :conditions => { :method => :post }, :controller => 'constituency_lists', :action => 'update' map.resource :constituency_list map.resources :password_resets map.root :controller => "postcodes" map.connect '/postcodes/:postcode.:format', :controller => "postcodes", :action => 'show' map.connect '/postcodes/:postcode', :controller => "postcodes", :action => 'show' map.connect '/search/:q.:format', :controller => "search", :action => 'show' map.connect '/search/:q', :controller => "search", :action => 'show' map.search '/search', :controller => "search", :action => 'index' map.connect '/constituencies/hide_members', :conditions => { :method => :post }, :controller => "constituencies", :action => 'hide_members' map.connect '/constituencies/unhide_members', :conditions => { :method => :post }, :controller => "constituencies", :action => 'unhide_members' map.admin '/admin', :controller => 'admin', :action => 'index' map.connect '/admin/sent', :controller => 'admin', :action => 'sent' map.connect '/admin/sent/:yyyy_mm', :controller => 'admin', :action => 'sent_by_month' map.connect '/admin/waiting_to_be_sent', :controller => 'admin', :action => 'waiting_to_be_sent' map.connect '/admin/stats', :controller => 'admin', :action => 'stats' map.shutdown '/admin/shutdown', :controller => 'admin', :action => 'shutdown' map.mailserver_status '/admin/mailserver_status', :controller => 'admin', :action => 'mailserver_status' map.blacklisted_postcodes '/admin/blacklist', :controller => 'blacklisted_postcodes', :action => 'index' map.connect '/admin/blacklist/restore/:code', :controller => 'blacklisted_postcodes', :action => 'restore' map.connect '/admin/blacklist/new', :controller => 'blacklisted_postcodes', :action => 'new' map.manual_postcodes '/admin/manual_postcodes', :controller => 'manual_postcodes', :action => 'index' map.connect '/admin/manual_postcodes/remove/:code', :controller => 'manual_postcodes', :action => 'remove' map.connect '/admin/manual_postcodes/new', :controller => 'manual_postcodes', :action => 'new' map.api '/api', :controller => 'api', :action => 'index' map.connect 'api/search', :controller => 'api', :action => 'search' map.connect 'api/postcodes', :controller => 'api', :action => 'postcodes' map.connect 'api/constituencies', :controller => 'api', :action => 'constituencies' map.connect '/commons/constituency/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/member/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/postcode/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/constituency/cons/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/member/cons/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/email/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/l/', :controller => 'postcodes', :action => 'redir' map.connect '/commons/', :controller => 'postcodes', :action => 'redir' map.connect '*bad_route', :controller => 'application', :action => 'render_not_found' end diff --git a/lib/members_names_data.rb b/lib/members_names_data.rb new file mode 100644 index 0000000..cd4fbf1 --- /dev/null +++ b/lib/members_names_data.rb @@ -0,0 +1,39 @@ +#encoding: utf-8 + +require 'rest-client' +require 'nokogiri' + +class MembersNamesData + def initialize(url=nil) + unless url + url = "http://data.parliament.uk/membersdataplatform/services/mnis/members/query/House=Commons/Addresses" + end + @data = fetch(url) + end + + def to_tsv + doc = Nokogiri::XML(@data) + members = doc.search("//Member") + rows = [] + members.each do |member| + row = [] + row << "\"#{member.at("MemberFrom/text()").to_s.gsub("&#xF4;", "o")}\"" + row << "\"#{member.at("DisplayAs/text()").to_s}\"" + row << "\"#{member.at("Party/text()").to_s}\"" + row << "\"#{"http://www.parliament.uk/biographies/commons/#{member.at("DisplayAs/text()").to_s.gsub(" ", "-")}/#{member.attribute("Member_Id")}"}\"" + row << "\"#{member.at("Addresses/Address[@Type_Id='1']/Email/text()").to_s.gsub("mailto:", "").gsub(/;.*/, "")}\"" + row << "\"#{member.at("Addresses/Address[@Type_Id='6']/Address1/text()").to_s}\"" + row << "\"#{member.at("CurrentStatus").attr("IsActive")}\"" + rows << row.join("\t") + end + rows.sort.join("\n") + end + + + private + + def fetch(data_url) + response = RestClient.get(data_url) + response.body + end +end \ No newline at end of file diff --git a/spec/lib/members_names_data_spec.rb b/spec/lib/members_names_data_spec.rb new file mode 100644 index 0000000..2e2e740 --- /dev/null +++ b/spec/lib/members_names_data_spec.rb @@ -0,0 +1,83 @@ +require './spec/spec_helper' +require './lib/members_names_data' + +describe MembersNamesData do + context 'when creating the object' do + before do + @fake_response = mock("Response") + @fake_response.stub!(:body).and_return("<xml>sample</xml>") + end + + it 'should use RestClient to fetch data from the web' do + RestClient.should_receive(:get).and_return(@fake_response) + MembersNamesData.new + end + + it 'should default to the hardcoded url if none is supplied' do + data_url = "http://data.parliament.uk/membersdataplatform/services/mnis/members/query/House=Commons/Addresses" + RestClient.should_receive(:get).with(data_url).and_return(@fake_response) + MembersNamesData.new + end + + it 'should use the url param if one is supplied' do + data_url = "http://www.theyworkforyou.com/" + RestClient.should_receive(:get).with(data_url).and_return(@fake_response) + MembersNamesData.new(data_url) + end + end + + context 'when asked for the TSV' do + before do + @fake_response = mock("Response") + @fake_response.stub!(:body).and_return(%Q| + <Members> + <Member Member_Id="172" Dods_Id="25790" Pims_Id="3572"> + <DisplayAs>Ms Diane Abbott</DisplayAs> + <ListAs>Abbott, Diane</ListAs> + <FullTitle>Ms Diane Abbott MP</FullTitle> + <DateOfBirth>1953-09-27T00:00:00</DateOfBirth> + <DateOfDeath xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/> + <Gender>F</Gender> + <Party Id="15">Labour</Party> + <House>Commons</House> + <MemberFrom>Hackney North and Stoke Newington</MemberFrom> + <HouseStartDate>1987-06-11T00:00:00</HouseStartDate> + <HouseEndDate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/> + <CurrentStatus Id="0" IsActive="True"> + <Name>Current Member</Name> + <Reason/> + <StartDate>1987-06-11T00:00:00</StartDate> + </CurrentStatus> + <Addresses> + <Address Type_Id="6"> + <Type>Website</Type> + <IsPreferred>False</IsPreferred> + <IsPhysical>False</IsPhysical> + <Note/> + <Address1>http://www.dianeabbott.org.uk</Address1> + </Address> + <Address Type_Id="1"> + <Type>Parliamentary</Type> + <IsPreferred>False</IsPreferred> + <IsPhysical>True</IsPhysical> + <Note/> + <Address1>House of Commons</Address1> + <Address2/> + <Address3/> + <Address4/> + <Address5>London</Address5> + <Postcode>SW1A 0AA</Postcode> + <Phone>000 0000 0000</Phone> + <Fax>000 0000 0000</Fax> + <Email>me@here.com</Email> + <OtherAddress/> + </Address>|) + end + + it 'should format the member data properly' do + RestClient.should_receive(:get).and_return(@fake_response) + data = MembersNamesData.new() + data.to_tsv.should == %Q|"Hackney North and Stoke Newington"\t"Ms Diane Abbott"\t"Labour"\t"http://www.parliament.uk/biographies/commons/Ms-Diane-Abbott/172"\t"me@here.com"\t"http://www.dianeabbott.org.uk"\t"True"| + end + end +end \ No newline at end of file
robertbrook/findyourmp
336244287ca3afd924bbe825a7872fdc1bdca486
fixed cucumber features
diff --git a/Gemfile b/Gemfile index 4d7e1f6..9547754 100644 --- a/Gemfile +++ b/Gemfile @@ -1,23 +1,27 @@ source "http://rubygems.org" gem 'rake' gem 'rails', '2.3.17' gem 'rdoc' gem 'haml', '3.1.8' gem 'authlogic', '2.1.9' gem 'friendly_id', '2.3.4', :require => "friendly_id" gem 'xss_terminate' gem 'hpricot' gem 'aws-s3' gem 'mysql2', '0.2.6' gem 'unicode' gem 'resource_controller' group :test do gem 'test-unit', '1.2.3' gem 'webrat' + gem 'nokogiri' gem 'simplecov' gem 'rspec', '1.3.2' gem 'rspec-rails', '1.3.2' - gem 'cucumber-rails' + gem "capybara", "1.1.1" + gem "gherkin", "2.5.0" + gem 'cucumber', '1.1.0' + gem 'cucumber-rails', '0.3.2' end diff --git a/Gemfile.lock b/Gemfile.lock index bad8aab..d4e60e8 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,116 +1,133 @@ GEM remote: http://rubygems.org/ specs: actionmailer (2.3.17) actionpack (= 2.3.17) actionpack (2.3.17) activesupport (= 2.3.17) rack (~> 1.1.0) activerecord (2.3.17) activesupport (= 2.3.17) activeresource (2.3.17) activesupport (= 2.3.17) activesupport (2.3.17) authlogic (2.1.9) activerecord (~> 2.3.0) activesupport (~> 2.3.0) aws-s3 (0.6.3) builder mime-types xml-simple builder (3.2.2) - capybara (2.2.0) + capybara (1.1.1) mime-types (>= 1.16) nokogiri (>= 1.3.3) rack (>= 1.0.0) rack-test (>= 0.5.4) - xpath (~> 2.0) + selenium-webdriver (~> 2.0) + xpath (~> 0.1.4) chardet (0.9.0) - cucumber (1.3.10) + childprocess (0.3.9) + ffi (~> 1.0, >= 1.0.11) + cucumber (1.1.0) builder (>= 2.1.2) - diff-lcs (>= 1.1.3) - gherkin (~> 2.12) - multi_json (>= 1.7.5, < 2.0) - multi_test (>= 0.0.2) - cucumber-rails (1.3.0) - capybara (>= 1.1.2) - cucumber (>= 1.1.8) - nokogiri (>= 1.5.0) + diff-lcs (>= 1.1.2) + gherkin (~> 2.5.0) + json (>= 1.4.6) + term-ansicolor (>= 1.0.6) + cucumber-rails (0.3.2) + cucumber (>= 0.8.0) diff-lcs (1.2.5) + docile (1.1.1) + ffi (1.9.3) friendly_id (2.3.4) activerecord (>= 2.2) activesupport (>= 2.2) - gherkin (2.12.2) - multi_json (~> 1.3) + gherkin (2.5.0) + json (>= 1.4.6) haml (3.1.8) hoe (3.7.1) rake (>= 0.8, < 11.0) hpricot (0.8.6) html5 (0.10.0) chardet (>= 0.9.0) hoe (>= 1.2.0) json (1.8.1) mime-types (2.0) mini_portile (0.5.2) multi_json (1.8.2) - multi_test (0.0.2) mysql2 (0.2.6) nokogiri (1.6.0) mini_portile (~> 0.5.0) rack (1.1.6) rack-test (0.6.2) rack (>= 1.0) rails (2.3.17) actionmailer (= 2.3.17) actionpack (= 2.3.17) activerecord (= 2.3.17) activeresource (= 2.3.17) activesupport (= 2.3.17) rake (>= 0.8.3) rake (10.1.0) rdoc (4.0.1) json (~> 1.4) resource_controller (0.6.6) rspec (1.3.2) rspec-rails (1.3.2) rack (>= 1.0.0) rspec (>= 1.3.0) - simplecov (0.7.1) + rubyzip (1.0.0) + selenium-webdriver (2.37.0) + childprocess (>= 0.2.5) multi_json (~> 1.0) - simplecov-html (~> 0.7.1) - simplecov-html (0.7.1) + rubyzip (~> 1.0.0) + websocket (~> 1.0.4) + simplecov (0.8.2) + docile (~> 1.1.0) + multi_json + simplecov-html (~> 0.8.0) + simplecov-html (0.8.0) + term-ansicolor (1.2.2) + tins (~> 0.8) test-unit (1.2.3) hoe (>= 1.5.1) + tins (0.13.1) unicode (0.4.4) webrat (0.7.3) nokogiri (>= 1.2.0) rack (>= 1.0) rack-test (>= 0.5.3) + websocket (1.0.7) xml-simple (1.1.2) - xpath (2.0.0) + xpath (0.1.4) nokogiri (~> 1.3) xss_terminate (0.22) html5 (>= 0.10.0) PLATFORMS ruby DEPENDENCIES authlogic (= 2.1.9) aws-s3 - cucumber-rails + capybara (= 1.1.1) + cucumber (= 1.1.0) + cucumber-rails (= 0.3.2) friendly_id (= 2.3.4) + gherkin (= 2.5.0) haml (= 3.1.8) hpricot mysql2 (= 0.2.6) + nokogiri rails (= 2.3.17) rake rdoc resource_controller rspec (= 1.3.2) rspec-rails (= 1.3.2) simplecov test-unit (= 1.2.3) unicode webrat xss_terminate diff --git a/features/step_definitions/find_mp_from_postcode_steps.rb b/features/step_definitions/find_mp_from_postcode_steps.rb index e999df7..dcfd752 100644 --- a/features/step_definitions/find_mp_from_postcode_steps.rb +++ b/features/step_definitions/find_mp_from_postcode_steps.rb @@ -1,10 +1,10 @@ When /^I search for "(.*)"$/ do |search_term| - within '.search' do + within '#search' do fill_in("q", :with => search_term) end And 'I press "Find MP"' end Given /I am on the Front page/ do visit "/" end diff --git a/features/step_definitions/setup.rb b/features/step_definitions/setup.rb index 7b8503f..5a65bc1 100644 --- a/features/step_definitions/setup.rb +++ b/features/step_definitions/setup.rb @@ -1,144 +1,144 @@ Before do Postcode.delete_all Constituency.delete_all Constituency.connection.execute('delete from slugs;') PostcodeDistrict.delete_all Given 'there is a postcode "AB101AA" in constituency "Aberdeen North", ons id "801"' Given 'there is an MP "Frank Doran" in constituency "Aberdeen North"' Given 'there is a postcode "ML14BW" in constituency "Motherwell and Wishaw", ons id "846"' Given 'there is an MP "Mr Frank Roy" in constituency "Motherwell and Wishaw"' Given 'there is a postcode "AB101BE" in constituency "Aberdeen South", ons id "802"' Given 'there is an MP "Miss Anne Begg" in constituency "Aberdeen South"' Given 'there is a postcode "KY8 5XY" in constituency "Glenrothes", ons id "835"' Given 'there is no MP in constituency "Glenrothes"' Given 'there is a postcode "GY1 1AB" with no constituency' Given 'there is a postcode "BT35 8DL" in constituency "Newry & Armagh", ons id "711"' Given 'there is an MP "Conor Murphy" in constituency "Newry & Armagh"' Given 'there is a postcode "BT35 6QY" in constituency "Upper Bann", ons id "717"' Given 'there is an MP "David Simpson" in constituency "Upper Bann"' Given 'there is a postcode district "BT35" that links to constituencies "upper-bann" and "newry-armagh"' if user = User.find_by_login('admin') unless user.admin? user.admin = true user.save! end else user = User.new(:login => 'admin', :password => 'admin', :password_confirmation => 'admin', :email=>'admin@parliament.uk', :admin=>true) user.save! end unless User.find_by_login('editor') user = User.new(:login => 'editor', :password => 'editor', :password_confirmation => 'editor', :email=>'editor@parliament.uk', :admin=>false) user.save! end Message.delete_all # MessageSummary.delete_all Email.delete_all message = Message.new({ :message => 'test', :sender_email => 'x@y.co.uk', :postcode => 'AB101AA', :constituency_id => Constituency.find('aberdeen-north').id, :sender_is_constituent => '1', :sender => 'x', :subject => 'test' }) message.save! message.mailer_error = "535 5.7.8 Error: authentication failed: authentication failure" message.created_at = Date.new(2009,1,1) message.save! email = Email.create({:created_on => message.created_at}) email.save message = Message.new({ :message => 'test', :sender_email => 'x@y.co.uk', :postcode => 'AB101AA', :constituency_id => Constituency.find('aberdeen-north').id, :sender_is_constituent => '1', :sender => 'x', :subject => 'test' }) message.save! message.sent = true message.sent_at = Date.new(2009,2,1) message.save! summary = MessageSummary.find_from_message(message) summary.save! email = Email.new({:created_on => message.created_at}) email.save end When /^I clear "(.*)"$/ do |field| fill_in(field, :with => "") end Then /^I should see json (.+)$/ do |json| response.body.should include(json) end Then /^I should see csv (.+)$/ do |csv| response.body.should include(csv) end Then /^I should see xml "(.+)"$/ do |xml| - response.body.should include(xml) + response.body.should include(xml.strip) end Then /^I should see html "(.+)"$/ do |html| response.body.should include(html) end Then /^I should see link to "(.+)"$/ do |url| response.body.should include(%Q|href="#{url}"|) end Then /^I should see "(.+)" button$/ do |button_text| response.body.should include(%Q|value="#{button_text}"|) end Given /^there is a postcode "(.*)" with no constituency$/ do |postcode_code| Postcode.find_or_create_by_code_and_constituency_id_and_ons_id(postcode_code.gsub(' ','').strip, nil, 900) end Given /^there is a postcode "(.*)" in constituency "(.*)", ons id "(.*)"$/ do |postcode_code, constituency_name, ons_id| constituency = Constituency.find_or_create_by_name_and_ons_id(constituency_name, ons_id) postcode = Postcode.find_or_create_by_code_and_constituency_id_and_ons_id(postcode_code.gsub(' ','').strip, constituency.id, ons_id) end Given /^there is a postcode district "(.*)" that links to constituencies "(.*)" and "(.*)"$/ do |district, constituency1, constituency2| constituency_id = Constituency.find(constituency1).id PostcodeDistrict.find_or_create_by_district_and_constituency_id(district, constituency_id) constituency_id = Constituency.find(constituency2).id PostcodeDistrict.find_or_create_by_district_and_constituency_id(district, constituency_id) end Given /^there is an MP "(.*)" in constituency "(.*)"$/ do |member_name, constituency_name| constituency = Constituency.find_by_name(constituency_name) constituency.member_name = member_name constituency.member_email = member_name.tr(' ','').tableize.singularize + '@parl.uk' constituency.member_visible = true constituency.save end Given /^there is no MP in constituency "(.*)"$/ do |constituency_name| constituency = Constituency.find_or_create_by_name(constituency_name) if constituency.member_name constituency.member_name = nil constituency.save end end diff --git a/features/step_definitions/webrat_steps.rb b/features/step_definitions/webrat_steps.rb index b506289..ae63656 100644 --- a/features/step_definitions/webrat_steps.rb +++ b/features/step_definitions/webrat_steps.rb @@ -1,103 +1,101 @@ -require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths")) - # Commonly used webrat steps # http://github.com/brynary/webrat Given /^I am at (.+)$/ do |page_name| visit path_to(page_name) end When /^I go to (.+)$/ do |page_name| visit path_to(page_name) end When /^I press "([^\"]*)"$/ do |button| click_button(button) end When /^I follow "([^\"]*)"$/ do |link| click_link(link) end When /^I fill in "([^\"]*)" with "([^\"]*)"$/ do |field, value| fill_in(field, :with => value) end When /^I select "([^\"]*)" from "([^\"]*)"$/ do |value, field| select(value, :from => field) end # Use this step in conjunction with Rail's datetime_select helper. For example: # When I select "December 25, 2008 10:00" as the date and time When /^I select "([^\"]*)" as the date and time$/ do |time| select_datetime(time) end # Use this step when using multiple datetime_select helpers on a page or # you want to specify which datetime to select. Given the following view: # <%= f.label :preferred %><br /> # <%= f.datetime_select :preferred %> # <%= f.label :alternative %><br /> # <%= f.datetime_select :alternative %> # The following steps would fill out the form: # When I select "November 23, 2004 11:20" as the "Preferred" data and time # And I select "November 25, 2004 10:30" as the "Alternative" data and time When /^I select "([^\"]*)" as the "([^\"]*)" date and time$/ do |datetime, datetime_label| select_datetime(datetime, :from => datetime_label) end # Use this step in conjunction with Rail's time_select helper. For example: # When I select "2:20PM" as the time # Note: Rail's default time helper provides 24-hour time-- not 12 hour time. Webrat # will convert the 2:20PM to 14:20 and then select it. When /^I select "([^\"]*)" as the time$/ do |time| select_time(time) end # Use this step when using multiple time_select helpers on a page or you want to # specify the name of the time on the form. For example: # When I select "7:30AM" as the "Gym" time When /^I select "([^\"]*)" as the "([^\"]*)" time$/ do |time, time_label| select_time(time, :from => time_label) end # Use this step in conjunction with Rail's date_select helper. For example: # When I select "February 20, 1981" as the date When /^I select "([^\"]*)" as the date$/ do |date| select_date(date) end # Use this step when using multiple date_select helpers on one page or # you want to specify the name of the date on the form. For example: # When I select "April 26, 1982" as the "Date of Birth" date When /^I select "([^\"]*)" as the "([^\"]*)" date$/ do |date, date_label| select_date(date, :from => date_label) end When /^I check "([^\"]*)"$/ do |field| check(field) end When /^I uncheck "([^\"]*)"$/ do |field| uncheck(field) end When /^I choose "([^\"]*)"$/ do |field| choose(field) end When /^I attach the file at "([^\"]*)" to "([^\"]*)"$/ do |path, field| attach_file(field, path) end Then /^I should see "([^\"]*)"$/ do |text| response.should contain(text) end Then /^I should not see "([^\"]*)"$/ do |text| response.should_not contain(text) end Then /^the "([^\"]*)" checkbox should be checked$/ do |label| field_labeled(label).should be_checked end diff --git a/features/support/env.rb b/features/support/env.rb index 386b2a3..bc50b37 100644 --- a/features/support/env.rb +++ b/features/support/env.rb @@ -1,15 +1,33 @@ # Sets up the Rails environment for Cucumber ENV["RAILS_ENV"] ||= "test" -require File.expand_path(File.dirname(__FILE__) + '/../../config/environment') +require "./config/environment.rb" require 'cucumber/rails/world' -require 'cucumber/formatters/unicode' # Comment out this line if you don't want Cucumber Unicode support -Cucumber::Rails.use_transactional_fixtures +# require 'cucumber/formatters/unicode' # Comment out this line if you don't want Cucumber Unicode support +# Cucumber::Rails.use_transactional_fixtures require 'webrat' Webrat.configure do |config| config.mode = :rails end + +module NavigationHelpers + def path_to(page_name) + case page_name + + when /the homepage/ + root_path + + # Add more page name => path mappings here + + else + raise "Can't find mapping from \"#{page_name}\" to a path." + end + end +end + +World(NavigationHelpers) + require 'cucumber/rails/rspec' require 'webrat/core/matchers' diff --git a/features/support/paths.rb b/features/support/paths.rb deleted file mode 100644 index 925e67a..0000000 --- a/features/support/paths.rb +++ /dev/null @@ -1,19 +0,0 @@ -module NavigationHelpers - def path_to(page_name) - case page_name - - when /the homepage/ - root_path - - # Add more page name => path mappings here - - else - raise "Can't find mapping from \"#{page_name}\" to a path." - end - end -end - -World do |world| - world.extend NavigationHelpers - world -end diff --git a/lib/tasks/cucumber.rake b/lib/tasks/cucumber.rake index f3fa7af..e98e796 100644 --- a/lib/tasks/cucumber.rake +++ b/lib/tasks/cucumber.rake @@ -1,15 +1,15 @@ -$LOAD_PATH.unshift(RAILS_ROOT + '/vendor/plugins/cucumber/lib') if File.directory?(RAILS_ROOT + '/vendor/plugins/cucumber/lib') +require "cucumber" begin require 'cucumber/rake/task' Cucumber::Rake::Task.new(:features) do |t| t.cucumber_opts = "--format pretty" end task :features => 'db:test:prepare' rescue LoadError desc 'Cucumber rake task not available' task :features do abort 'Cucumber rake task is not available. Be sure to install cucumber as a gem or plugin' end end
robertbrook/findyourmp
67cbc476d0570163297bedca485b0b42451c2f70
dealing with new ONS data format
diff --git a/db/migrate/20130523144325_ons_id_longer.rb b/db/migrate/20130523144325_ons_id_longer.rb new file mode 100644 index 0000000..6e28e0e --- /dev/null +++ b/db/migrate/20130523144325_ons_id_longer.rb @@ -0,0 +1,15 @@ +class OnsIdLonger < ActiveRecord::Migration + def self.up + change_column :blacklisted_postcodes, :ons_id, :string, :limit => 20 + change_column :constituencies, :ons_id, :string, :limit => 20 + change_column :manual_postcodes, :ons_id, :string, :limit => 20 + change_column :postcodes, :ons_id, :string, :limit => 20 + end + + def self.down + change_column :blacklisted_postcodes, :ons_id, :string, :limit => 3 + change_column :constituencies, :ons_id, :string, :limit => 3 + change_column :manual_postcodes, :ons_id, :string, :limit => 3 + change_column :postcodes, :ons_id, :string, :limit => 3 + end +end diff --git a/db/schema.rb b/db/schema.rb index 979225c..30945e2 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,146 +1,146 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20100412150417) do +ActiveRecord::Schema.define(:version => 20130523144325) do create_table "blacklisted_postcodes", :force => true do |t| t.string "code", :limit => 7 t.integer "constituency_id" - t.string "ons_id", :limit => 3 + t.string "ons_id", :limit => 20 t.datetime "created_at" t.datetime "updated_at" end add_index "blacklisted_postcodes", ["code"], :name => "index_blacklisted_postcodes_on_code" create_table "constituencies", :force => true do |t| t.string "name" t.string "member_name" t.string "member_party" t.string "member_email" t.string "member_biography_url" t.boolean "member_visible" t.string "member_website" t.string "member_requested_contact_url" - t.string "ons_id", :limit => 3 + t.string "ons_id", :limit => 20 t.datetime "updated_at" end add_index "constituencies", ["ons_id"], :name => "index_constituencies_on_ons_id" create_table "emails", :force => true do |t| t.string "from" t.string "to" t.integer "last_send_attempt", :default => 0 t.text "mail" t.datetime "created_on" end create_table "manual_postcodes", :force => true do |t| t.string "code", :limit => 7 t.integer "constituency_id" - t.string "ons_id", :limit => 3 + t.string "ons_id", :limit => 20 t.datetime "created_at" t.datetime "updated_at" end add_index "manual_postcodes", ["code"], :name => "index_manual_postcodes_on_code" create_table "message_summaries", :force => true do |t| t.string "constituency_name" t.string "recipient" t.string "recipient_email" t.datetime "created_at" t.datetime "updated_at" t.date "sent_month" t.integer "count" end add_index "message_summaries", ["constituency_name"], :name => "index_message_summaries_on_constituency_name" add_index "message_summaries", ["recipient"], :name => "index_message_summaries_on_recipient" add_index "message_summaries", ["recipient_email"], :name => "index_message_summaries_on_recipient_email" add_index "message_summaries", ["sent_month"], :name => "index_message_summaries_on_sent_month" create_table "messages", :force => true do |t| t.string "constituency_id" t.string "sender_email" t.string "sender" t.string "recipient" t.string "address" t.string "postcode" t.string "subject" t.text "message" t.boolean "sent" t.datetime "created_at" t.datetime "updated_at" t.string "authenticity_token" t.string "recipient_email" t.boolean "sender_is_constituent" t.string "constituency_name" t.string "mailer_error" t.datetime "sent_at" t.string "sender_ip_address" end add_index "messages", ["sent"], :name => "index_messages_on_sent" add_index "messages", ["sent_at"], :name => "index_messages_on_sent_at" create_table "postcode_districts", :force => true do |t| t.string "district", :limit => 4 t.integer "constituency_id" end add_index "postcode_districts", ["district"], :name => "index_postcode_districts_on_district" create_table "postcodes", :force => true do |t| t.string "code", :limit => 7 t.integer "constituency_id" - t.string "ons_id", :limit => 3 + t.string "ons_id", :limit => 20 end add_index "postcodes", ["code"], :name => "index_postcodes_on_code" add_index "postcodes", ["constituency_id"], :name => "index_postcodes_on_constituency_id" add_index "postcodes", ["ons_id"], :name => "index_postcodes_on_ons_id" create_table "slugs", :force => true do |t| t.string "name" t.integer "sluggable_id" t.integer "sequence", :default => 1, :null => false t.string "sluggable_type", :limit => 40 t.string "scope", :limit => 40 t.datetime "created_at" end add_index "slugs", ["name", "sluggable_type", "scope", "sequence"], :name => "index_slugs_on_name_and_sluggable_type_and_scope_and_sequence", :unique => true add_index "slugs", ["sluggable_id"], :name => "index_slugs_on_sluggable_id" create_table "users", :force => true do |t| t.string "login" t.string "crypted_password" t.string "password_salt" t.string "persistence_token" t.integer "login_count" t.datetime "last_request_at" t.datetime "last_login_at" t.datetime "current_login_at" t.string "last_login_ip" t.string "current_login_ip" t.datetime "created_at" t.datetime "updated_at" t.string "perishable_token", :default => "", :null => false t.string "email", :default => "", :null => false t.boolean "admin", :default => false end add_index "users", ["email"], :name => "index_users_on_email" add_index "users", ["perishable_token"], :name => "index_users_on_perishable_token" end diff --git a/lib/data_loader.rb b/lib/data_loader.rb index 1f0f3fa..2e77c32 100644 --- a/lib/data_loader.rb +++ b/lib/data_loader.rb @@ -1,495 +1,512 @@ +#encoding: utf-8 + require File.expand_path(File.dirname(__FILE__) + '/timer') module FindYourMP; end module FindYourMP::DataLoader include FindYourMP::Timer DATA_DIR = File.expand_path(File.dirname(__FILE__) + '/../data') MEMBER_FILE = "#{DATA_DIR}/FYMP_all.txt" CONSTITUENCY_FILE = "#{DATA_DIR}/new_constituencies.txt" POSTCODE_FILE = "#{DATA_DIR}/postcodes.txt" def diff_ons_ids old_file, new_file unless File.exist?(old_file) raise "#{old_file} not found" end unless File.exist?(new_file) raise "#{new_file} not found" end diff_file = "#{DATA_DIR}/diff_ons_ids.txt" if File.exist?(diff_file) cmd = "mv #{diff_file} #{diff_file}.#{Time.now.to_i.to_s}" puts cmd `#{cmd}` end constituencies_by_id = {} constituencies_by_name = {} old_data = File.open(old_file) old_data.each do |line| line.gsub!("\n", "") parts = line.split("\t") constituencies_by_id[parts[0]] = parts[1].strip constituencies_by_name[parts[1]] = parts[0] end new_data = File.open(new_file) output = File.open(diff_file, 'w') new_data.each do |line| line.gsub!("\n", "") parts = line.split("\t") name = parts[1].strip unless constituencies_by_id.has_key?(parts[0]) unless constituencies_by_name.has_key?(name) name.gsub!("&", "and") end if constituencies_by_name.has_key?(name) correction = "#{constituencies_by_name[name]}\t#{parts[0]}\n" output.write(correction) end end end end def patch_postcodes new_data = "\n" + File.open("#{DATA_DIR}/new_postcodes.txt").read start_timing Postcode.find_all_by_ons_id("0").each do |postcode| search_code = postcode.code if postcode.code.length < 6 code = "#{postcode.code[0..postcode.code.length-4]} #{postcode.code[postcode.code.length-3..postcode.code.length]}" elsif postcode.code.length < 7 code = "#{postcode.code[0..postcode.code.length-4]} #{postcode.code[postcode.code.length-3..postcode.code.length]}" end match = new_data.match(/\n#{code} ([A-Z0-9]{3})/) if match ons_id = match.values_at(1).to_s constituency = Constituency.find_by_ons_id(ons_id) postcode.ons_id = ons_id postcode.constituency_id = constituency.id postcode.save! else warn "trouble matching #{postcode.code}" end end BlacklistedPostcode.find_all_by_ons_id("0").each do |postcode| search_code = postcode.code if postcode.code.length < 6 code = "#{postcode.code[0..postcode.code.length-4]} #{postcode.code[postcode.code.length-3..postcode.code.length]}" elsif postcode.code.length < 7 code = "#{postcode.code[0..postcode.code.length-4]} #{postcode.code[postcode.code.length-3..postcode.code.length]}" end match = new_data.match(/\n#{code} ([A-Z0-9]{3})/) if match ons_id = match.values_at(1).to_s postcode.delete Postcode.create! :code => postcode.code, :ons_id => ons_id else warn "trouble matching #{postcode.code}" end end log_duration end def diff_postcodes old_file, new_file unless File.exist?(old_file) raise "#{old_file} not found" end unless File.exist?(new_file) raise "#{new_file} not found" end old_postcodes = "#{DATA_DIR}/old_postcodes.txt" new_postcodes = "#{DATA_DIR}/new_postcodes.txt" parse_postcodes old_file, old_postcodes parse_postcodes new_file, new_postcodes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if File.exist?(diff_file) cmd = "mv #{diff_file} #{diff_file}.#{Time.now.to_i.to_s}" puts cmd `#{cmd}` end cmd = "diff #{old_postcodes} #{new_postcodes} > #{diff_file}" puts cmd `#{cmd}` end def patch_ons_ids patch_file = "#{DATA_DIR}/diff_ons_ids.txt" unless File.exist?(patch_file) raise "#{patch_file} not found" end start_timing data = File.open(patch_file) data.each do |line| line.gsub!("\n", "") parts = line.split("\t") - old_id = parts[0].strip - new_id = parts[1].strip + new_id = parts[0].strip + old_id = parts[1].strip ActiveRecord::Base.connection.execute("UPDATE blacklisted_postcodes SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") ActiveRecord::Base.connection.execute("UPDATE manual_postcodes SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") ActiveRecord::Base.connection.execute("UPDATE constituencies SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") + ActiveRecord::Base.connection.execute("UPDATE postcodes SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") end log_duration end def determine_postcode_changes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if file_not_found(diff_file) puts "Generate or upload #{diff_file}" return end to_delete = {} to_create = {} to_update = {} IO.foreach(diff_file) do |line| parts = line.strip.split(' ') indicator = parts[0] if indicator[/(<|>)/] ons_id = parts.pop postcode = parts.join(' ').sub(indicator, '').strip if indicator == '<' to_delete[postcode] = ons_id elsif indicator == '>' to_create[postcode] = ons_id end end end to_create.keys.each do |postcode| if to_delete.delete(postcode) ons_id = to_create.delete(postcode) to_update[postcode] = ons_id end end puts 'to_delete ' + to_delete.size.to_s + ' e.g. ' + to_delete.to_a.first.inspect puts 'to_update ' + to_update.size.to_s + ' e.g. ' + to_update.to_a.first.inspect puts 'to_create ' + to_create.size.to_s + ' e.g. ' + to_create.to_a.first.inspect puts 'checking we have constituencies... ' (to_update.values + to_create.values).flatten.uniq.each do |ons_id| unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) raise "unexpected constituency id #{ons_id}" unless constituency end end puts 'all constituencies found' return [to_delete, to_update, to_create] end def update_postcodes to_delete, to_update, to_create = determine_postcode_changes # puts "Update database? y/n" # answer = STDIN.gets # if answer.strip == 'y' do_postcode_update to_delete, to_update, to_create # else # puts 'exiting without database update' # end end def ignore_ons_id?(ons_id) - ons_id == '800' || ons_id == '900' + ons_id == 'M99999999' || ons_id == 'L99999999' || ons_id == '800' || ons_id == '900' end def analyze_postcode_update to_delete, to_update, to_create = determine_postcode_changes already_deleted = [] to_delete.each do |postcode, ons_id| already_deleted << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO DELETE, BUT ALREADY DELETED: #{already_deleted.size}" missing_updates = [] to_update.each do |postcode, ons_id| unless Postcode.exists?(:code => postcode.sub(' ','')) missing_updates << [postcode, ons_id] unless BlacklistedPostcode.exists?(:code => postcode.sub(' ','')) end end puts "TO UPDATE, BUT MISSING FROM DB: #{missing_updates.size}" already_there = [] to_create.each do |postcode, ons_id| if Postcode.exists?(:code => postcode.sub(' ','')) already_there << [postcode, ons_id] if ManualPostcode.exists?(:code => postcode.sub(' ','')) end end puts "TO CREATE, BUT ALREADY IN DB: #{already_there.size}" end def do_postcode_update to_delete, to_update, to_create puts 'do_postcode_update...' total = (to_delete.size + to_update.size + to_create.size).to_f count = 0 include ActionView::Helpers::DateHelper start_timing #process deletions to_delete.each do |postcode, ons_id| if post_code = Postcode.find_by_code(postcode.sub(' ','')) if ManualPostcode.find_by_code(postcode.sub(' ','')) warn "deleted postcode #{postcode}) exists as manual postcode" else post_code.destroy count = count.next log_duration count / total end else warn "cannot delete postcode, as it was not in database: #{postcode}" end end #process updates to_update.each do |postcode, ons_id| post_code = Postcode.find_by_code(postcode.sub(' ','')) if post_code unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) if constituency.nil? raise "cannot update postcode, as constituency was not in database: #{postcode} #{ons_id}" end end blacklisted = BlacklistedPostcode.find_by_code postcode.sub(' ','') if blacklisted puts " (deleting blacklisted postcode - #{postcode})" unless blacklisted.ons_id == ons_id blacklisted.delete end end post_code.ons_id = ons_id.strip if constituency post_code.constituency_id = constituency.id else post_code.constituency_id = nil end post_code.save count = count.next log_duration count / total else blacklisted = BlacklistedPostcode.find_by_code postcode.sub(' ', '') if blacklisted blacklisted.delete end constituency = Constituency.find_by_ons_id(ons_id) Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id, :constituency_id => constituency.id end end #process new postcodes to_create.each do |postcode, ons_id| unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) if constituency.nil? raise "cannot create postcode, as constituency was not in database: #{postcode} #{ons_id}" end begin if Postcode.exists?(:code => postcode.sub(' ','')) warn 'exists: ' + postcode elsif BlacklistedPostcode.find_by_code postcode.sub(' ','') warn 'exists (and blacklisted): ' + postcode else manual = ManualPostcode.find_by_code postcode.sub(' ', '') if manual manual.delete end constituency = Constituency.find_by_ons_id(ons_id) Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id, :constituency_id => constituency.id end rescue Exception => e raise e end end count = count.next log_duration count / total end log_duration end def load_members member_file member_file = MEMBER_FILE unless member_file return if file_not_found(member_file) lines = [] IO.foreach(member_file) do |line| line.strip! lines << line unless(line.blank? || line[/Constituency/]) end lines.each do |line| begin parts = line.split("\t") constituency_name = parts[0].strip member_name = parts[1].strip if is_vacant?(member_name) log "Constituency is vacant: #{constituency_name}" else existing, updated_constituency = Constituency.load_tsv_line(line) if existing && updated_constituency existing.attributes = updated_constituency.attributes existing.save! elsif updated_constituency log "Cannot find constituency for member for line: #{line}" else # nothing to update end end rescue Exception => e log "Cannot set member_name on constituency for: #{line} | #{e.to_s}" end end end def load_constituencies return if file_not_found(CONSTITUENCY_FILE) Constituency.delete_all Slug.delete_all IO.foreach(CONSTITUENCY_FILE) do |line| constituency_id = line[0..2] constituency_name = line[3..(line.length-1)].strip Constituency.create :name=>constituency_name, :ons_id=>constituency_id end end def parse_postcodes source_file, output_file=POSTCODE_FILE return if file_not_found(source_file) start_timing blank_date = ' ' blank_code = ' ' new_line = "\n" space = ' ' post_codes = [] - + IO.foreach(source_file) do |line| termination_date = line[29..34] if termination_date == blank_date - consistuency_code = line[69..71] - unless consistuency_code == blank_code - post_code = line[0..6] + consistuency_code = line[114..122] + unless consistuency_code.strip == "" + post_code = line[0..6].gsub(" ", "") post_codes << post_code << space << consistuency_code post_codes << new_line end end end log_duration start_timing File.open(output_file,'w') do |file| file.write(post_codes.join('')) end log_duration end def load_postcodes group_size=1000 return if file_not_found(POSTCODE_FILE) index = 0 groups = 0 puts 'saving data to db' Postcode.delete_all columns = [:code, :constituency_id] total = `cat #{POSTCODE_FILE} | wc -l` total = total.strip.to_f include ActionView::Helpers::DateHelper post_codes = [] start_timing IO.foreach(POSTCODE_FILE) do |line| code = line[0..6].tr(' ','') constituency_id = line[8..10] post_codes << [code, constituency_id] index = index.next if (index % group_size) == 0 load_codes(post_codes) groups = groups.next percentage_complete = (group_size * groups) / total log_duration percentage_complete post_codes = [] end end # complete remaining load_codes(post_codes) log_duration 1.0 end def load_postcode_districts PostcodeDistrict.delete_all sql = "SELECT SUBSTRING(code, 1, LENGTH(code)-3) " + "AS district, constituency_id " + "FROM postcodes " + "GROUP BY district, constituency_id;" districts = PostcodeDistrict.find_by_sql(sql) districts.each do |district| PostcodeDistrict.create!(district.attributes) end end def load_manual_postcodes manual_codes = ManualPostcode.all manual_codes.each do |manual_code| Postcode.create :code => manual_code.code, :constituency_id => manual_code.constituency_id, :ons_id => manual_code.ons_id end end + def output_current_postcodes_file output_file="./data/postcodes_current.txt" + output = [] + start_timing + Postcode.find_in_batches do |batch| + batch.each do |postcode| + output << "#{postcode.code.gsub(' ', '')} #{postcode.ons_id}" + end + end + File.open(output_file, "w") do |file| + file.write(output.join("\n")) + end + log_duration + end + private def load_codes(post_codes) post_codes.each do |codes| if BlacklistedPostcode.find_by_code codes[0] puts " (ignoring blacklisted postcode - #{codes[0]})" else Postcode.create :code => codes[0], :ons_id => codes[1] end end end def is_vacant?(name) name == 'Vacant' end def log msg $stderr.puts msg end def file_not_found file_name if File.exist?(file_name) false else log "Data file not found: #{file_name}" true end end end diff --git a/lib/tasks/parse.rake b/lib/tasks/parse.rake index 4a05838..7d43082 100644 --- a/lib/tasks/parse.rake +++ b/lib/tasks/parse.rake @@ -1,115 +1,119 @@ require File.expand_path(File.dirname(__FILE__) + '/../data_loader') require File.expand_path(File.dirname(__FILE__) + '/../commons_member_biographies') require File.expand_path(File.dirname(__FILE__) + '/../cache_writer') require File.expand_path(File.dirname(__FILE__) + '/../constituency_upmystreet_links') require File.expand_path(File.dirname(__FILE__) + '/../boundary_changes') namespace :fymp do include FindYourMP::DataLoader include FindYourMP::CacheWriter include FindYourMP::BoundaryChanges desc "Create new_constituencies file for boundary changes" task :create_new_constituencies_file => :environment do create_new_constituencies_file end desc "Populate data for constituencies in DB" task :constituencies => :environment do load_constituencies end desc "Populate data for members in DB" task :members => :environment do file = ENV['file'] load_members file end desc "Create cache of all postcode pages" task :make_cache => :environment do make_cache end desc "Parse data file for postcode and constituency ID *only*" task :parse_postcodes do source_file = ENV['source'] if source_file parse_postcodes source_file else puts 'USAGE: rake fymp:parse_postcodes source=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end desc "Parse data file for postcode and constituency ID *only*" task :parse_new_postcodes do old_file = ENV['oldfile'] new_file = ENV['newfile'] output_file = ENV['output'] if old_file && new_file parse_new_postcodes old_file, new_file, output_file else puts 'USAGE: rake fymp:parse_new_postcodes oldfile=data/postcodes.txt newfile=data/pcd_pcon_aug_2009_uk_lu/pcd_pcon_aug_2009_uk_lu.txt output=data/new_postcodes.txt' end end task :diff_ons_ids => :environment do old_file = ENV['old'] new_file = ENV['new'] if old_file && new_file diff_ons_ids old_file, new_file else puts 'USAGE: rake fymp:diff_ons_ids old=data/constituencies.txt new=data/new_constituencies.txt' end end task :patch_ons_ids => :environment do patch_ons_ids end + + task :dump_postcodes_to_file => :environment do + output_current_postcodes_file + end desc "Update postcodes from data files for postcode and constituency ID *only*" task :diff_postcodes => :environment do old_file = ENV['old'] new_file = ENV['new'] if old_file && new_file diff_postcodes old_file, new_file else puts 'USAGE: rake fymp:diff_postcodes old=data/NSPDF_FEB_2009_UK_1M.txt new=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end desc "Only analyze potential postcode update and log db discrepancies" task :analyze_postcode_update => :environment do analyze_postcode_update end task :patch_postcodes => :environment do patch_postcodes end desc "Update postcodes from data files for postcode and constituency ID *only*" task :update_postcodes => :environment do puts 'USAGE: rake fymp:update_postcodes' update_postcodes end desc "Populate data for postcode and constituency ID in DB" task :populate => :environment do load_postcodes end desc "Populate the postcode districts table" task :load_postcode_districts => :environment do load_postcode_districts end desc "Populate the manually added postcodes" task :load_manual_postcodes => :environment do load_manual_postcodes end desc "Populate the upmystreet lookup table" task :load_upmystreet_lookup => :environment do load_upmystreetcodes end end
robertbrook/findyourmp
ade581f6b2e59478ad942453fd808677de549b76
skip not ski
diff --git a/lib/s3uploader.rb b/lib/s3uploader.rb index ca3a72c..474af2d 100644 --- a/lib/s3uploader.rb +++ b/lib/s3uploader.rb @@ -1,174 +1,174 @@ require File.expand_path(File.dirname(__FILE__) + '/encryption') require 'aws/s3' module FindYourMP; end module FindYourMP::S3Uploader include FindYourMP::Encryption def call_cleanup(max_size) s3_conf = "#{RAILS_ROOT}/config/s3.yml" unless File.exist?(s3_conf) raise "Error, config file not found" end s3_config = File.open(s3_conf) s3_options = YAML.load(s3_config) cleanup_files(s3_options[:bucket_name], s3_options[:bucket_key], s3_options[:bucket_secret], max_size) end def db_backup(path, env) if path.last == "/" path = path.chop end s3_conf = "#{RAILS_ROOT}/config/s3.yml" unless File.exist?(s3_conf) raise "Error, config file not found" end s3_config = File.open(s3_conf) s3_options = YAML.load(s3_config) t = Time.now datetime = t.strftime("%Y%m%d%H%M%S") outfile = "#{path}/findyourmp_#{datetime}.bak" puts "" puts "backing up database to #{outfile} ..." unless s3_options[:db_password].blank? - system("mysqldump --user=#{s3_options[:db_user]} --password=#{s3_options[:db_password]} --opt --quote-names --ski-set-charset --default-character-set=latin1 findyourmp_#{env} > #{outfile}") + system("mysqldump --user=#{s3_options[:db_user]} --password=#{s3_options[:db_password]} --opt --quote-names --skip-set-charset --default-character-set=latin1 findyourmp_#{env} > #{outfile}") else system("mysqldump --user=#{s3_options[:db_user]} --opt --quote-names --skip-set-charset --default-character-set=latin1 findyourmp_#{env} > #{outfile}") end puts "" return outfile end def send_backup(backup_file) unless File.exist?(backup_file) raise "Error, file to be backed up does not exist" end backup_path = "#{RAILS_ROOT}/db/backup" s3_conf = "#{RAILS_ROOT}/config/s3.yml" pem_file = "#{RAILS_ROOT}/config/fymp-public.pem" unless File.exist?(pem_file) raise "Error, public key not found - cannot encrypt backup data" end unless File.exist?(s3_conf) raise "Error, config file not found" end s3_config = File.open(s3_conf) s3_options = YAML.load(s3_config) system("cp #{backup_file} #{backup_path}") backup_file_path = File.dirname(backup_file) backup_file_name = backup_file.gsub(backup_file_path + '/', '') t = Time.now datetime = t.strftime("%Y%m%d%H%M%S") outfile = "#{backup_path}/findyourmp_#{datetime}_s3.bak" compressed_file = "#{backup_path}/findyourmp_#{datetime}_s3.zip" puts "Compressing backup file" system("tar -C #{backup_path} -cvzf #{compressed_file} #{backup_file_name}") puts "" puts "Encrypting file..." puts "#{outfile}" encrypt_file(compressed_file, outfile, s3_options[:alg], pem_file) puts "" data_file_name = "findyourmp_#{datetime}_s3.bak" send_file_name = data_file_name.gsub('.bak', '.tar.gz') key_file_name = data_file_name.gsub('.bak', '_key.txt') iv_file_name = data_file_name.gsub('.bak', '_iv.txt') puts "Zipping files..." system("tar -C #{backup_path} -cvzf #{backup_path}/#{send_file_name} #{data_file_name} #{key_file_name} #{iv_file_name}") puts "" puts "Deleting temporary files..." system("rm #{backup_path}/#{data_file_name}; rm #{backup_path}/#{key_file_name}; rm #{backup_path}/#{iv_file_name}; rm #{backup_path}/#{backup_file}; rm #{compressed_file}") puts "" puts "Uploading to S3..." upload_file("#{backup_path}/#{send_file_name}", s3_options[:bucket_name], s3_options[:bucket_key], s3_options[:bucket_secret]) puts "" puts "Deleting backup file..." system("rm #{backup_path}/#{send_file_name}") puts "" puts "Done!" end def decrypt_data(input) pem_file = "#{RAILS_ROOT}/config/fymp-private.pem" s3_conf = "#{RAILS_ROOT}/config/s3.yml" unless File.exist?(pem_file) raise "Error, private key not found - cannot decrypt the data" end unless File.exist?(s3_conf) raise "Error, config file not found" end s3_config = File.open(s3_conf) s3_options = YAML.load(s3_config) alg = s3_options[:alg] pass = s3_options[:password] output = input + ".decrypted.tar.gz" decrypt_file(input, output, alg, pass, pem_file) return output end def upload_file(file, bucket, key, secret) AWS::S3::Base.establish_connection!( :access_key_id => key, :secret_access_key => secret ) stored_file_path = File.dirname(file) stored_file = file.gsub(stored_file_path + '/', '') AWS::S3::S3Object.store(stored_file, open(file), bucket) end def cleanup_files(bucket, key, secret, max_size) AWS::S3::Base.establish_connection!( :access_key_id => key, :secret_access_key => secret ) backup_store = AWS::S3::Bucket.find(bucket) current_size = backup_store.objects.size max_size = max_size.to_i if current_size > max_size files = [] backup_store.each do |object| files << object.key end files.sort! files.reverse! while files.size > max_size AWS::S3::S3Object.delete files.last, bucket files.pop end end end end \ No newline at end of file
robertbrook/findyourmp
2c6c3e0620894689f3b6ab60d58454d68b5c838b
using utf8-safe version of mysqldump command
diff --git a/lib/s3uploader.rb b/lib/s3uploader.rb index c4087c6..ca3a72c 100644 --- a/lib/s3uploader.rb +++ b/lib/s3uploader.rb @@ -1,174 +1,174 @@ require File.expand_path(File.dirname(__FILE__) + '/encryption') require 'aws/s3' module FindYourMP; end module FindYourMP::S3Uploader include FindYourMP::Encryption def call_cleanup(max_size) s3_conf = "#{RAILS_ROOT}/config/s3.yml" unless File.exist?(s3_conf) raise "Error, config file not found" end s3_config = File.open(s3_conf) s3_options = YAML.load(s3_config) cleanup_files(s3_options[:bucket_name], s3_options[:bucket_key], s3_options[:bucket_secret], max_size) end def db_backup(path, env) if path.last == "/" path = path.chop end s3_conf = "#{RAILS_ROOT}/config/s3.yml" unless File.exist?(s3_conf) raise "Error, config file not found" end s3_config = File.open(s3_conf) s3_options = YAML.load(s3_config) t = Time.now datetime = t.strftime("%Y%m%d%H%M%S") outfile = "#{path}/findyourmp_#{datetime}.bak" puts "" puts "backing up database to #{outfile} ..." unless s3_options[:db_password].blank? - system("mysqldump findyourmp_#{env} --user=#{s3_options[:db_user]} --password=#{s3_options[:db_password]} > #{outfile}") + system("mysqldump --user=#{s3_options[:db_user]} --password=#{s3_options[:db_password]} --opt --quote-names --ski-set-charset --default-character-set=latin1 findyourmp_#{env} > #{outfile}") else - system("mysqldump findyourmp_#{env} --user=#{s3_options[:db_user]} > #{outfile}") + system("mysqldump --user=#{s3_options[:db_user]} --opt --quote-names --skip-set-charset --default-character-set=latin1 findyourmp_#{env} > #{outfile}") end puts "" return outfile end def send_backup(backup_file) unless File.exist?(backup_file) raise "Error, file to be backed up does not exist" end backup_path = "#{RAILS_ROOT}/db/backup" s3_conf = "#{RAILS_ROOT}/config/s3.yml" pem_file = "#{RAILS_ROOT}/config/fymp-public.pem" unless File.exist?(pem_file) raise "Error, public key not found - cannot encrypt backup data" end unless File.exist?(s3_conf) raise "Error, config file not found" end s3_config = File.open(s3_conf) s3_options = YAML.load(s3_config) system("cp #{backup_file} #{backup_path}") backup_file_path = File.dirname(backup_file) backup_file_name = backup_file.gsub(backup_file_path + '/', '') t = Time.now datetime = t.strftime("%Y%m%d%H%M%S") outfile = "#{backup_path}/findyourmp_#{datetime}_s3.bak" compressed_file = "#{backup_path}/findyourmp_#{datetime}_s3.zip" puts "Compressing backup file" system("tar -C #{backup_path} -cvzf #{compressed_file} #{backup_file_name}") puts "" puts "Encrypting file..." puts "#{outfile}" encrypt_file(compressed_file, outfile, s3_options[:alg], pem_file) puts "" data_file_name = "findyourmp_#{datetime}_s3.bak" send_file_name = data_file_name.gsub('.bak', '.tar.gz') key_file_name = data_file_name.gsub('.bak', '_key.txt') iv_file_name = data_file_name.gsub('.bak', '_iv.txt') puts "Zipping files..." system("tar -C #{backup_path} -cvzf #{backup_path}/#{send_file_name} #{data_file_name} #{key_file_name} #{iv_file_name}") puts "" puts "Deleting temporary files..." system("rm #{backup_path}/#{data_file_name}; rm #{backup_path}/#{key_file_name}; rm #{backup_path}/#{iv_file_name}; rm #{backup_path}/#{backup_file}; rm #{compressed_file}") puts "" puts "Uploading to S3..." upload_file("#{backup_path}/#{send_file_name}", s3_options[:bucket_name], s3_options[:bucket_key], s3_options[:bucket_secret]) puts "" puts "Deleting backup file..." system("rm #{backup_path}/#{send_file_name}") puts "" puts "Done!" end def decrypt_data(input) pem_file = "#{RAILS_ROOT}/config/fymp-private.pem" s3_conf = "#{RAILS_ROOT}/config/s3.yml" unless File.exist?(pem_file) raise "Error, private key not found - cannot decrypt the data" end unless File.exist?(s3_conf) raise "Error, config file not found" end s3_config = File.open(s3_conf) s3_options = YAML.load(s3_config) alg = s3_options[:alg] pass = s3_options[:password] output = input + ".decrypted.tar.gz" decrypt_file(input, output, alg, pass, pem_file) return output end def upload_file(file, bucket, key, secret) AWS::S3::Base.establish_connection!( :access_key_id => key, :secret_access_key => secret ) stored_file_path = File.dirname(file) stored_file = file.gsub(stored_file_path + '/', '') AWS::S3::S3Object.store(stored_file, open(file), bucket) end def cleanup_files(bucket, key, secret, max_size) AWS::S3::Base.establish_connection!( :access_key_id => key, :secret_access_key => secret ) backup_store = AWS::S3::Bucket.find(bucket) current_size = backup_store.objects.size max_size = max_size.to_i if current_size > max_size files = [] backup_store.each do |object| files << object.key end files.sort! files.reverse! while files.size > max_size AWS::S3::S3Object.delete files.last, bucket files.pop end end end end \ No newline at end of file
robertbrook/findyourmp
048d4d7b764c839378ff00373fc6063b34484f59
adding database.example.yml file
diff --git a/config/database.example.yml b/config/database.example.yml new file mode 100644 index 0000000..b42d2f9 --- /dev/null +++ b/config/database.example.yml @@ -0,0 +1,21 @@ +development: + adapter: mysql + database: findyourmp_development + username: root + password: + socket: /tmp/mysql.sock + +test: + adapter: mysql + database: findyourmp_test + username: root + password: + socket: /tmp/mysql.sock + + +production: + adapter: mysql + database: findyourmp_production + username: root + password: + socket: /tmp/mysql.sock \ No newline at end of file
robertbrook/findyourmp
da28a489550c970957570daf40928899307cda76
fix for member website displaying as NULL issue
diff --git a/app/views/constituencies/_member.haml b/app/views/constituencies/_member.haml index 81dc6f3..a986c53 100644 --- a/app/views/constituencies/_member.haml +++ b/app/views/constituencies/_member.haml @@ -1,25 +1,25 @@ .text - if @constituency.no_sitting_member? %p There is no sitting Member of Parliament for this constituency. - else - member_name = h(@constituency.member_name) .row_item .row_label Member for this constituency .row_value - if @constituency.member_biography_url? = link_to member_name, @constituency.member_biography_url - else = member_name .row_item .row_label Party .row_value= h(@constituency.member_party) - - if @constituency.member_website? + - if @constituency.member_website? and @constituency.member_website.strip != "NULL" .row_item .row_label Website .row_value = link_to @constituency.member_website - if @constituency.member_biography_url? %p %br = link_to "More information about #{member_name} MP", @constituency.member_biography_url
robertbrook/findyourmp
9257cb34dfebb32b574b6235220f00a4fb769725
moved to Bundler/Gemfile rather than vendor/plugins and git submodule; unfrozen Rails
diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index a9a4869..0000000 --- a/.gitmodules +++ /dev/null @@ -1,30 +0,0 @@ -[submodule "vendor/rails"] - path = vendor/rails - url = git://github.com/rails/rails.git -[submodule "vendor/plugins/haml"] - path = vendor/plugins/haml - url = git://github.com/nex3/haml.git -[submodule "vendor/plugins/rspec_rails"] - path = vendor/plugins/rspec_rails - url = git://github.com/dchelimsky/rspec-rails.git -[submodule "vendor/plugins/rspec"] - path = vendor/plugins/rspec - url = git://github.com/dchelimsky/rspec.git -[submodule "vendor/plugins/resource_controller"] - path = vendor/plugins/resource_controller - url = git://github.com/giraffesoft/resource_controller.git -[submodule "vendor/plugins/cucumber"] - path = vendor/plugins/cucumber - url = git://github.com/cucumber/cucumber.git -[submodule "vendor/plugins/webrat"] - path = vendor/plugins/webrat - url = git://github.com/brynary/webrat.git -[submodule "vendor/plugins/friendly_id"] - path = vendor/plugins/friendly_id - url = git://github.com/norman/friendly_id.git -[submodule "vendor/plugins/authlogic"] - path = vendor/plugins/authlogic - url = git://github.com/binarylogic/authlogic.git -[submodule "vendor/plugins/xss_terminate"] - path = vendor/plugins/xss_terminate - url = git://github.com/look/xss_terminate.git diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..31de716 --- /dev/null +++ b/Gemfile @@ -0,0 +1,21 @@ +source "http://rubygems.org" + +gem 'rake' +gem 'rails', '2.3.17' +gem 'rdoc' +gem 'haml', '3.1.8' +gem 'authlogic', '1.4.1' +gem 'friendly_id', '2.3.4' +gem 'xss_terminate' +gem 'hpricot' +gem 'aws-s3', '0.5.1' +gem 'mysql', '2.8.1' +gem 'unicode' +gem 'resource_controller' + +group :test do + gem 'webrat' + gem 'rspec', '1.3.2' + gem 'rspec-rails', '1.3.2' + gem 'cucumber-rails' +end \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..03d87bb --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,127 @@ +GEM + remote: http://rubygems.org/ + specs: + actionmailer (2.3.17) + actionpack (= 2.3.17) + actionpack (2.3.17) + activesupport (= 2.3.17) + rack (~> 1.1.0) + activerecord (2.3.17) + activesupport (= 2.3.17) + activeresource (2.3.17) + activesupport (= 2.3.17) + activesupport (2.3.17) + allison (2.0.3) + authlogic (1.4.1) + activesupport + echoe + echoe + aws-s3 (0.5.1) + builder + mime-types + xml-simple + builder (3.2.0) + capybara (2.0.2) + mime-types (>= 1.16) + nokogiri (>= 1.3.3) + rack (>= 1.0.0) + rack-test (>= 0.5.4) + selenium-webdriver (~> 2.0) + xpath (~> 1.0.0) + chardet (0.9.0) + childprocess (0.3.9) + ffi (~> 1.0, >= 1.0.11) + cucumber (1.2.3) + builder (>= 2.1.2) + diff-lcs (>= 1.1.3) + gherkin (~> 2.11.6) + multi_json (~> 1.3) + cucumber-rails (1.3.0) + capybara (>= 1.1.2) + cucumber (>= 1.1.8) + nokogiri (>= 1.5.0) + diff-lcs (1.2.1) + echoe (4.6.3) + allison (>= 2.0.3) + gemcutter (>= 0.7.0) + rake (>= 0.9.2) + rdoc (>= 3.6.1) + rubyforge (>= 2.0.4) + ffi (1.4.0) + friendly_id (2.3.4) + activerecord (>= 2.2) + activesupport (>= 2.2) + gemcutter (0.7.1) + gherkin (2.11.6) + json (>= 1.7.6) + haml (3.1.8) + hoe (3.5.1) + rake (>= 0.8, < 11.0) + hpricot (0.8.6) + html5 (0.10.0) + chardet (>= 0.9.0) + hoe (>= 1.2.0) + json (1.7.7) + json_pure (1.7.7) + mime-types (1.21) + multi_json (1.6.1) + mysql (2.8.1) + nokogiri (1.5.6) + rack (1.1.6) + rack-test (0.6.2) + rack (>= 1.0) + rails (2.3.17) + actionmailer (= 2.3.17) + actionpack (= 2.3.17) + activerecord (= 2.3.17) + activeresource (= 2.3.17) + activesupport (= 2.3.17) + rake (>= 0.8.3) + rake (10.0.3) + rdoc (4.0.0) + json (~> 1.4) + resource_controller (0.6.6) + rspec (1.3.2) + rspec-rails (1.3.2) + rack (>= 1.0.0) + rspec (>= 1.3.0) + rubyforge (2.0.4) + json_pure (>= 1.1.7) + rubyzip (0.9.9) + selenium-webdriver (2.31.0) + childprocess (>= 0.2.5) + multi_json (~> 1.0) + rubyzip + websocket (~> 1.0.4) + unicode (0.4.4) + webrat (0.7.3) + nokogiri (>= 1.2.0) + rack (>= 1.0) + rack-test (>= 0.5.3) + websocket (1.0.7) + xml-simple (1.1.2) + xpath (1.0.0) + nokogiri (~> 1.3) + xss_terminate (0.2) + html5 (>= 0.10.0) + +PLATFORMS + ruby + +DEPENDENCIES + authlogic (= 1.4.1) + aws-s3 (= 0.5.1) + cucumber-rails + friendly_id (= 2.3.4) + haml (= 3.1.8) + hpricot + mysql (= 2.8.1) + rails (= 2.3.17) + rake + rdoc + resource_controller + rspec (= 1.3.2) + rspec-rails (= 1.3.2) + unicode + webrat + xss_terminate diff --git a/README b/README deleted file mode 100644 index f2dbd5c..0000000 --- a/README +++ /dev/null @@ -1,39 +0,0 @@ -sudo mysqladmin create findyourmp_test -sudo mysqladmin create findyourmp_development -sudo mysqladmin create findyourmp_production - -git pull - -git submodule init - -git submodule update - -mv config/database.yml.example config/database.yml - -sudo gem install unicode - -rake db:migrate:reset - -# the steps below requires data which is not in git repository -# files need to end up in the /data directory - -rake fymp:constituencies -rake fymp:members - -rake fymp:parse -rake fymp:populate - -rake fymp:load_postcode_districts - -rake friendly_id:make_slugs MODEL=Constituency - -# To get the emergency server shutdown to work, you need to run the following... -# -# sudo visudo -# -# ...and add in the next 2 lines, substituting [SITE_CONTEXT_USER] with the actual user or group the site runs as -# -# Cmnd_Alias APACHE = /etc/init.d/apache2 start, /etc/init.d/apache2 stop, /etc/init.d/apache2 restart, /etc/init.d/apache2 reload -# [SITE_CONTEXT_USER] ALL=NOPASSWD: APACHE - - diff --git a/README.md b/README.md new file mode 100644 index 0000000..ecee087 --- /dev/null +++ b/README.md @@ -0,0 +1,69 @@ +## Installation + +clone the repository + +create your database.yml file using the supplied example + + cp config/database.yml.example config/database.yml + +run the rake tasks to create the database + + rake db:create:all + rake db:migrate:reset RAILS_ENV=xxx + +restore the data from a recent database dump or use the rake tasks to load the data from files (not included as part of the repository - to big, would infringe copyright, would be a job in its own right keeping this updated.) + +### load constituency data + + rake fymp:constituencies RAILS_ENV=xxx + +expects a TSV formatted file consisting of + ID, constituency name +as `data/new_constituencies.txt` + +### load the member data + + rake fymp:members RAILS_ENV=xxx + +expects a TSV formatted file consisting of + consituency name, mp name (party) +as `data/FYMP_all.txt` (unless another file name is specified using file= on the command line) + +### prepare the postcode data for loading + +Creates postcodes.txt. If you already have a `data/postcodes.txt` that looks promising DO NOT RUN THIS STEP, otherwise go make a cup of tea; this bit isn't quick. + + rake fymp:parse RAILS_ENV=xxx source_file=xxx + +expects the sort of file one would expect to pay ONS a recurring subscription fee to receive (plaintext version) + +### load the postcode data + +Definitely cup of tea time, consider renting a movie, maybe 2. Takes the simplified postcode data from `data/postcodes.txt` - still millions of records but just the bits we actually want from the massive file - and loads them into the database. Takes hours (on my MacBook Pro, I'm getting a 4 hour estimate). + + rake fymp:populate RAILS_ENV=xx + +### set up the postcode districts + +Runs some SQL against the postcodes table in order to populate the postcode districts information. Reasonably fast. + + rake fymp:load_postcode_districts RAILS_ENV=xx + + +### set up us the constituency slugs + +Invoke the power of the `friendly_id` gem to create nice url slugs for the constituencies + + rake friendly_id:make_slugs MODEL=Constituency RAILS_ENV=xx + + +## Maintenance notes (copied verbatim from original README, not tested) + +To get the emergency server shutdown to work, you need to run the following... + + sudo visudo + +...and add in the next 2 lines, substituting [SITE_CONTEXT_USER] with the actual user or group the site runs as + + Cmnd_Alias APACHE = /etc/init.d/apache2 start, /etc/init.d/apache2 stop, /etc/init.d/apache2 restart, /etc/init.d/apache2 reload` + [SITE_CONTEXT_USER] ALL=NOPASSWD: APACHE \ No newline at end of file diff --git a/Rakefile b/Rakefile index 3bb0e85..dad956e 100644 --- a/Rakefile +++ b/Rakefile @@ -1,10 +1,10 @@ # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require(File.join(File.dirname(__FILE__), 'config', 'boot')) require 'rake' require 'rake/testtask' -require 'rake/rdoctask' +require 'rdoc/task' -require 'tasks/rails' +require 'tasks/rails' \ No newline at end of file diff --git a/app/models/constituency.rb b/app/models/constituency.rb index 68cd8be..5cd90eb 100755 --- a/app/models/constituency.rb +++ b/app/models/constituency.rb @@ -1,213 +1,213 @@ class Constituency < ActiveRecord::Base include ActionController::UrlWriter - has_friendly_id :name, :use_slug => true, :strip_diacritics => true + has_friendly_id :name, :use_slug => true, :approximate_ascii => true has_many :postcodes has_many :postcode_districts has_many :messages validate :valid_email? class << self def all_constituencies all.select{|c| c.name != 'Example'} end def remove_quotes text unless text text = "" end text.strip[/^"?([^"]+)"?$/,1] end def load_tsv_line line parts = line.split("\t") constituency_name = remove_quotes(parts[0]) member_name = remove_quotes(parts[1]) member_party = remove_quotes(parts[2]) member_bio_url = remove_quotes(parts[3]) member_contact = remove_quotes(parts[4]) member_website = remove_quotes(parts[5]) member_contact = "" unless member_contact existing = Constituency.find_by_constituency_name(constituency_name) new_constituency = nil if existing non_matching = (existing.member_name != member_name || existing.member_party != member_party || existing.member_biography_url != member_bio_url) non_matching = non_matching || ( member_contact[/http:\/\//] ? (existing.member_requested_contact_url.to_s.strip != member_contact.to_s.strip) : (existing.member_email.to_s.strip != member_contact.to_s.strip) ) if non_matching new_constituency = Constituency.new(existing.attributes) new_constituency.member_name = member_name new_constituency.member_party = member_party new_constituency.member_biography_url = member_bio_url if member_contact[/http:\/\//] new_constituency.member_requested_contact_url = member_contact else new_constituency.member_email = member_contact.chomp('.') end new_constituency.member_website = member_website end [existing, new_constituency] else [nil, nil] end end def find_all_constituency_and_member_matches term term = term.squeeze(' ').gsub('"','') constituencies = Constituency.find_all_name_or_member_name_matches(term) members = constituencies.clone if term[/[A-Z][a-z].*/] constituencies = constituencies.select { |c| c.name.include? term } members = members.select { |c| c.member_name.include? term } else constituencies = constituencies.select { |c| c.name.downcase.include? term.downcase } members = members.select { |c| c.member_name? && c.member_name.downcase.include?(term.downcase) } end constituencies = constituencies.sort_by(&:name) members = members.sort_by(&:member_name) return [constituencies, members] end def find_all_name_or_member_name_matches term term = term.squeeze(' ').gsub('"','') matches_name_or_member_name = %Q|name like "%#{term}%" or | + %Q|(member_name like "%#{term}%" and member_visible = 1)| constituencies = find(:all, :conditions => matches_name_or_member_name) constituencies.delete_if{|c| c.name == 'Example'} if case_sensitive(term) constituencies.delete_if do |c| !c.name.include?(term) && !c.member_name.include?(term) end end constituencies end def case_sensitive term term.gsub('"','')[/^([A-Z][a-z]+[ ]+)*([A-Z][a-z]+)$/] ? true : false end def find_by_constituency_name name name.gsub!(' - ','-') if name[/^(.+), City of$/] name = "City of #{$1}" end constituency = find_by_name(name) unless constituency name.gsub!('&', 'and') if name == "Regent's Park and Kensington North" name = "Regent's Park and North Kensington" end if name[/^(.+), The$/] name = "The #{$1}" end name.tr!('-', ' ') name.gsub!('ô','o') name.gsub!('and#244;', 'o') constituency = find_by_name(name) end unless constituency name.gsub!('St ', 'St. ') constituency = find_by_name(name) end unless constituency puts "" puts "not found: #{name}" end constituency end end def show_message_form? member_name? && member_email? && !member_requested_contact_url? end def code if ons_id.nil? '' elsif ons_id.length == 1 "00#{ons_id}" elsif ons_id.length == 2 "0#{ons_id}" else ons_id.to_s end end def no_sitting_member? (!member_name?) || (!member_visible) end def to_tsv_line %Q|"#{name}"\t"#{member_name}"\t"#{member_party}"\t"#{member_biography_url}"\t"#{member_email}"\t"#{member_website}"| end def to_json host, port if no_sitting_member? %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "No sitting member", "member_party": "", "member_biography_url": "", "member_website": "", "uri": "#{object_url(host, port, "json")}" } }| else %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "#{member_name}", "member_party": "#{member_party}", "member_biography_url": "#{member_biography_url}", "member_website": "#{member_website}", "uri": "#{object_url(host, port, "json")}" } }| end end def to_text host, port, format="txt" if no_sitting_member? %Q|constituency_name: #{name}\nmember_name: No sitting member\nmember_party: \nmember_biography_url: \nmember_website: \nuri: #{object_url(host, port, format)}| else %Q|constituency_name: #{name}\nmember_name: #{member_name}\nmember_party: #{member_party}\nmember_biography_url: #{member_biography_url}\nmember_website: #{member_website}\nuri: #{object_url(host, port, format)}| end end def to_csv host, port headers = 'constituency_name,member_name,member_party,member_biography_url,member_website,uri' values = to_csv_value(host, port) "#{headers}\n#{values}\n" end def to_csv_value host, port if no_sitting_member? %Q|"#{name}","No sitting member","","","","#{object_url(host, port, format, "csv")}"| else %Q|"#{name}","#{member_name}","#{member_party}","#{member_biography_url}","#{member_website}","#{object_url(host, port, "csv")}"| end end def to_output_yaml host, port "---\n#{to_text(host, port, "yaml")}" end def member_attribute_changed? attribute, constituency send(attribute).to_s.strip != constituency.send(attribute).to_s.strip end private def valid_email? unless member_email.blank? begin self.member_email = MessageMailer.parse_email(member_email).address rescue errors.add_to_base("Member email must be a valid email") end end end def object_url host, port, format=nil if port.to_s == "80" url_for :host=> host, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false else url_for :host=> host, :port=> port, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false end end end diff --git a/config/boot.rb b/config/boot.rb index 0ad0f78..0b08940 100644 --- a/config/boot.rb +++ b/config/boot.rb @@ -1,110 +1,116 @@ # Don't change this file! # Configure your app in config/environment.rb and config/environments/*.rb RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT) module Rails class << self def boot! unless booted? preinitialize pick_boot.run end end def booted? defined? Rails::Initializer end def pick_boot (vendor_rails? ? VendorBoot : GemBoot).new end def vendor_rails? File.exist?("#{RAILS_ROOT}/vendor/rails") end def preinitialize load(preinitializer_path) if File.exist?(preinitializer_path) end def preinitializer_path "#{RAILS_ROOT}/config/preinitializer.rb" end end class Boot def run load_initializer + + Rails::Initializer.class_eval do + def load_gems + @bundler_loaded ||= Bundler.require :default, Rails.env + end + end + Rails::Initializer.run(:set_load_path) end end class VendorBoot < Boot def load_initializer - require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer" + require 'initializer' Rails::Initializer.run(:install_gem_spec_stubs) - Rails::GemDependency.add_frozen_gem_path end end class GemBoot < Boot def load_initializer self.class.load_rubygems load_rails_gem require 'initializer' end - + def load_rails_gem if version = self.class.gem_version gem 'rails', version else gem 'rails' end rescue Gem::LoadError => load_error $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.) exit 1 end class << self def rubygems_version Gem::RubyGemsVersion rescue nil end def gem_version if defined? RAILS_GEM_VERSION RAILS_GEM_VERSION elsif ENV.include?('RAILS_GEM_VERSION') ENV['RAILS_GEM_VERSION'] else parse_gem_version(read_environment_rb) end end def load_rubygems require 'rubygems' min_version = '1.3.1' unless rubygems_version >= min_version $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.) exit 1 end rescue LoadError $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org) exit 1 end def parse_gem_version(text) $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/ end private def read_environment_rb File.read("#{RAILS_ROOT}/config/environment.rb") end end end end # All that for this: Rails.boot! diff --git a/config/environment.rb b/config/environment.rb index cb92d22..101d609 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,88 +1,86 @@ # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present -RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION +#RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "aws-s3", :lib => "aws/s3" # config.gem 'ar-extensions' # config.gem "adzap-ar_mailer", :lib => 'action_mailer/ar_mailer', :source => 'http://gems.github.com' # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'UTC' # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) - config.load_paths << "#{RAILS_ROOT}/app/sweepers" + config.autoload_paths << "#{RAILS_ROOT}/app/sweepers" # Force all environments to use the same logger level # (by default production uses :info, the others :debug) # config.log_level = :debug # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. config.action_controller.session = { :key => '_findyourmp_session', :secret => '46530d6a3d7dcbdd1a8d6935314dbd52fe689e773e15cd833a09cac0fb68d797fcc0d1b8202f58ccf643ada161aa1e2ea48801b0b6bce7b0b9b0e99ddecdcbbd' } # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # config.action_controller.session_store = :active_record_store # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector - end -require 'action_mailer/ar_mailer' require 'passenger_mgt' require 'route_helper' require 'sitemap' require 'zlib' Haml::Template.options[:format] = :html5 ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!( :month_year => "%B %Y" ) ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!( :month_year => "%B %Y" ) ActiveRecord::Base.send(:include, CountByMonth) ActiveRecord::Base.send(:include, FindYourMP::PassengerManagement) diff --git a/config/environments/test.rb b/config/environments/test.rb index b34971d..3e76502 100644 --- a/config/environments/test.rb +++ b/config/environments/test.rb @@ -1,24 +1,24 @@ # Settings specified here will take precedence over those in config/environment.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = true config.action_controller.perform_caching = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = $allow_forgery_protection ? true : false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. -config.action_mailer.delivery_method = :test +# config.action_mailer.delivery_method = :test -require "#{RAILS_ROOT}/vendor/plugins/webrat/lib/webrat" +require "webrat" diff --git a/config/initializers/smtp_gmail.rb b/config/initializers/smtp_gmail.rb deleted file mode 100644 index bdc3fe7..0000000 --- a/config/initializers/smtp_gmail.rb +++ /dev/null @@ -1,18 +0,0 @@ -# -# For Rails 2.x: -# A copy of this file should be placed in RAILS_ROOT/initializers/ -# A file named mailer.yml should be placed in RAILS_ROOT/config/ -# See mailer.yml.sample -# - -mailer_conf = "#{RAILS_ROOT}/config/mailer.yml" - -if File.exists?(mailer_conf) - require "smtp_tls" - - mailer_config = File.open(mailer_conf) - mailer_options = YAML.load(mailer_config) - ActionMailer::Base.smtp_settings = mailer_options -elsif ActionMailer::Base.delivery_method == :smtp - raise "config/mailer.yml not found, failed to setup smtp_tls plugin" -end diff --git a/config/preinitializer.rb b/config/preinitializer.rb new file mode 100644 index 0000000..1686575 --- /dev/null +++ b/config/preinitializer.rb @@ -0,0 +1,20 @@ +begin + require "rubygems" + require "bundler" +rescue LoadError + raise "Could not load the bundler gem. Install it with `gem install bundler`." +end + +if Gem::Version.new(Bundler::VERSION) <= Gem::Version.new("0.9.24") + raise RuntimeError, "Your bundler version is too old for Rails 2.3.\n" + + "Run `gem install bundler` to upgrade." +end + +begin + # Set up load paths for all bundled gems + ENV["BUNDLE_GEMFILE"] = File.expand_path("../../Gemfile", __FILE__) + Bundler.setup +rescue Bundler::GemNotFound + raise RuntimeError, "Bundler couldn't find some gems.\n" + + "Did you run `bundle install`?" +end \ No newline at end of file diff --git a/lib/route_helper.rb b/lib/route_helper.rb index 5e232d0..02c1e3b 100644 --- a/lib/route_helper.rb +++ b/lib/route_helper.rb @@ -1,20 +1,19 @@ -require File.dirname(__FILE__) + '/../vendor/rails/actionpack/lib/action_controller/integration' +require 'action_controller/integration' class RouteHelper include ActionView::Helpers::UrlHelper include ApplicationHelper def initialize app, helper, hostname app = ActionController::Integration::Session.new unless app @app = app @hostname = hostname end def method_missing symbol, *args if symbol.to_s.ends_with? 'url' @app.send(symbol, *args).sub('www.example.com', @hostname) end end - end diff --git a/spec/controllers/search_controller_spec.rb b/spec/controllers/search_controller_spec.rb index 2e1a801..01b1894 100644 --- a/spec/controllers/search_controller_spec.rb +++ b/spec/controllers/search_controller_spec.rb @@ -1,258 +1,258 @@ require File.dirname(__FILE__) + '/../spec_helper' describe SearchController do before do @postcode = ' N1 1aA ' @postcode_district = 'N1' @postcode_with_space = 'N1 1AA' @canonical_postcode = @postcode.upcase.tr(' ','') @constituency_id = 801 @constituency_name_part = 'Islington' @member_name_part = 'Bloggs' @constituency_name_short = 'sl' @constituency_name = 'Islington South' @friendly_constituency_id = 'islington-south' @constituency = mock_model(Constituency, :name => @constituency_name, :id => @constituency_id, :friendly_id => @friendly_constituency_id, :has_better_id? => false, :member_name => 'Dave Bloggs') @other_constituency = mock_model(Constituency, :name => 'Islington East', :id => 802, :friendly_id => 'islington-east', :has_better_id? => false, :member_name => 'Jo Bloggs') @json = '{json : {}}' @text = "text:" @xml = '<xml/>' @csv = 'c,s,v' @yaml = '---yaml:' @postcode_record = mock_model(Postcode, :constituency_id => @constituency_id, :code => @canonical_postcode, :code_with_space => @postcode_with_space, :constituency => @constituency, :to_json => @json, :to_text => @text, :to_csv => @csv, :to_output_yaml=>@yaml) @district_record = mock_model(PostcodeDistrict, :id => 1234, :friendly_id => @friendly_constituency_id, :constituency => @constituency, :constituency_name => @constituency_name, :member_name => @member_name, :district => 'N1') @other_district_record = mock_model(PostcodeDistrict, :id => 1123, :friendly_id => 'islington-east', :constituency => @other_constituency, :constituency_name => 'Islington East', :member_name => 'Donal Duck', :district => 'E1') Postcode.stub!(:find_postcode_by_code).and_return nil end describe "when asked for constituency given an exact constituency name" do def do_get format=nil get :index, :q => @constituency_name, :format => format end before do PostcodeDistrict.should_receive(:find_all_by_district).with(@constituency_name).and_return [] Postcode.should_receive(:find_postcode_by_code).with(@constituency_name).and_return nil end describe 'and a matching constituency is not found' do it 'should redirect to root page' do do_get response.should redirect_to("") end it_should_behave_like "returns in correct format" end describe 'and a matching constituency is found' do before do Constituency.should_receive(:find_all_name_or_member_name_matches).with(@constituency_name).and_return [@constituency] end it 'should redirect to constituency view showing constituency' do do_get response.should redirect_to("constituencies/#{@friendly_constituency_id}") end end end describe "when asked for constituency given part of constituency name" do def do_get format=nil get :index, :q => @constituency_name_part, :format => format end before do Postcode.should_receive(:find_postcode_by_code).with(@constituency_name_part).and_return nil end describe 'and a matching constituency is not found' do it 'should redirect to root page' do do_get response.should redirect_to("") end end describe 'and two matching constituencies are found' do before do @other_constituency = mock_model(Constituency, :name => 'Islington North', :id => 802) @matching = [@constituency, @other_constituency] Constituency.should_receive(:find_all_name_or_member_name_matches).with(@constituency_name_part).and_return @matching Constituency.should_receive(:find_all_constituency_and_member_matches).and_return [@matching, []] end it 'should show list of matching constituencies' do @controller.should_receive(:render).with :template => '/constituencies/show' do_get end it 'should assign search term to view' do do_get assigns[:last_search_term].should == @constituency_name_part end it_should_behave_like "returns in correct format" end end describe "when asked to search for a term of 2 letters" do before do Postcode.should_receive(:find_postcode_by_code).with(@constituency_name_short).and_return nil end def do_get format=nil get :index, :q => @constituency_name_short, :format => format end it 'should store "not_found" in flash memory</p>' do do_get flash[:not_found].should == "not_found" end it 'should redirect to root page' do do_get response.should redirect_to("") end it_should_behave_like "returns in correct format" it 'should set last_search_term in flash memory' do do_get flash[:last_search_term].should == @constituency_name_short end end describe "when asked for constituency given a postcode" do def do_get format=nil get :index, :q => @postcode, :format => format end describe 'and no matching postcode is found' do it 'should redirect to root page' do do_get response.should redirect_to("") end it_should_behave_like "returns in correct format" it 'should set last_search_term in flash memory' do do_get flash[:last_search_term].should == @postcode end end describe 'and a matching postcode is found' do before do Postcode.should_receive(:find_postcode_by_code).with(@postcode).and_return @postcode_record end it 'should redirect to postcode view showing constituency' do do_get response.should redirect_to("postcodes/#{@canonical_postcode}") end end end describe "when asked to search for a partial postcode" do def do_get format=nil get :index, :q => @postcode_district, :format => format end before do @matches = [ @district_record ] PostcodeDistrict.should_receive(:find_all_by_district).with(@postcode_district).and_return @matches end it 'should redirect to show with the postcode district' do do_get response.should redirect_to(:controller => 'postcodes', :action => 'show', :postcode => @postcode_district) end end describe 'when asked to show 2 or more constituencies' do before do @matching = [[@other_constituency, @constituency], []] end describe 'and there are constituency matches' do before do Constituency.should_receive(:find_all_constituency_and_member_matches).with(@constituency_name_part).and_return @matching end def do_get format=nil get :show, :q => @constituency_name_part, :format => format end it 'should assign search term to view' do do_get assigns[:last_search_term].should == @constituency_name_part end it_should_behave_like "returns in correct format" end describe 'and there are member matches' do before do matching = [[], [@constituency, @other_constituency]] Constituency.should_receive(:find_all_constituency_and_member_matches).with(@member_name_part).and_return matching end def do_get format=nil get :show, :q => @member_name_part, :format => format end it 'should assign constituencies to view ordered by member_name' do do_get members_ordered_by_name = [@constituency, @other_constituency] assigns[:members].should == members_ordered_by_name end it 'should assign search term to view' do do_get assigns[:last_search_term].should == @member_name_part end it_should_behave_like "returns in correct format" end describe 'and the search term is all lower case' do before do Constituency.should_receive(:find_all_constituency_and_member_matches).with('islington').and_return @matching end def do_get format=nil get :show, :q => 'islington', :format => format end it 'should show list of matching constituencies' do do_get constituencies_ordered_by_name = [@other_constituency, @constituency] assigns[:constituencies].should == constituencies_ordered_by_name end it_should_behave_like "returns in correct format" end end describe 'search route' do it 'should route correctly' do - params_from(:get, "/search?q=E3+2AT&commit=Find+MP").should == {:controller => "search", :action => "index", :q=>'E3+2AT', :commit=>"Find+MP"} + params_from(:get, "/search?q=E3+2AT&commit=Find+MP").should == {:controller => "search", :action => "index", :q=>'E3 2AT', :commit=>"Find MP"} end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index c47a8c9..c950d52 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,49 +1,52 @@ # This file is copied to ~/spec when you run 'ruby script/generate rspec' # from the project root directory. ENV["RAILS_ENV"] = "test" + require File.expand_path(File.dirname(__FILE__) + "/../config/environment") + require 'spec' require 'spec/rails' + require File.expand_path(File.dirname(__FILE__) + "/spec_utils.rb") Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} Spec::Runner.configure do |config| # If you're not using ActiveRecord you should remove these # lines, delete config/database.yml and disable :active_record # in your config/boot.rb config.use_transactional_fixtures = true config.use_instantiated_fixtures = false config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # == Fixtures # # You can declare fixtures for each example_group like this: # describe "...." do # fixtures :table_a, :table_b # # Alternatively, if you prefer to declare them only once, you can # do so right here. Just uncomment the next line and replace the fixture # names with your fixtures. # # config.global_fixtures = :table_a, :table_b # # If you declare global fixtures, be aware that they will be declared # for all of your examples, even those that don't use them. # # You can also declare which fixtures to use (for example fixtures for test/fixtures): # # config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # # == Mock Framework # # RSpec uses it's own mocking framework by default. If you prefer to # use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # # == Notes # # For more information take a look at Spec::Example::Configuration and Spec::Runner end diff --git a/spec/views/constituencies/show.haml_spec.rb b/spec/views/constituencies/show.haml_spec.rb index bb014a7..1e2edf2 100644 --- a/spec/views/constituencies/show.haml_spec.rb +++ b/spec/views/constituencies/show.haml_spec.rb @@ -1,50 +1,50 @@ require File.dirname(__FILE__) + '/../../spec_helper' describe "/constituencies/show.haml" do before do @constituency = Constituency.new( :member_name => 'member_name', :member_party => 'member_party', :member_biography_url => 'http://here.it.is', :member_website => 'http://the.re', :member_email => "member@email", :member_requested_contact_url=>'', :name => "Islington North", :member_visible => true) @constituency.stub!(:friendly_id).and_return 'islington_north' @other_constituency = Constituency.new( :member_name => 'member_name', :member_party => 'member_party', :member_biography_url => '', :member_website => '', :member_email => "member@email", :member_requested_contact_url => nil, :name => "Islington South", :member_visible => true) @other_constituency.stub!(:friendly_id).and_return 'islington_south' end it "should not render member website when the data is not supplied" do assigns[:constituency] = @other_constituency render "/constituencies/show.haml" response.should_not have_text(/Website/) end it "should not render member biography when the data is not supplied" do assigns[:constituency] = @other_constituency render "/constituencies/show.haml" response.should_not have_text(/Biography/) end it 'should not show member name if no sitting member' do @constituency.stub!(:member_visible).and_return false assigns[:constituencies] = [@constituency, @other_constituency] assigns[:members] = [] render "/constituencies/show.haml" - response.should have_text(/Islington North<\/a>\n &mdash; no sitting Member/) - response.should have_text(/Islington South<\/a>\n &mdash; member_name/) + response.should have_text(/Islington North<\/a>\n&mdash; no sitting Member/) + response.should have_text(/Islington South<\/a>\n&mdash; member_name/) end end diff --git a/vendor/plugins/authlogic b/vendor/plugins/authlogic deleted file mode 160000 index 331df65..0000000 --- a/vendor/plugins/authlogic +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 331df65c74b30b8accda6f297ac024fb39191e50 diff --git a/vendor/plugins/cucumber b/vendor/plugins/cucumber deleted file mode 160000 index d0555e4..0000000 --- a/vendor/plugins/cucumber +++ /dev/null @@ -1 +0,0 @@ -Subproject commit d0555e4ca8a133f020efefd5a755da04bde3f57d diff --git a/vendor/plugins/friendly_id b/vendor/plugins/friendly_id deleted file mode 160000 index 650e80f..0000000 --- a/vendor/plugins/friendly_id +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 650e80fa1d992282b0307333664d89b495cbbbb3 diff --git a/vendor/plugins/haml b/vendor/plugins/haml deleted file mode 160000 index 4f41cf0..0000000 --- a/vendor/plugins/haml +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 4f41cf00fcb59e9b80c911a4b2e742970870a3eb diff --git a/vendor/plugins/resource_controller b/vendor/plugins/resource_controller deleted file mode 160000 index d995c62..0000000 --- a/vendor/plugins/resource_controller +++ /dev/null @@ -1 +0,0 @@ -Subproject commit d995c620af63ca57d83f62539ed744a162454fb5 diff --git a/vendor/plugins/rspec b/vendor/plugins/rspec deleted file mode 160000 index 59d8c1d..0000000 --- a/vendor/plugins/rspec +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 59d8c1d218f532bf4528d2589ba0c61cbd20cc11 diff --git a/vendor/plugins/rspec_rails b/vendor/plugins/rspec_rails deleted file mode 160000 index 8a71d62..0000000 --- a/vendor/plugins/rspec_rails +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 8a71d62ecca1291dc1378371c9513ab6b44ef4bc diff --git a/vendor/plugins/webrat b/vendor/plugins/webrat deleted file mode 160000 index e2a672a..0000000 --- a/vendor/plugins/webrat +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e2a672a7679dec65153dcb0e252d6aae9ccdd751 diff --git a/vendor/plugins/xss_terminate b/vendor/plugins/xss_terminate deleted file mode 160000 index 724aba5..0000000 --- a/vendor/plugins/xss_terminate +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 724aba589e2e753e7b0cfaf3196548f493b169da diff --git a/vendor/rails b/vendor/rails deleted file mode 160000 index dc88847..0000000 --- a/vendor/rails +++ /dev/null @@ -1 +0,0 @@ -Subproject commit dc88847e5ce392eed210b97525c14fca55852867
robertbrook/findyourmp
fd82261eb2334efbedb9fb4eb79e998ef4c318f3
new url for cucumber repo
diff --git a/.gitmodules b/.gitmodules index 1b449b7..a9a4869 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,30 +1,30 @@ [submodule "vendor/rails"] path = vendor/rails url = git://github.com/rails/rails.git [submodule "vendor/plugins/haml"] path = vendor/plugins/haml url = git://github.com/nex3/haml.git [submodule "vendor/plugins/rspec_rails"] path = vendor/plugins/rspec_rails url = git://github.com/dchelimsky/rspec-rails.git [submodule "vendor/plugins/rspec"] path = vendor/plugins/rspec url = git://github.com/dchelimsky/rspec.git [submodule "vendor/plugins/resource_controller"] path = vendor/plugins/resource_controller url = git://github.com/giraffesoft/resource_controller.git [submodule "vendor/plugins/cucumber"] path = vendor/plugins/cucumber - url = git://github.com/aslakhellesoy/cucumber.git + url = git://github.com/cucumber/cucumber.git [submodule "vendor/plugins/webrat"] path = vendor/plugins/webrat url = git://github.com/brynary/webrat.git [submodule "vendor/plugins/friendly_id"] path = vendor/plugins/friendly_id url = git://github.com/norman/friendly_id.git [submodule "vendor/plugins/authlogic"] path = vendor/plugins/authlogic url = git://github.com/binarylogic/authlogic.git [submodule "vendor/plugins/xss_terminate"] path = vendor/plugins/xss_terminate url = git://github.com/look/xss_terminate.git
robertbrook/findyourmp
5df78c798641be3a20ea6914100d037a06c7740c
fixing api screen bug caused by "new" html wrapper
diff --git a/app/controllers/api_controller.rb b/app/controllers/api_controller.rb index ee7e336..7924811 100644 --- a/app/controllers/api_controller.rb +++ b/app/controllers/api_controller.rb @@ -1,219 +1,220 @@ class ApiController < ApplicationController def index @host = request.host unless request.port == 80 @host += ':' + request.port.to_s end end def search + params[:search_term] = params[:q1] unless params[:q1].blank? params[:search_term] = params[:q] unless params[:q].blank? search_term = params[:search_term] params[:format] = params[:f] unless params[:f].blank? search_format = params[:format] if search_term postcode_districts = PostcodeDistrict.find_all_by_district(search_term) unless postcode_districts.empty? show_postcode_districts(postcode_districts, search_format) else postcode = Postcode.find_postcode_by_code(search_term) if postcode show_postcode(postcode, search_term, search_format) else stripped_term = search_term.strip.squeeze(' ').gsub('"','') if stripped_term.size > 2 constituencies = Constituency.find_all_name_or_member_name_matches(stripped_term) if constituencies.empty? flash[:not_found] = "not_found" flash[:last_search_term] = search_term show_error(search_format) elsif constituencies.size == 1 show_constituencies([constituencies.first], stripped_term, search_format) else show_constituencies(constituencies, stripped_term, search_format) end else flash[:not_found] = "Sorry: we need more than two letters to search" flash[:last_search_term] = search_term show_error(search_format) end end end else flash[:not_found] = "Sorry: the API did not recognise this parameter" show_error(search_format) end end def postcodes code = params[:code] district = params[:district] params[:format] = params[:f] unless params[:f].blank? search_format = params[:format] if district postcode_districts = PostcodeDistrict.find_all_by_district(district) unless postcode_districts.empty? show_postcode_districts(postcode_districts, search_format) else flash[:not_found] = "Sorry: we couldn't find a postcode when we searched for #{district}. Please go back and check the postcode you entered, and ensure you have entered a complete postcode. If you are an expatriate, in an overseas territory, a Crown dependency or in the Armed Forces without a postcode, this service cannot be used to find your MP." show_error(search_format) end elsif code postcode = Postcode.find_postcode_by_code(code) if postcode show_postcode(postcode, code, search_format) else flash[:not_found] = "Sorry: we couldn't find a postcode when we searched for #{code}. Please go back and check the postcode you entered, and ensure you have entered a complete postcode. If you are an expatriate, in an overseas territory, a Crown dependency or in the Armed Forces without a postcode, this service cannot be used to find your MP." show_error(search_format) end else flash[:not_found] = "Sorry: the API did not recognise this parameter" show_error(search_format) end end def constituencies member_name = params[:member] constituency_name = params[:constituency] ons_id = params[:ons_id] params[:format] = params[:f] unless params[:f].blank? search_format = params[:format] if ons_id ons_id = ons_id.strip.gsub('"','') constituency = Constituency.find_by_ons_id(ons_id) if constituency show_constituency(constituency, search_format) else flash[:not_found] = "Sorry: we couldn't find a constituency with an ONS id of #{ons_id}" show_error(search_format) end elsif member_name member_name = member_name.strip.gsub('"','') constituency = Constituency.find_by_member_name(member_name) if constituency show_constituency(constituency, search_format) else flash[:not_found] = "Sorry: we couldn't find a constituency with a member name of #{member_name}" show_error(search_format) end elsif constituency_name constituency_name = constituency_name.strip.gsub('"','') constituency = Constituency.find_by_name(constituency_name) if constituency show_constituency(constituency, search_format) else flash[:not_found] = "Sorry: we couldn't find a constituency with a constituency name of #{constituency_name}" show_error(search_format) end else flash[:not_found] = "Sorry: the API did not recognise this parameter" show_error(search_format) end end private def show_postcode postcode, search_term, format host = request.host port = request.port show_constituencies([postcode.constituency], nil, format) # @postcode = postcode # @constituency = postcode.constituency # respond_to do |format| # format.html { render :template => '/postcodes/show', :postcode => postcode } # format.xml { render :template => '/postcodes/show', :postcode => postcode, :layout => false } # format.json { render :json => postcode.to_json(host, port) } # format.js { render :json => postcode.to_json(host, port) } # format.text { render :text => postcode.to_text(host, port) } # format.csv { render :text => postcode.to_csv(host, port) } # format.yaml { render :text => postcode.to_output_yaml(host, port) } # end end def show_postcode_districts postcode_districts, format @search_term = params[:q] respond_to do |format| @postcode_districts = postcode_districts @constituencies = postcode_districts.collect { |postcode| postcode.constituency } format.html { render :template => '/postcodes/show' } format.xml { render :template => '/constituencies/show', :layout => false } format.json { render :json => results_to_json(@constituencies, []) } format.js { render :json => results_to_json(@constituencies, []) } format.text { render :text => results_to_text(@constituencies, []) } format.csv { render :text => results_to_csv(@constituencies, []) } format.yaml { render :text => results_to_yaml(@constituencies, []) } end end def show_constituency constituency, format @constituency = constituency host = request.host port = request.port respond_to do |format| format.html { render :template => '/constituencies/show' } format.xml { render :template => '/constituencies/show.xml.haml', :layout => false } format.json { render :json => constituency.to_json(host, port) } format.js { render :json => constituency.to_json(host, port) } format.text { render :text => constituency.to_text(host, port) } format.csv { render :text => constituency.to_csv(host, port) } format.yaml { render :text => constituency.to_output_yaml(host, port) } end end def show_constituencies constituencies, search_term, format @constituencies = constituencies if search_term @members = constituencies.clone if search_term[/[A-Z][a-z].*/] @constituencies.delete_if { |c| !(c.name.include? search_term) } @members.delete_if { |c| c.member_name.blank? || !(c.member_name.include? search_term) } else @constituencies.delete_if { |c| !(c.name.downcase.include? search_term.downcase) } @members.delete_if { |c| c.member_name.blank? || !(c.member_name.downcase.include? search_term.downcase) } end else @members = [] end respond_to do |format| format.html { render :template => '/constituencies/show' } format.xml { render :template => '/constituencies/show.xml.haml', :layout => false } format.json { render :json => results_to_json(@constituencies, @members, params[:callback]) } format.js { render :json => results_to_json(@constituencies, @members, params[:callback]) } format.text { render :text => results_to_text(@constituencies, @members) } format.csv { render :text => results_to_csv(@constituencies, @members) } format.yaml { render :text => results_to_yaml(@constituencies, @members) } end end def show_error format @error_message = flash[:not_found] flash[:not_found] = nil unless format == 'html' respond_to do |format| format.html { render :template => '/api/index'} format.xml { render :template => '/constituencies/show.xml.haml', :layout => false } format.json { render :json => results_to_json([], []) } format.js { render :json => results_to_json([], []) } format.text { render :text => results_to_text([], []) } format.csv { render :text => results_to_csv([], []) } format.yaml { render :text => results_to_yaml([], []) } end end end \ No newline at end of file diff --git a/app/views/api/index.haml b/app/views/api/index.haml index 3123cf0..39b1e9f 100644 --- a/app/views/api/index.haml +++ b/app/views/api/index.haml @@ -1,36 +1,36 @@ -@title = 'API' -@crumbtrail = 'API' -@javascript = 'prototype' %div.text.flash= flash[:not_found] if flash[:not_found] %p.text The Find Your MP service provides output in several formats in addition to HTML - XML, JSON, Javascript, plain text, comma separated values and YAML. %p.text You can query the service using the following URL format: <b><code>http://findyourmp.parliament.uk/api/search?q=YOUR_SEARCH_TERM&format=YOUR_DESIRED_FORMAT</code></b>, where <b><code>YOUR_SEARCH_TERM</code></b> should be replaced with whatever you wish to search for and <b><code>YOUR_DESIRED_FORMAT</code></b> with one of XML, JSON, JS, TEXT, CSV, or YAML. %p.text There are currently no usage limits to the API, but they may be introduced in future. - form_remote_tag :url => "http://#{@host}/api/search", :success => "$('result').innerHTML = '<pre>'+request.responseText.escapeHTML().gsub('{','{<br/>').gsub(',',',<br/>')+'</pre>'" do %p = label_tag 'f_xml', 'XML' = radio_button_tag 'f', 'xml' %br = label_tag 'f_js', 'JS' = radio_button_tag 'f', 'js' %br = label_tag 'f_csv', 'CSV' = radio_button_tag 'f', 'csv' %p - = text_field_tag 'q', '', :size => 24 + = text_field_tag 'q1', '', :size => 24 = submit_tag 'Find MP' = observe_field :f_xml, :frequency => 0.5, :function => 'if($("f_xml").checked) { $("format").innerHTML = $("f_xml").value }' = observe_field :f_js, :frequency => 0.5, :function => 'if($("f_js").checked) { $("format").innerHTML = $("f_js").value }' = observe_field :f_csv, :frequency => 0.5, :function => 'if($("f_csv").checked) { $("format").innerHTML = $("f_csv").value }' -= observe_field :q, :frequency => 0.5, :function => '$("query").innerHTML = escape($("q").value)' += observe_field :q1, :frequency => 0.5, :function => '$("query").innerHTML = escape($("q1").value)' %p URL: %p = "http://#{@host}/api/search?q=<b><span id='query'></span></b>&amp;f=<b><span id='format'></span></b>" #result diff --git a/spec/controllers/api_controller_spec.rb b/spec/controllers/api_controller_spec.rb index e1d7bee..2134226 100644 --- a/spec/controllers/api_controller_spec.rb +++ b/spec/controllers/api_controller_spec.rb @@ -1,431 +1,431 @@ require File.dirname(__FILE__) + '/../spec_helper' describe ApiController do before do @postcode_no_space = 'N11AA' @postcode = ' N1 1aA ' @postcode_with_space = 'N1 1AA' @postcode_district = 'N1' @canonical_postcode = @postcode.upcase.tr(' ','') @constituency_id = 801 @constituency_name_part = 'Islington' @constituency_name_short = 'sl' @constituency_name = 'Islington South' @member_name = 'Mickey Muse' @friendly_constituency_id = 'islington-south' @constituency = mock_model(Constituency, :name => @constituency_name, :id => @constituency_id, :member_name => @member_name, :friendly_id => @friendly_constituency_id, :has_better_id? => false, :to_text => 'text version of data', :to_csv => 'csv version of data with headers', :to_csv_value => 'csv version of data', :to_json => '(json version of data)', :to_output_yaml => 'yaml version of data') @other_constituency_id = 802 @other_constituency = mock_model(Constituency, :name => 'Islington & North', :id => 802, :member_name => 'A Biggens-South', :to_text => 'text version of data', :to_csv_value => 'csv version of data', :to_json => '(json version of data)', :to_output_yaml => 'yaml version of data') @postcode_record = mock_model(Postcode, :constituency_id => @constituency_id, :code => @canonical_postcode, :code_with_space => @postcode_with_space, :constituency => @constituency, :to_json => @json, :to_text => @text, :to_csv => @csv, :to_output_yaml=>@yaml) end describe 'non redirecting url', :shared => true do it 'should not redirect' do do_get response.redirect?.should be_false end end describe "when finding route for action" do it 'should display page not found for unknown routes' do params_from(:get, "/bad_url").should == {:controller => "application", :action => "render_not_found", :bad_route=>['bad_url']} end end describe "the search api" do describe "when passed a search_term which matches a postcode" do before do Postcode.stub!(:find_postcode_by_code).and_return @postcode_record Postcode.should_receive(:find_postcode_by_code).with(@postcode_no_space).and_return @postcode_record end def do_get format=nil get :search, :q => @postcode_no_space, :format => format end it_should_behave_like "returns in correct format" it_should_behave_like "non redirecting url" it 'should render js correctly' do do_get 'js' - response.body.should == %Q|{"results": { "constituencies": {json version of data}, "members": {} }} | + response.body.should == %Q|{"results": { "constituencies": [json version of data], "members": [] }} | end it 'should render js with callback correctly' do get :search, :q => @postcode_no_space, :format => 'js', :callback => 'callback_function' - response.body.should == %Q|callback_function({"results": { "constituencies": {json version of data}, "members": {} }} )| + response.body.should == %Q|callback_function({"results": { "constituencies": [json version of data], "members": [] }} )| end end describe "when passed a search term which matches a single constituency" do before do Postcode.stub!(:find_postcode_by_code) Postcode.should_receive(:find_postcode_by_code).with(@constituency_name).and_return nil Constituency.stub!(:find_all_name_or_member_name_matches) Constituency.should_receive(:find_all_name_or_member_name_matches).with(@constituency_name).and_return [ @constituency ] end def do_get format=nil get :search, :q => @constituency_name, :format => format end it_should_behave_like "returns in correct format" it_should_behave_like "non redirecting url" end describe "when passed a search term which matches 2 constituencies" do before do @matches = [ @constituency, @other_constituency ] Postcode.stub!(:find_postcode_by_code) Postcode.should_receive(:find_postcode_by_code).with(@constituency_name_part).and_return nil Constituency.stub!(:find_all_name_or_member_name_matches) Constituency.should_receive(:find_all_name_or_member_name_matches).with(@constituency_name_part).and_return @matches @constituency.should_receive(:member_name).and_return('asdf') @other_constituency.should_receive(:member_name).and_return('qweq') end def do_get format=nil get :search, :q => @constituency_name_part, :format => format end it 'should assign constituency to view' do do_get assigns[:constituencies].should == @matches end it_should_behave_like "returns in correct format" it_should_behave_like "non redirecting url" end describe "when passed a search term which matches 2 constituencies and is all lower case" do before do @matches = [ @constituency, @other_constituency ] Postcode.stub!(:find_postcode_by_code) Postcode.should_receive(:find_postcode_by_code).with('islington').and_return nil Constituency.stub!(:find_all_name_or_member_name_matches) Constituency.should_receive(:find_all_name_or_member_name_matches).with('islington').and_return @matches @constituency.should_receive(:member_name).and_return('asdf') @other_constituency.should_receive(:member_name).and_return('qweq') end def do_get format=nil get :search, :q => 'islington', :format => format end it_should_behave_like "returns in correct format" it_should_behave_like "non redirecting url" it 'should assign constituency to view' do do_get assigns[:constituencies].should == @matches end end describe "when passed a search term which matches a postcode district" do before do @matches = [ @postcode_record ] PostcodeDistrict.should_receive(:find_all_by_district).with(@postcode_district).and_return(@matches) end def do_get format=nil get :search, :q => @postcode_district, :format => format end it 'should assign the search term to the view' do do_get assigns[:search_term].should == @postcode_district end it_should_behave_like "returns in correct format" it_should_behave_like "non redirecting url" end describe "when passed a search term which returns no results" do before do Postcode.stub!(:find_postcode_by_code) Postcode.should_receive(:find_postcode_by_code).and_return nil Constituency.stub!(:find_all_name_or_member_name_matches) Constituency.should_receive(:find_all_name_or_member_name_matches).and_return [ ] end def do_get format=nil get :search, :q => 'invalid', :format => format end it_should_behave_like "returns in correct format" it_should_behave_like "non redirecting url" it 'should store the error message in flash memory' do do_get flash[:not_found].should be_nil end it 'should store the search term in flash memory' do do_get flash[:last_search_term].should == 'invalid' end end describe "when passed a search term of 2 characters" do def do_get format=nil get :search, :q => @constituency_name_short, :format => format end it_should_behave_like "returns in correct format" it_should_behave_like "non redirecting url" it 'should store the error message in flash memory' do do_get flash[:not_found].should be_nil end it 'should store the search term in flash memory' do do_get flash[:last_search_term].should == @constituency_name_short end end describe "when not passed a search_term parameter" do def do_get format=nil get :search, :format => format end it 'should store an error message in flash memory' do do_get flash[:not_found].should be_nil end it 'should not redirect' do do_get response.redirect?.should be_false end end end describe "the postcodes api" do describe "when passed a valid postcode" do before do Postcode.stub!(:find_postcode_by_code).and_return @postcode_record Postcode.should_receive(:find_postcode_by_code).with(@postcode_no_space).and_return @postcode_record end def do_get format=nil get :postcodes, :code => @postcode_no_space, :format => format end it_should_behave_like "returns in correct format" it_should_behave_like "non redirecting url" end describe "when passed an invalid postcode" do before do Postcode.stub!(:find_postcode_by_code).and_return nil Postcode.should_receive(:find_postcode_by_code).with('invalid').and_return nil end def do_get format=nil get :postcodes, :code => 'invalid', :format => format end it 'should store the error message in flash memory' do do_get flash[:not_found].should be_nil end end describe "when passed a valid postcode_district" do before do @matches = [ @postcode_record ] PostcodeDistrict.should_receive(:find_all_by_district).with(@postcode_district).and_return(@matches) end def do_get format=nil get :postcodes, :district => @postcode_district, :format => format end it_should_behave_like "returns in correct format" it_should_behave_like "non redirecting url" end describe "when passed an invalid postcode_district" do before do PostcodeDistrict.should_receive(:find_all_by_district).with('invalid').and_return([]) end def do_get get :postcodes, :district => 'invalid' end it 'should not redirect' do do_get response.redirect?.should be_false end it 'should store the error message in flash memory' do do_get flash[:not_found].should be_nil end end describe "when not passed a valid parameter" do def do_get format=nil get :postcodes, :format => format end it 'should store an error message in flash memory' do do_get flash[:not_found].should be_nil end end end describe "the constituencies api" do describe "when passed a valid ONS id" do before do Constituency.stub!(:find).and_return @constituency Constituency.should_receive(:find).and_return @constituency end def do_get format=nil get :constituencies, :ons_id => '123', :format => format end it 'should assign constituency to view' do do_get assigns[:constituency].should == @constituency end it_should_behave_like "returns in correct format" it_should_behave_like "non redirecting url" end describe "when passed an invalid ONS id" do before do Constituency.stub!(:find).and_return nil Constituency.should_receive(:find).and_return nil end def do_get format=nil get :constituencies, :ons_id => 9999, :format => format end it 'should not redirect' do do_get response.redirect?.should be_false end it 'should store the error message in flash memory' do do_get flash[:not_found].should be_nil end end describe "when passed a valid member name" do before do Constituency.stub!(:find).and_return @constituency Constituency.should_receive(:find).and_return @constituency end def do_get format=nil get :constituencies, :member => @member_name, :format => format end it 'should assign constituency to view' do do_get assigns[:constituency].should == @constituency end it_should_behave_like "returns in correct format" it_should_behave_like "non redirecting url" end describe "when passed an invalid member name" do before do Constituency.stub!(:find).and_return nil Constituency.should_receive(:find).and_return nil end def do_get format=nil get :constituencies, :member => 'invalid', :format => format end it 'should not redirect' do do_get response.redirect?.should be_false end it 'should store the error message in flash memory' do do_get flash[:not_found].should be_nil end end describe "when passed a valid constituency name" do before do Constituency.stub!(:find).and_return @constituency Constituency.should_receive(:find).and_return @constituency end def do_get format=nil get :constituencies, :constituency => @constituency_name, :format => format end it 'should assign constituency to view' do do_get assigns[:constituency].should == @constituency end it_should_behave_like "returns in correct format" it_should_behave_like "non redirecting url" end describe "when passed an invalid constituency name" do before do Constituency.stub!(:find).and_return nil Constituency.should_receive(:find).and_return nil end def do_get format=nil get :constituencies, :constituency => 'invalid', :format => format end it 'should store the error message in flash memory' do do_get flash[:not_found].should be_nil end end describe "when not passed a valid parameter" do def do_get format=nil get :constituencies, :format => format end it 'should store an error message in flash memory' do do_get flash[:not_found].should be_nil end end end end \ No newline at end of file
robertbrook/findyourmp
904dc4789d3da957ad6c2b934943494703265373
gah, missed a bit
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index e357008..c47a8c9 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,48 +1,49 @@ # This file is copied to ~/spec when you run 'ruby script/generate rspec' # from the project root directory. ENV["RAILS_ENV"] = "test" require File.expand_path(File.dirname(__FILE__) + "/../config/environment") require 'spec' require 'spec/rails' require File.expand_path(File.dirname(__FILE__) + "/spec_utils.rb") +Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} Spec::Runner.configure do |config| # If you're not using ActiveRecord you should remove these # lines, delete config/database.yml and disable :active_record # in your config/boot.rb config.use_transactional_fixtures = true config.use_instantiated_fixtures = false config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # == Fixtures # # You can declare fixtures for each example_group like this: # describe "...." do # fixtures :table_a, :table_b # # Alternatively, if you prefer to declare them only once, you can # do so right here. Just uncomment the next line and replace the fixture # names with your fixtures. # # config.global_fixtures = :table_a, :table_b # # If you declare global fixtures, be aware that they will be declared # for all of your examples, even those that don't use them. # # You can also declare which fixtures to use (for example fixtures for test/fixtures): # # config.fixture_path = RAILS_ROOT + '/spec/fixtures/' # # == Mock Framework # # RSpec uses it's own mocking framework by default. If you prefer to # use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # # == Notes # # For more information take a look at Spec::Example::Configuration and Spec::Runner end
robertbrook/findyourmp
0925d2c2638864b81040a89e4ffa10e2a0271959
fixing the spec shared_examples loading order bug
diff --git a/spec/controllers/application_controller_spec.rb b/spec/controllers/application_controller_spec.rb index d64c2d1..0beff19 100644 --- a/spec/controllers/application_controller_spec.rb +++ b/spec/controllers/application_controller_spec.rb @@ -1,51 +1,22 @@ require File.dirname(__FILE__) + '/../spec_helper' describe ApplicationController do - - shared_examples_for "returns in correct format" do - it 'should return xml when passed format=xml' do - do_get 'xml' - response.content_type.should == "application/xml" - end - - it 'should return json when passed format=json' do - do_get 'json' - response.content_type.should == "application/json" - end - - it 'should return text when passed format=text' do - do_get 'text' - response.content_type.should == "text/plain" - end - - it 'should return csv when passed format=csv' do - do_get 'csv' - response.content_type.should =='text/csv' - end - - it 'should return yaml when passed format=yaml' do - do_get 'yaml' - response.content_type.should =='application/x-yaml' - end - - end - describe "when finding route for action" do it 'should display page not found for unknown routes' do params_from(:get, "/bad_url").should == {:controller => "application", :action => "render_not_found", :bad_route=>['bad_url']} end end describe 'converting date to month year string' do it 'should render correctly' do Date.new(2009,2,14).to_s(:month_year).should == 'February 2009' end end describe 'converting time to month year string' do it 'should render correctly' do Date.new(2009,2,14).to_time.to_s(:month_year).should == 'February 2009' end end end diff --git a/spec/support/controllers/formats.rb b/spec/support/controllers/formats.rb new file mode 100644 index 0000000..0a3baa9 --- /dev/null +++ b/spec/support/controllers/formats.rb @@ -0,0 +1,26 @@ +shared_examples_for "returns in correct format" do + it 'should return xml when passed format=xml' do + do_get 'xml' + response.content_type.should == "application/xml" + end + + it 'should return json when passed format=json' do + do_get 'json' + response.content_type.should == "application/json" + end + + it 'should return text when passed format=text' do + do_get 'text' + response.content_type.should == "text/plain" + end + + it 'should return csv when passed format=csv' do + do_get 'csv' + response.content_type.should =='text/csv' + end + + it 'should return yaml when passed format=yaml' do + do_get 'yaml' + response.content_type.should =='application/x-yaml' + end +end \ No newline at end of file
robertbrook/findyourmp
3e57284ea1e102c8934746cf550a28a46e7b7e79
modified search_api feature to reflect changes
diff --git a/features/search_api.feature b/features/search_api.feature index 9589b4a..7e1c569 100644 --- a/features/search_api.feature +++ b/features/search_api.feature @@ -1,89 +1,89 @@ Feature: Search API In order to search using the API as a constituent I want to get data via the search API Scenario: Call search API with valid postcode, requesting XML Given I call the search API searching for "AB101AA" and requesting "xml" Then I should see xml "<results>" Then I should see xml "<constituencies>" Then I should see xml " <constituency>" Then I should see xml " <constituency-name>Aberdeen North</constituency-name>" Then I should see xml " <member-name>Frank Doran</member-name>" Then I should see xml " <member-party></member-party>" Then I should see xml " <member-biography-url></member-biography-url>" Then I should see xml " <member-website></member-website>" Then I should see xml " <uri>http://www.example.com/constituencies/aberdeen-north.xml</uri>" Scenario: Call search API with valid postcode, requesting plain text Given I call the search API searching for "AB101AA" and requesting "text" And I should see "constituency_name: Aberdeen North" And I should see "member_name: Frank Doran" Scenario: Call search API with valid postcode, requesting JSON Given I call the search API searching for "AB101AA" and requesting "json" - Then I should see json {"results": { "constituencies": {"constituency": {"constituency_name": "Aberdeen North", "member_name": "Frank Doran", "member_party": "", "member_biography_url": "", "member_website": "", "uri": "http://www.example.com/constituencies/aberdeen-north.json" } }, "members": {} }} + Then I should see json {"results": { "constituencies": [{"constituency_name": "Aberdeen North", "member_name": "Frank Doran", "member_party": "", "member_biography_url": "", "member_website": "", "uri": "http://www.example.com/constituencies/aberdeen-north.json" } ], "members": [] }} Scenario: Call search API with valid postcode, requesting CSV Given I call the search API searching for "AB101AA" and requesting "csv" Then I should see "constituency_name,member_name,member_party,member_biography_url,member_website" And I should see csv "Aberdeen North","Frank Doran","","","","http://www.example.com/constituencies/aberdeen-north.csv" Scenario: Call search API with valid constituency name, requesting XML Given I call the search API searching for "Aberdeen South" and requesting "xml" Then I should see xml "<constituency>" And I should see xml "<constituency-name>Aberdeen South</constituency-name>" And I should see xml "<member-name>Miss Anne Begg</member-name>" And I should see xml "<member-party></member-party>" And I should see xml "<member-biography-url></member-biography-url>" And I should see xml "<member-website></member-website>" And I should see xml "/constituencies/aberdeen-south.xml</uri>" Scenario: Call search API with valid constituency name, requesting JSON Given I call the search API searching for "Aberdeen South" and requesting "json" - Then I should see json {"constituency": { + Then I should see json { "constituencies": [ And I should see json "constituency_name": "Aberdeen South" And I should see json "member_name": "Miss Anne Begg" And I should see json "member_party": "" And I should see json "member_biography_url": "" And I should see json "member_website": "" And I should see json "uri": And I should see json /constituencies/aberdeen-south.json Scenario: Call search API with valid constituency name (but no MP), requesting XML Given I call the search API searching for "Glenrothes" and requesting "xml" Then I should see xml "<constituency>" And I should see xml "<constituency-name>Glenrothes</constituency-name>" And I should see xml "<member-name>No sitting member</member-name>" And I should see xml "<member-party></member-party>" And I should see xml "<member-biography-url></member-biography-url>" And I should see xml "<member-website></member-website>" And I should see xml "/constituencies/glenrothes.xml</uri>" Scenario: Call search API with partial member name which will return more than 1 result line, requesting XML Given I call the search API searching for "Frank" and requesting "xml" Then I should see xml "<results>" And I should see xml "<constituency-name>Aberdeen North</constituency-name>" And I should see xml "<member-name>Frank Doran</member-name>" And I should see xml "<constituency-name>Motherwell and Wishaw</constituency-name>" And I should see xml "<member-name>Mr Frank Roy</member-name>" And I should see xml "/constituencies/motherwell-and-wishaw.xml</uri>" And I should see xml "/constituencies/aberdeen-north.xml</uri>" Scenario: Call search API with an invalid search term, requesting XML Given I call the search API searching for "invalid" and requesting "xml" Then I should see xml "<constituencies></constituencies>" Scenario: Call search API to return a single record where the constituency name contains a "&" character, requesting XML Given I call the search API searching for "Newry" and requesting "xml" Then I should see xml "<constituency>" And I should see xml "<constituency-name>Newry &amp; Armagh</constituency-name>" Scenario: Call search API with postcode district, requesting XML Given I call the search API searching for "BT35" and requesting "xml" Then I should see xml "<results>" And I should see xml "<constituency>" And I should see xml "<constituency-name>Upper Bann</constituency-name>" And I should see xml "<constituency-name>Newry &amp; Armagh</constituency-name>" And I should see xml "/constituencies/upper-bann.xml</uri>" And I should see xml "/constituencies/newry-armagh.xml</uri>"
robertbrook/findyourmp
0a5e10ca6dadfae61f9b8427f86450672636f516
fixed bug in JSON output of multiple constituencies and members
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 569d25c..656669c 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,161 +1,161 @@ # Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base filter_parameter_logging :password, :password_confirmation, :message, :constituency_list helper_method :current_user_session, :is_admin? def render_not_found message='Page not found.' @title = "Page cannot be found (404 error)" @crumbtrail = "Error: page cannot be found" render :template => 'public/404.html', :status => 404 end private def render_unauthorized render :text => 'Unauthorized', :status => 401 end def respond_unauthorized_if_not_admin render_unauthorized unless is_admin? end def redirect_to_root_if_not_admin redirect_to '/', :status => 303 unless is_admin? end def is_admin? current_user ? true : false end def current_user_session return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find end def current_user return @current_user if defined?(@current_user) @current_user = current_user_session && current_user_session.user end def require_user unless current_user store_location flash[:notice] = "You must be logged in to access this page" redirect_to new_user_session_url return false end end def require_admin_user require_user unless current_user.admin? redirect_to admin_path return false end end def require_no_user if current_user store_location redirect_to admin_path return false end end def store_location session[:return_to] = request.request_uri end def redirect_back_or_default(default) redirect_to(session[:return_to] || default) session[:return_to] = nil end def results_to_json constituencies, members, callback=nil host = request.host port = request.port constituencies_json = "" constituencies.each do |constituency| constituencies_json += ", " unless constituencies_json == "" constituencies_json += constituency.to_json(host, port)[1..-2] end members_json = "" members.each do |member| members_json += ", " unless members_json == "" members_json += member.to_json(host, port)[1..-2] end - constituencies_results = %Q|"constituencies": {#{constituencies_json}}| - members_results = %Q|"members": {#{members_json}}| + constituencies_results = %Q|"constituencies": [#{constituencies_json.gsub('"constituency": ', "")}]| + members_results = %Q|"members": [#{members_json.gsub('"constituency": ', "").gsub("/r/n", "")}]| json = %Q|{"results": { #{constituencies_results}, #{members_results} }} | if callback %Q|#{callback}(#{json})| else json end end def results_to_text constituencies, members host = request.host port = request.port results = "" constituencies.each do |constituency| results += "\n\n" results += " - " + constituency.to_text(host, port).gsub("\n", "\n\ ") end members.each do |member| results += "\n\n" results += " - " + member.to_text(host, port).gsub("\n", "\n ") end "constituencies:" + results end def results_to_yaml constituencies, members "---\n#{results_to_text(constituencies, members)}" end def results_to_csv constituencies, members host = request.host port = request.port headers = 'constituency_name,member_name,member_party,member_biography_url,member_website, uri' values = "" constituencies.each do |constituency| values += constituency.to_csv_value(host, port) + "\n" end members.each do |constituency| values += constituency.to_csv_value(host, port) + "\n" end "#{headers}\n#{values}\n" end def message_to_json root, message %Q|{"#{root}": "#{message}"}| end def message_to_text root, message %Q|#{root}: #{message}\n| end def message_to_csv root, message, root_header, message_header headers = %Q|"#{root_header}","#{message_header}"| values = %Q|"#{root}","#{message}"| "#{headers}\n#{values}\n" end def message_to_yaml root, message "---\n#{message_to_text(root, message)}" end end
robertbrook/findyourmp
9e05e8f88485f11fb14a190426c2598904bcb04d
the constituency cache sweeper now clears partial postcode pages
diff --git a/app/sweepers/constituency_sweeper.rb b/app/sweepers/constituency_sweeper.rb index 42cc55c..791b0da 100644 --- a/app/sweepers/constituency_sweeper.rb +++ b/app/sweepers/constituency_sweeper.rb @@ -1,28 +1,34 @@ class ConstituencySweeper < ActionController::Caching::Sweeper observe Constituency def after_destroy(constituency) expire_cache_for(constituency) end def after_update(constituency) expire_cache_for(constituency) end def after_hide_members expire_constituency_cache end def after_unhide_members expire_constituency_cache end private def expire_cache_for(record) expire_page(:controller => 'constituencies', :action => 'show', :id => record.friendly_id) + postcodes = record.postcode_districts.collect { |x| x.district } + + cache_dir = RAILS_ROOT+"/public/postcodes" + postcodes.each do |cache_file| + FileUtils.rm(Dir.glob("#{cache_dir}/#{cache_file}.html")) rescue Errno::ENOENT + end end def expire_constituency_cache expire_page(:controller => 'constituencies', :action => 'show') end end \ No newline at end of file
robertbrook/findyourmp
1e135b251e9f6a0a6fb2cbcd9de8cefcf7c76d88
restoring the Website information to the Member info screen
diff --git a/app/views/constituencies/_member.haml b/app/views/constituencies/_member.haml index 6797771..81dc6f3 100644 --- a/app/views/constituencies/_member.haml +++ b/app/views/constituencies/_member.haml @@ -1,20 +1,25 @@ .text - if @constituency.no_sitting_member? %p There is no sitting Member of Parliament for this constituency. - else - member_name = h(@constituency.member_name) .row_item .row_label Member for this constituency .row_value - if @constituency.member_biography_url? = link_to member_name, @constituency.member_biography_url - else = member_name .row_item .row_label Party .row_value= h(@constituency.member_party) + - if @constituency.member_website? + .row_item + .row_label Website + .row_value + = link_to @constituency.member_website - if @constituency.member_biography_url? %p %br = link_to "More information about #{member_name} MP", @constituency.member_biography_url
robertbrook/findyourmp
f733324a27b73e465bd6f419f442b30698ed2dd4
bug fix - no longer crashes when passed a blank search term
diff --git a/app/controllers/search_controller.rb b/app/controllers/search_controller.rb index 9d26bd5..a20e8c2 100644 --- a/app/controllers/search_controller.rb +++ b/app/controllers/search_controller.rb @@ -1,107 +1,107 @@ class SearchController < ApplicationController def index params[:search_term] = params[:q] unless params[:q].blank? search_term = params[:search_term] - search_term.tr!('"', '') + search_term.tr!('"', '') unless search_term.nil? params[:format] = params[:f] unless params[:f].blank? search_format = params[:format] do_search search_term, search_format end def redir params[:search_term] = params[:q] unless params[:q].blank? search_term = params[:search_term] @search_term = search_term.gsub('+',' ') redirect_to :action => 'index', :q => @search_term end def show render_show end private def render_show flash.keep(:postcode) params[:search_term] = params[:q] unless params[:q].blank? @search_term = params[:search_term] @last_search_term = @search_term @constituencies, @members = Constituency.find_all_constituency_and_member_matches @search_term respond_to do |format| format.html { render :template => '/constituencies/show' } format.xml { redirect_to_api_search 'xml' } format.json { redirect_to_api_search 'json' } format.js { redirect_to_api_search 'js' } format.text { redirect_to_api_search 'text' } format.csv { redirect_to_api_search 'csv' } format.yaml { redirect_to_api_search 'yaml' } end end def redirect_to_api_search format redirect_to :action=>'search', :controller=>'api', :q => @search_term, :f => format end def do_search search_term, search_format postcode_districts = PostcodeDistrict.find_all_by_district(search_term) unless postcode_districts.empty? redirect_to :controller => 'postcodes', :action => 'show', :postcode => search_term, :format => search_format else postcode = Postcode.find_postcode_by_code(search_term) if postcode redirect_to :controller => 'postcodes', :action=>'show', :postcode => postcode.code, :format => search_format else stripped_term = search_term ? search_term.strip : '' if stripped_term.size > 2 constituencies = Constituency.find_all_name_or_member_name_matches(stripped_term) if constituencies.empty? flash[:not_found] = "not_found" flash[:last_search_term] = search_term if search_format show_error(search_format) else redirect_to root_url end elsif constituencies.size == 1 redirect_to :controller => 'constituencies', :action => 'show', :id => constituencies.first.friendly_id, :format => search_format else if params[:commit].blank? render_show else redirect_to :controller => 'search', :action=>'index', :q => search_term, :format => search_format end end else flash[:not_found] = "not_found" flash[:last_search_term] = search_term if search_format show_error(search_format) else redirect_to root_url end end end end end def show_error format @error_message = flash[:not_found] respond_to do |format| format.html format.xml { render :template => '/constituencies/show.xml.haml' } format.json { render :json => message_to_json("error", @error_message) } format.js { render :json => message_to_json("error", @error_message) } format.text { render :text => message_to_text("error", @error_message) } format.csv { render :text => message_to_csv("error", @error_message, "message", "content") } format.yaml { render :text => message_to_yaml("error", @error_message) } end end end \ No newline at end of file
robertbrook/findyourmp
b586a9ff9fb52487ed1a9e3c6a9a3df78910b0ea
better handling of blank search terms
diff --git a/app/controllers/search_controller.rb b/app/controllers/search_controller.rb index 9d26bd5..a20e8c2 100644 --- a/app/controllers/search_controller.rb +++ b/app/controllers/search_controller.rb @@ -1,107 +1,107 @@ class SearchController < ApplicationController def index params[:search_term] = params[:q] unless params[:q].blank? search_term = params[:search_term] - search_term.tr!('"', '') + search_term.tr!('"', '') unless search_term.nil? params[:format] = params[:f] unless params[:f].blank? search_format = params[:format] do_search search_term, search_format end def redir params[:search_term] = params[:q] unless params[:q].blank? search_term = params[:search_term] @search_term = search_term.gsub('+',' ') redirect_to :action => 'index', :q => @search_term end def show render_show end private def render_show flash.keep(:postcode) params[:search_term] = params[:q] unless params[:q].blank? @search_term = params[:search_term] @last_search_term = @search_term @constituencies, @members = Constituency.find_all_constituency_and_member_matches @search_term respond_to do |format| format.html { render :template => '/constituencies/show' } format.xml { redirect_to_api_search 'xml' } format.json { redirect_to_api_search 'json' } format.js { redirect_to_api_search 'js' } format.text { redirect_to_api_search 'text' } format.csv { redirect_to_api_search 'csv' } format.yaml { redirect_to_api_search 'yaml' } end end def redirect_to_api_search format redirect_to :action=>'search', :controller=>'api', :q => @search_term, :f => format end def do_search search_term, search_format postcode_districts = PostcodeDistrict.find_all_by_district(search_term) unless postcode_districts.empty? redirect_to :controller => 'postcodes', :action => 'show', :postcode => search_term, :format => search_format else postcode = Postcode.find_postcode_by_code(search_term) if postcode redirect_to :controller => 'postcodes', :action=>'show', :postcode => postcode.code, :format => search_format else stripped_term = search_term ? search_term.strip : '' if stripped_term.size > 2 constituencies = Constituency.find_all_name_or_member_name_matches(stripped_term) if constituencies.empty? flash[:not_found] = "not_found" flash[:last_search_term] = search_term if search_format show_error(search_format) else redirect_to root_url end elsif constituencies.size == 1 redirect_to :controller => 'constituencies', :action => 'show', :id => constituencies.first.friendly_id, :format => search_format else if params[:commit].blank? render_show else redirect_to :controller => 'search', :action=>'index', :q => search_term, :format => search_format end end else flash[:not_found] = "not_found" flash[:last_search_term] = search_term if search_format show_error(search_format) else redirect_to root_url end end end end end def show_error format @error_message = flash[:not_found] respond_to do |format| format.html format.xml { render :template => '/constituencies/show.xml.haml' } format.json { render :json => message_to_json("error", @error_message) } format.js { render :json => message_to_json("error", @error_message) } format.text { render :text => message_to_text("error", @error_message) } format.csv { render :text => message_to_csv("error", @error_message, "message", "content") } format.yaml { render :text => message_to_yaml("error", @error_message) } end end end \ No newline at end of file
robertbrook/findyourmp
3f000e6116a91aa3348ab045f1846f1150d53765
bug fix for patch_postcodes task
diff --git a/lib/data_loader.rb b/lib/data_loader.rb index ec5938e..1f0f3fa 100644 --- a/lib/data_loader.rb +++ b/lib/data_loader.rb @@ -1,495 +1,495 @@ require File.expand_path(File.dirname(__FILE__) + '/timer') module FindYourMP; end module FindYourMP::DataLoader include FindYourMP::Timer DATA_DIR = File.expand_path(File.dirname(__FILE__) + '/../data') MEMBER_FILE = "#{DATA_DIR}/FYMP_all.txt" CONSTITUENCY_FILE = "#{DATA_DIR}/new_constituencies.txt" POSTCODE_FILE = "#{DATA_DIR}/postcodes.txt" def diff_ons_ids old_file, new_file unless File.exist?(old_file) raise "#{old_file} not found" end unless File.exist?(new_file) raise "#{new_file} not found" end diff_file = "#{DATA_DIR}/diff_ons_ids.txt" if File.exist?(diff_file) cmd = "mv #{diff_file} #{diff_file}.#{Time.now.to_i.to_s}" puts cmd `#{cmd}` end constituencies_by_id = {} constituencies_by_name = {} old_data = File.open(old_file) old_data.each do |line| line.gsub!("\n", "") parts = line.split("\t") constituencies_by_id[parts[0]] = parts[1].strip constituencies_by_name[parts[1]] = parts[0] end new_data = File.open(new_file) output = File.open(diff_file, 'w') new_data.each do |line| line.gsub!("\n", "") parts = line.split("\t") name = parts[1].strip unless constituencies_by_id.has_key?(parts[0]) unless constituencies_by_name.has_key?(name) name.gsub!("&", "and") end if constituencies_by_name.has_key?(name) correction = "#{constituencies_by_name[name]}\t#{parts[0]}\n" output.write(correction) end end end end def patch_postcodes new_data = "\n" + File.open("#{DATA_DIR}/new_postcodes.txt").read start_timing Postcode.find_all_by_ons_id("0").each do |postcode| search_code = postcode.code if postcode.code.length < 6 code = "#{postcode.code[0..postcode.code.length-4]} #{postcode.code[postcode.code.length-3..postcode.code.length]}" elsif postcode.code.length < 7 code = "#{postcode.code[0..postcode.code.length-4]} #{postcode.code[postcode.code.length-3..postcode.code.length]}" end match = new_data.match(/\n#{code} ([A-Z0-9]{3})/) if match ons_id = match.values_at(1).to_s constituency = Constituency.find_by_ons_id(ons_id) postcode.ons_id = ons_id postcode.constituency_id = constituency.id postcode.save! else warn "trouble matching #{postcode.code}" end end BlacklistedPostcode.find_all_by_ons_id("0").each do |postcode| search_code = postcode.code if postcode.code.length < 6 code = "#{postcode.code[0..postcode.code.length-4]} #{postcode.code[postcode.code.length-3..postcode.code.length]}" elsif postcode.code.length < 7 code = "#{postcode.code[0..postcode.code.length-4]} #{postcode.code[postcode.code.length-3..postcode.code.length]}" end match = new_data.match(/\n#{code} ([A-Z0-9]{3})/) if match ons_id = match.values_at(1).to_s postcode.delete - Postcode.create! :code => postcode, :ons_id => ons_id + Postcode.create! :code => postcode.code, :ons_id => ons_id else warn "trouble matching #{postcode.code}" end end log_duration end def diff_postcodes old_file, new_file unless File.exist?(old_file) raise "#{old_file} not found" end unless File.exist?(new_file) raise "#{new_file} not found" end old_postcodes = "#{DATA_DIR}/old_postcodes.txt" new_postcodes = "#{DATA_DIR}/new_postcodes.txt" parse_postcodes old_file, old_postcodes parse_postcodes new_file, new_postcodes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if File.exist?(diff_file) cmd = "mv #{diff_file} #{diff_file}.#{Time.now.to_i.to_s}" puts cmd `#{cmd}` end cmd = "diff #{old_postcodes} #{new_postcodes} > #{diff_file}" puts cmd `#{cmd}` end def patch_ons_ids patch_file = "#{DATA_DIR}/diff_ons_ids.txt" unless File.exist?(patch_file) raise "#{patch_file} not found" end start_timing data = File.open(patch_file) data.each do |line| line.gsub!("\n", "") parts = line.split("\t") old_id = parts[0].strip new_id = parts[1].strip ActiveRecord::Base.connection.execute("UPDATE blacklisted_postcodes SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") ActiveRecord::Base.connection.execute("UPDATE manual_postcodes SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") ActiveRecord::Base.connection.execute("UPDATE constituencies SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") end log_duration end def determine_postcode_changes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if file_not_found(diff_file) puts "Generate or upload #{diff_file}" return end to_delete = {} to_create = {} to_update = {} IO.foreach(diff_file) do |line| parts = line.strip.split(' ') indicator = parts[0] if indicator[/(<|>)/] ons_id = parts.pop postcode = parts.join(' ').sub(indicator, '').strip if indicator == '<' to_delete[postcode] = ons_id elsif indicator == '>' to_create[postcode] = ons_id end end end to_create.keys.each do |postcode| if to_delete.delete(postcode) ons_id = to_create.delete(postcode) to_update[postcode] = ons_id end end puts 'to_delete ' + to_delete.size.to_s + ' e.g. ' + to_delete.to_a.first.inspect puts 'to_update ' + to_update.size.to_s + ' e.g. ' + to_update.to_a.first.inspect puts 'to_create ' + to_create.size.to_s + ' e.g. ' + to_create.to_a.first.inspect puts 'checking we have constituencies... ' (to_update.values + to_create.values).flatten.uniq.each do |ons_id| unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) raise "unexpected constituency id #{ons_id}" unless constituency end end puts 'all constituencies found' return [to_delete, to_update, to_create] end def update_postcodes to_delete, to_update, to_create = determine_postcode_changes # puts "Update database? y/n" # answer = STDIN.gets # if answer.strip == 'y' do_postcode_update to_delete, to_update, to_create # else # puts 'exiting without database update' # end end def ignore_ons_id?(ons_id) ons_id == '800' || ons_id == '900' end def analyze_postcode_update to_delete, to_update, to_create = determine_postcode_changes already_deleted = [] to_delete.each do |postcode, ons_id| already_deleted << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO DELETE, BUT ALREADY DELETED: #{already_deleted.size}" missing_updates = [] to_update.each do |postcode, ons_id| unless Postcode.exists?(:code => postcode.sub(' ','')) missing_updates << [postcode, ons_id] unless BlacklistedPostcode.exists?(:code => postcode.sub(' ','')) end end puts "TO UPDATE, BUT MISSING FROM DB: #{missing_updates.size}" already_there = [] to_create.each do |postcode, ons_id| if Postcode.exists?(:code => postcode.sub(' ','')) already_there << [postcode, ons_id] if ManualPostcode.exists?(:code => postcode.sub(' ','')) end end puts "TO CREATE, BUT ALREADY IN DB: #{already_there.size}" end def do_postcode_update to_delete, to_update, to_create puts 'do_postcode_update...' total = (to_delete.size + to_update.size + to_create.size).to_f count = 0 include ActionView::Helpers::DateHelper start_timing #process deletions to_delete.each do |postcode, ons_id| if post_code = Postcode.find_by_code(postcode.sub(' ','')) if ManualPostcode.find_by_code(postcode.sub(' ','')) warn "deleted postcode #{postcode}) exists as manual postcode" else post_code.destroy count = count.next log_duration count / total end else warn "cannot delete postcode, as it was not in database: #{postcode}" end end #process updates to_update.each do |postcode, ons_id| post_code = Postcode.find_by_code(postcode.sub(' ','')) if post_code unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) if constituency.nil? raise "cannot update postcode, as constituency was not in database: #{postcode} #{ons_id}" end end blacklisted = BlacklistedPostcode.find_by_code postcode.sub(' ','') if blacklisted puts " (deleting blacklisted postcode - #{postcode})" unless blacklisted.ons_id == ons_id blacklisted.delete end end post_code.ons_id = ons_id.strip if constituency post_code.constituency_id = constituency.id else post_code.constituency_id = nil end post_code.save count = count.next log_duration count / total else blacklisted = BlacklistedPostcode.find_by_code postcode.sub(' ', '') if blacklisted blacklisted.delete end constituency = Constituency.find_by_ons_id(ons_id) Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id, :constituency_id => constituency.id end end #process new postcodes to_create.each do |postcode, ons_id| unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) if constituency.nil? raise "cannot create postcode, as constituency was not in database: #{postcode} #{ons_id}" end begin if Postcode.exists?(:code => postcode.sub(' ','')) warn 'exists: ' + postcode elsif BlacklistedPostcode.find_by_code postcode.sub(' ','') warn 'exists (and blacklisted): ' + postcode else manual = ManualPostcode.find_by_code postcode.sub(' ', '') if manual manual.delete end constituency = Constituency.find_by_ons_id(ons_id) Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id, :constituency_id => constituency.id end rescue Exception => e raise e end end count = count.next log_duration count / total end log_duration end def load_members member_file member_file = MEMBER_FILE unless member_file return if file_not_found(member_file) lines = [] IO.foreach(member_file) do |line| line.strip! lines << line unless(line.blank? || line[/Constituency/]) end lines.each do |line| begin parts = line.split("\t") constituency_name = parts[0].strip member_name = parts[1].strip if is_vacant?(member_name) log "Constituency is vacant: #{constituency_name}" else existing, updated_constituency = Constituency.load_tsv_line(line) if existing && updated_constituency existing.attributes = updated_constituency.attributes existing.save! elsif updated_constituency log "Cannot find constituency for member for line: #{line}" else # nothing to update end end rescue Exception => e log "Cannot set member_name on constituency for: #{line} | #{e.to_s}" end end end def load_constituencies return if file_not_found(CONSTITUENCY_FILE) Constituency.delete_all Slug.delete_all IO.foreach(CONSTITUENCY_FILE) do |line| constituency_id = line[0..2] constituency_name = line[3..(line.length-1)].strip Constituency.create :name=>constituency_name, :ons_id=>constituency_id end end def parse_postcodes source_file, output_file=POSTCODE_FILE return if file_not_found(source_file) start_timing blank_date = ' ' blank_code = ' ' new_line = "\n" space = ' ' post_codes = [] IO.foreach(source_file) do |line| termination_date = line[29..34] if termination_date == blank_date consistuency_code = line[69..71] unless consistuency_code == blank_code post_code = line[0..6] post_codes << post_code << space << consistuency_code post_codes << new_line end end end log_duration start_timing File.open(output_file,'w') do |file| file.write(post_codes.join('')) end log_duration end def load_postcodes group_size=1000 return if file_not_found(POSTCODE_FILE) index = 0 groups = 0 puts 'saving data to db' Postcode.delete_all columns = [:code, :constituency_id] total = `cat #{POSTCODE_FILE} | wc -l` total = total.strip.to_f include ActionView::Helpers::DateHelper post_codes = [] start_timing IO.foreach(POSTCODE_FILE) do |line| code = line[0..6].tr(' ','') constituency_id = line[8..10] post_codes << [code, constituency_id] index = index.next if (index % group_size) == 0 load_codes(post_codes) groups = groups.next percentage_complete = (group_size * groups) / total log_duration percentage_complete post_codes = [] end end # complete remaining load_codes(post_codes) log_duration 1.0 end def load_postcode_districts PostcodeDistrict.delete_all sql = "SELECT SUBSTRING(code, 1, LENGTH(code)-3) " + "AS district, constituency_id " + "FROM postcodes " + "GROUP BY district, constituency_id;" districts = PostcodeDistrict.find_by_sql(sql) districts.each do |district| PostcodeDistrict.create!(district.attributes) end end def load_manual_postcodes manual_codes = ManualPostcode.all manual_codes.each do |manual_code| Postcode.create :code => manual_code.code, :constituency_id => manual_code.constituency_id, :ons_id => manual_code.ons_id end end private def load_codes(post_codes) post_codes.each do |codes| if BlacklistedPostcode.find_by_code codes[0] puts " (ignoring blacklisted postcode - #{codes[0]})" else Postcode.create :code => codes[0], :ons_id => codes[1] end end end def is_vacant?(name) name == 'Vacant' end def log msg $stderr.puts msg end def file_not_found file_name if File.exist?(file_name) false else log "Data file not found: #{file_name}" true end end end
robertbrook/findyourmp
02dc0445e65b7466fe215c28c2147bb92bbd8849
improved handling of new-format codes and blacklists during update; task to deal with changes to ONS codes; fix for "the Aldershot problem"
diff --git a/lib/data_loader.rb b/lib/data_loader.rb index bace783..ec5938e 100644 --- a/lib/data_loader.rb +++ b/lib/data_loader.rb @@ -1,420 +1,495 @@ require File.expand_path(File.dirname(__FILE__) + '/timer') module FindYourMP; end module FindYourMP::DataLoader include FindYourMP::Timer DATA_DIR = File.expand_path(File.dirname(__FILE__) + '/../data') MEMBER_FILE = "#{DATA_DIR}/FYMP_all.txt" CONSTITUENCY_FILE = "#{DATA_DIR}/new_constituencies.txt" POSTCODE_FILE = "#{DATA_DIR}/postcodes.txt" def diff_ons_ids old_file, new_file unless File.exist?(old_file) raise "#{old_file} not found" end unless File.exist?(new_file) raise "#{new_file} not found" end diff_file = "#{DATA_DIR}/diff_ons_ids.txt" if File.exist?(diff_file) cmd = "mv #{diff_file} #{diff_file}.#{Time.now.to_i.to_s}" puts cmd `#{cmd}` end constituencies_by_id = {} constituencies_by_name = {} old_data = File.open(old_file) old_data.each do |line| line.gsub!("\n", "") parts = line.split("\t") constituencies_by_id[parts[0]] = parts[1].strip constituencies_by_name[parts[1]] = parts[0] end new_data = File.open(new_file) output = File.open(diff_file, 'w') new_data.each do |line| line.gsub!("\n", "") parts = line.split("\t") + name = parts[1].strip unless constituencies_by_id.has_key?(parts[0]) - if constituencies_by_name.has_key?(parts[1].strip) - correction = "#{constituencies_by_name[parts[1].strip]}\t#{parts[0]}\n" + unless constituencies_by_name.has_key?(name) + name.gsub!("&", "and") + end + if constituencies_by_name.has_key?(name) + correction = "#{constituencies_by_name[name]}\t#{parts[0]}\n" output.write(correction) end end end end + def patch_postcodes + new_data = "\n" + File.open("#{DATA_DIR}/new_postcodes.txt").read + + start_timing + + Postcode.find_all_by_ons_id("0").each do |postcode| + search_code = postcode.code + if postcode.code.length < 6 + code = "#{postcode.code[0..postcode.code.length-4]} #{postcode.code[postcode.code.length-3..postcode.code.length]}" + elsif postcode.code.length < 7 + code = "#{postcode.code[0..postcode.code.length-4]} #{postcode.code[postcode.code.length-3..postcode.code.length]}" + end + match = new_data.match(/\n#{code} ([A-Z0-9]{3})/) + if match + ons_id = match.values_at(1).to_s + constituency = Constituency.find_by_ons_id(ons_id) + postcode.ons_id = ons_id + postcode.constituency_id = constituency.id + postcode.save! + else + warn "trouble matching #{postcode.code}" + end + end + + BlacklistedPostcode.find_all_by_ons_id("0").each do |postcode| + search_code = postcode.code + if postcode.code.length < 6 + code = "#{postcode.code[0..postcode.code.length-4]} #{postcode.code[postcode.code.length-3..postcode.code.length]}" + elsif postcode.code.length < 7 + code = "#{postcode.code[0..postcode.code.length-4]} #{postcode.code[postcode.code.length-3..postcode.code.length]}" + end + match = new_data.match(/\n#{code} ([A-Z0-9]{3})/) + if match + ons_id = match.values_at(1).to_s + postcode.delete + Postcode.create! :code => postcode, :ons_id => ons_id + else + warn "trouble matching #{postcode.code}" + end + end + + log_duration + end + def diff_postcodes old_file, new_file unless File.exist?(old_file) raise "#{old_file} not found" end - + unless File.exist?(new_file) raise "#{new_file} not found" end - + old_postcodes = "#{DATA_DIR}/old_postcodes.txt" new_postcodes = "#{DATA_DIR}/new_postcodes.txt" parse_postcodes old_file, old_postcodes parse_postcodes new_file, new_postcodes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if File.exist?(diff_file) cmd = "mv #{diff_file} #{diff_file}.#{Time.now.to_i.to_s}" puts cmd `#{cmd}` end cmd = "diff #{old_postcodes} #{new_postcodes} > #{diff_file}" puts cmd `#{cmd}` - end + end def patch_ons_ids patch_file = "#{DATA_DIR}/diff_ons_ids.txt" unless File.exist?(patch_file) raise "#{patch_file} not found" end start_timing data = File.open(patch_file) data.each do |line| line.gsub!("\n", "") parts = line.split("\t") old_id = parts[0].strip new_id = parts[1].strip ActiveRecord::Base.connection.execute("UPDATE blacklisted_postcodes SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") ActiveRecord::Base.connection.execute("UPDATE manual_postcodes SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") - ActiveRecord::Base.connection.execute("UPDATE postcodes SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") + ActiveRecord::Base.connection.execute("UPDATE constituencies SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") end log_duration end def determine_postcode_changes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if file_not_found(diff_file) puts "Generate or upload #{diff_file}" return end to_delete = {} to_create = {} to_update = {} IO.foreach(diff_file) do |line| parts = line.strip.split(' ') indicator = parts[0] if indicator[/(<|>)/] ons_id = parts.pop postcode = parts.join(' ').sub(indicator, '').strip if indicator == '<' to_delete[postcode] = ons_id elsif indicator == '>' to_create[postcode] = ons_id end end end to_create.keys.each do |postcode| if to_delete.delete(postcode) ons_id = to_create.delete(postcode) to_update[postcode] = ons_id end end puts 'to_delete ' + to_delete.size.to_s + ' e.g. ' + to_delete.to_a.first.inspect puts 'to_update ' + to_update.size.to_s + ' e.g. ' + to_update.to_a.first.inspect puts 'to_create ' + to_create.size.to_s + ' e.g. ' + to_create.to_a.first.inspect puts 'checking we have constituencies... ' - (to_delete.values + to_update.values + to_create.values).flatten.uniq.each do |ons_id| + (to_update.values + to_create.values).flatten.uniq.each do |ons_id| unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) raise "unexpected constituency id #{ons_id}" unless constituency end end puts 'all constituencies found' return [to_delete, to_update, to_create] end def update_postcodes to_delete, to_update, to_create = determine_postcode_changes # puts "Update database? y/n" # answer = STDIN.gets # if answer.strip == 'y' do_postcode_update to_delete, to_update, to_create # else # puts 'exiting without database update' # end end def ignore_ons_id?(ons_id) ons_id == '800' || ons_id == '900' end def analyze_postcode_update to_delete, to_update, to_create = determine_postcode_changes already_deleted = [] to_delete.each do |postcode, ons_id| already_deleted << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO DELETE, BUT ALREADY DELETED: #{already_deleted.size}" missing_updates = [] to_update.each do |postcode, ons_id| - missing_updates << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) + unless Postcode.exists?(:code => postcode.sub(' ','')) + missing_updates << [postcode, ons_id] unless BlacklistedPostcode.exists?(:code => postcode.sub(' ','')) + end end puts "TO UPDATE, BUT MISSING FROM DB: #{missing_updates.size}" already_there = [] to_create.each do |postcode, ons_id| - already_there << [postcode, ons_id] if Postcode.exists?(:code => postcode.sub(' ','')) + if Postcode.exists?(:code => postcode.sub(' ','')) + already_there << [postcode, ons_id] if ManualPostcode.exists?(:code => postcode.sub(' ','')) + end end puts "TO CREATE, BUT ALREADY IN DB: #{already_there.size}" end def do_postcode_update to_delete, to_update, to_create puts 'do_postcode_update...' total = (to_delete.size + to_update.size + to_create.size).to_f count = 0 include ActionView::Helpers::DateHelper start_timing + #process deletions to_delete.each do |postcode, ons_id| if post_code = Postcode.find_by_code(postcode.sub(' ','')) if ManualPostcode.find_by_code(postcode.sub(' ','')) - puts " (ignoring manually added postcode - #{postcode})" + warn "deleted postcode #{postcode}) exists as manual postcode" else post_code.destroy count = count.next log_duration count / total end else warn "cannot delete postcode, as it was not in database: #{postcode}" end end + + #process updates to_update.each do |postcode, ons_id| post_code = Postcode.find_by_code(postcode.sub(' ','')) if post_code unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) if constituency.nil? raise "cannot update postcode, as constituency was not in database: #{postcode} #{ons_id}" end end - if BlacklistedPostcode.find_by_code postcode.sub(' ','') + blacklisted = BlacklistedPostcode.find_by_code postcode.sub(' ','') + if blacklisted puts " (deleting blacklisted postcode - #{postcode})" - post_code.destroy - else - post_code.ons_id = ons_id.strip.to_i - if constituency - post_code.constituency_id = constituency.id - else - post_code.constituency_id = nil + unless blacklisted.ons_id == ons_id + blacklisted.delete end - post_code.save end - + post_code.ons_id = ons_id.strip + if constituency + post_code.constituency_id = constituency.id + else + post_code.constituency_id = nil + end + post_code.save + count = count.next log_duration count / total else - raise "cannot update postcode, as it was not in database: #{postcode} #{ons_id}" + blacklisted = BlacklistedPostcode.find_by_code postcode.sub(' ', '') + if blacklisted + blacklisted.delete + end + constituency = Constituency.find_by_ons_id(ons_id) + Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id, :constituency_id => constituency.id end end + #process new postcodes to_create.each do |postcode, ons_id| - begin - if Postcode.exists?(:code => postcode.sub(' ','')) - warn 'exists ' + postcode - elsif BlacklistedPostcode.find_by_code postcode.sub(' ','') - puts " (ignoring blacklisted postcode - #{postcode})" - else - Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id.strip.to_i + unless ignore_ons_id?(ons_id) + constituency = Constituency.find_by_ons_id(ons_id) + if constituency.nil? + raise "cannot create postcode, as constituency was not in database: #{postcode} #{ons_id}" + end + + begin + if Postcode.exists?(:code => postcode.sub(' ','')) + warn 'exists: ' + postcode + elsif BlacklistedPostcode.find_by_code postcode.sub(' ','') + warn 'exists (and blacklisted): ' + postcode + else + manual = ManualPostcode.find_by_code postcode.sub(' ', '') + if manual + manual.delete + end + constituency = Constituency.find_by_ons_id(ons_id) + Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id, :constituency_id => constituency.id + end + rescue Exception => e + raise e end - rescue Exception => e - raise e end count = count.next log_duration count / total end log_duration end def load_members member_file member_file = MEMBER_FILE unless member_file return if file_not_found(member_file) lines = [] IO.foreach(member_file) do |line| line.strip! lines << line unless(line.blank? || line[/Constituency/]) end lines.each do |line| begin parts = line.split("\t") constituency_name = parts[0].strip member_name = parts[1].strip if is_vacant?(member_name) log "Constituency is vacant: #{constituency_name}" else existing, updated_constituency = Constituency.load_tsv_line(line) if existing && updated_constituency existing.attributes = updated_constituency.attributes existing.save! elsif updated_constituency log "Cannot find constituency for member for line: #{line}" else # nothing to update end end rescue Exception => e log "Cannot set member_name on constituency for: #{line} | #{e.to_s}" end end end def load_constituencies return if file_not_found(CONSTITUENCY_FILE) Constituency.delete_all Slug.delete_all IO.foreach(CONSTITUENCY_FILE) do |line| constituency_id = line[0..2] constituency_name = line[3..(line.length-1)].strip Constituency.create :name=>constituency_name, :ons_id=>constituency_id end end def parse_postcodes source_file, output_file=POSTCODE_FILE return if file_not_found(source_file) start_timing blank_date = ' ' blank_code = ' ' new_line = "\n" space = ' ' post_codes = [] IO.foreach(source_file) do |line| termination_date = line[29..34] if termination_date == blank_date consistuency_code = line[69..71] unless consistuency_code == blank_code post_code = line[0..6] post_codes << post_code << space << consistuency_code post_codes << new_line end end end log_duration start_timing File.open(output_file,'w') do |file| file.write(post_codes.join('')) end log_duration end def load_postcodes group_size=1000 return if file_not_found(POSTCODE_FILE) index = 0 groups = 0 puts 'saving data to db' Postcode.delete_all columns = [:code, :constituency_id] total = `cat #{POSTCODE_FILE} | wc -l` total = total.strip.to_f include ActionView::Helpers::DateHelper post_codes = [] start_timing IO.foreach(POSTCODE_FILE) do |line| code = line[0..6].tr(' ','') constituency_id = line[8..10] post_codes << [code, constituency_id] index = index.next if (index % group_size) == 0 load_codes(post_codes) groups = groups.next percentage_complete = (group_size * groups) / total log_duration percentage_complete post_codes = [] end end # complete remaining load_codes(post_codes) log_duration 1.0 end def load_postcode_districts PostcodeDistrict.delete_all sql = "SELECT SUBSTRING(code, 1, LENGTH(code)-3) " + "AS district, constituency_id " + "FROM postcodes " + "GROUP BY district, constituency_id;" districts = PostcodeDistrict.find_by_sql(sql) districts.each do |district| PostcodeDistrict.create!(district.attributes) end end def load_manual_postcodes manual_codes = ManualPostcode.all manual_codes.each do |manual_code| Postcode.create :code => manual_code.code, :constituency_id => manual_code.constituency_id, :ons_id => manual_code.ons_id end end private def load_codes(post_codes) post_codes.each do |codes| if BlacklistedPostcode.find_by_code codes[0] puts " (ignoring blacklisted postcode - #{codes[0]})" else Postcode.create :code => codes[0], :ons_id => codes[1] end end end def is_vacant?(name) name == 'Vacant' end def log msg $stderr.puts msg end def file_not_found file_name if File.exist?(file_name) false else log "Data file not found: #{file_name}" true end end end diff --git a/lib/tasks/parse.rake b/lib/tasks/parse.rake index 21f6f7c..4a05838 100644 --- a/lib/tasks/parse.rake +++ b/lib/tasks/parse.rake @@ -1,111 +1,115 @@ require File.expand_path(File.dirname(__FILE__) + '/../data_loader') require File.expand_path(File.dirname(__FILE__) + '/../commons_member_biographies') require File.expand_path(File.dirname(__FILE__) + '/../cache_writer') require File.expand_path(File.dirname(__FILE__) + '/../constituency_upmystreet_links') require File.expand_path(File.dirname(__FILE__) + '/../boundary_changes') namespace :fymp do include FindYourMP::DataLoader include FindYourMP::CacheWriter include FindYourMP::BoundaryChanges desc "Create new_constituencies file for boundary changes" task :create_new_constituencies_file => :environment do create_new_constituencies_file end desc "Populate data for constituencies in DB" task :constituencies => :environment do load_constituencies end desc "Populate data for members in DB" task :members => :environment do file = ENV['file'] load_members file end desc "Create cache of all postcode pages" task :make_cache => :environment do make_cache end desc "Parse data file for postcode and constituency ID *only*" task :parse_postcodes do source_file = ENV['source'] if source_file parse_postcodes source_file else puts 'USAGE: rake fymp:parse_postcodes source=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end desc "Parse data file for postcode and constituency ID *only*" task :parse_new_postcodes do old_file = ENV['oldfile'] new_file = ENV['newfile'] output_file = ENV['output'] if old_file && new_file parse_new_postcodes old_file, new_file, output_file else puts 'USAGE: rake fymp:parse_new_postcodes oldfile=data/postcodes.txt newfile=data/pcd_pcon_aug_2009_uk_lu/pcd_pcon_aug_2009_uk_lu.txt output=data/new_postcodes.txt' end end task :diff_ons_ids => :environment do old_file = ENV['old'] new_file = ENV['new'] if old_file && new_file diff_ons_ids old_file, new_file else puts 'USAGE: rake fymp:diff_ons_ids old=data/constituencies.txt new=data/new_constituencies.txt' end end task :patch_ons_ids => :environment do patch_ons_ids end desc "Update postcodes from data files for postcode and constituency ID *only*" task :diff_postcodes => :environment do old_file = ENV['old'] new_file = ENV['new'] if old_file && new_file diff_postcodes old_file, new_file else puts 'USAGE: rake fymp:diff_postcodes old=data/NSPDF_FEB_2009_UK_1M.txt new=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end desc "Only analyze potential postcode update and log db discrepancies" task :analyze_postcode_update => :environment do analyze_postcode_update end + + task :patch_postcodes => :environment do + patch_postcodes + end desc "Update postcodes from data files for postcode and constituency ID *only*" task :update_postcodes => :environment do puts 'USAGE: rake fymp:update_postcodes' update_postcodes end desc "Populate data for postcode and constituency ID in DB" task :populate => :environment do load_postcodes end desc "Populate the postcode districts table" task :load_postcode_districts => :environment do load_postcode_districts end desc "Populate the manually added postcodes" task :load_manual_postcodes => :environment do load_manual_postcodes end desc "Populate the upmystreet lookup table" task :load_upmystreet_lookup => :environment do load_upmystreetcodes end end
robertbrook/findyourmp
343898ee041078ac98918c7dabe7684802e8a42a
early stages of rake tasks to deal with ONS code changes
diff --git a/lib/data_loader.rb b/lib/data_loader.rb index 66716e8..bace783 100644 --- a/lib/data_loader.rb +++ b/lib/data_loader.rb @@ -1,356 +1,420 @@ require File.expand_path(File.dirname(__FILE__) + '/timer') module FindYourMP; end module FindYourMP::DataLoader include FindYourMP::Timer DATA_DIR = File.expand_path(File.dirname(__FILE__) + '/../data') MEMBER_FILE = "#{DATA_DIR}/FYMP_all.txt" CONSTITUENCY_FILE = "#{DATA_DIR}/new_constituencies.txt" POSTCODE_FILE = "#{DATA_DIR}/postcodes.txt" + def diff_ons_ids old_file, new_file + unless File.exist?(old_file) + raise "#{old_file} not found" + end + + unless File.exist?(new_file) + raise "#{new_file} not found" + end + + diff_file = "#{DATA_DIR}/diff_ons_ids.txt" + if File.exist?(diff_file) + cmd = "mv #{diff_file} #{diff_file}.#{Time.now.to_i.to_s}" + puts cmd + `#{cmd}` + end + + constituencies_by_id = {} + constituencies_by_name = {} + old_data = File.open(old_file) + old_data.each do |line| + line.gsub!("\n", "") + parts = line.split("\t") + constituencies_by_id[parts[0]] = parts[1].strip + constituencies_by_name[parts[1]] = parts[0] + end + + new_data = File.open(new_file) + output = File.open(diff_file, 'w') + new_data.each do |line| + line.gsub!("\n", "") + parts = line.split("\t") + unless constituencies_by_id.has_key?(parts[0]) + if constituencies_by_name.has_key?(parts[1].strip) + correction = "#{constituencies_by_name[parts[1].strip]}\t#{parts[0]}\n" + output.write(correction) + end + end + end + end + def diff_postcodes old_file, new_file unless File.exist?(old_file) raise "#{old_file} not found" end unless File.exist?(new_file) raise "#{new_file} not found" end old_postcodes = "#{DATA_DIR}/old_postcodes.txt" new_postcodes = "#{DATA_DIR}/new_postcodes.txt" parse_postcodes old_file, old_postcodes parse_postcodes new_file, new_postcodes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if File.exist?(diff_file) cmd = "mv #{diff_file} #{diff_file}.#{Time.now.to_i.to_s}" puts cmd `#{cmd}` end cmd = "diff #{old_postcodes} #{new_postcodes} > #{diff_file}" puts cmd `#{cmd}` end + + def patch_ons_ids + patch_file = "#{DATA_DIR}/diff_ons_ids.txt" + + unless File.exist?(patch_file) + raise "#{patch_file} not found" + end + + start_timing + + data = File.open(patch_file) + data.each do |line| + line.gsub!("\n", "") + parts = line.split("\t") + old_id = parts[0].strip + new_id = parts[1].strip + + ActiveRecord::Base.connection.execute("UPDATE blacklisted_postcodes SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") + ActiveRecord::Base.connection.execute("UPDATE manual_postcodes SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") + ActiveRecord::Base.connection.execute("UPDATE postcodes SET ons_id = '#{new_id}' WHERE ons_id = '#{old_id}';") + end + + log_duration + end def determine_postcode_changes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if file_not_found(diff_file) puts "Generate or upload #{diff_file}" return end to_delete = {} to_create = {} to_update = {} IO.foreach(diff_file) do |line| parts = line.strip.split(' ') indicator = parts[0] if indicator[/(<|>)/] ons_id = parts.pop postcode = parts.join(' ').sub(indicator, '').strip if indicator == '<' to_delete[postcode] = ons_id elsif indicator == '>' to_create[postcode] = ons_id end end end to_create.keys.each do |postcode| if to_delete.delete(postcode) ons_id = to_create.delete(postcode) to_update[postcode] = ons_id end end puts 'to_delete ' + to_delete.size.to_s + ' e.g. ' + to_delete.to_a.first.inspect puts 'to_update ' + to_update.size.to_s + ' e.g. ' + to_update.to_a.first.inspect puts 'to_create ' + to_create.size.to_s + ' e.g. ' + to_create.to_a.first.inspect puts 'checking we have constituencies... ' (to_delete.values + to_update.values + to_create.values).flatten.uniq.each do |ons_id| unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) raise "unexpected constituency id #{ons_id}" unless constituency end end puts 'all constituencies found' return [to_delete, to_update, to_create] end def update_postcodes to_delete, to_update, to_create = determine_postcode_changes # puts "Update database? y/n" # answer = STDIN.gets # if answer.strip == 'y' do_postcode_update to_delete, to_update, to_create # else # puts 'exiting without database update' # end end def ignore_ons_id?(ons_id) ons_id == '800' || ons_id == '900' end def analyze_postcode_update to_delete, to_update, to_create = determine_postcode_changes already_deleted = [] to_delete.each do |postcode, ons_id| already_deleted << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO DELETE, BUT ALREADY DELETED: #{already_deleted.size}" missing_updates = [] to_update.each do |postcode, ons_id| missing_updates << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO UPDATE, BUT MISSING FROM DB: #{missing_updates.size}" already_there = [] to_create.each do |postcode, ons_id| already_there << [postcode, ons_id] if Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO CREATE, BUT ALREADY IN DB: #{already_there.size}" end def do_postcode_update to_delete, to_update, to_create puts 'do_postcode_update...' total = (to_delete.size + to_update.size + to_create.size).to_f count = 0 include ActionView::Helpers::DateHelper start_timing to_delete.each do |postcode, ons_id| if post_code = Postcode.find_by_code(postcode.sub(' ','')) if ManualPostcode.find_by_code(postcode.sub(' ','')) puts " (ignoring manually added postcode - #{postcode})" else post_code.destroy count = count.next log_duration count / total end else warn "cannot delete postcode, as it was not in database: #{postcode}" end end to_update.each do |postcode, ons_id| post_code = Postcode.find_by_code(postcode.sub(' ','')) if post_code unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) if constituency.nil? raise "cannot update postcode, as constituency was not in database: #{postcode} #{ons_id}" end end if BlacklistedPostcode.find_by_code postcode.sub(' ','') puts " (deleting blacklisted postcode - #{postcode})" post_code.destroy else post_code.ons_id = ons_id.strip.to_i if constituency post_code.constituency_id = constituency.id else post_code.constituency_id = nil end post_code.save end count = count.next log_duration count / total else raise "cannot update postcode, as it was not in database: #{postcode} #{ons_id}" end end to_create.each do |postcode, ons_id| begin if Postcode.exists?(:code => postcode.sub(' ','')) warn 'exists ' + postcode elsif BlacklistedPostcode.find_by_code postcode.sub(' ','') puts " (ignoring blacklisted postcode - #{postcode})" else Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id.strip.to_i end rescue Exception => e raise e end count = count.next log_duration count / total end log_duration end def load_members member_file member_file = MEMBER_FILE unless member_file return if file_not_found(member_file) lines = [] IO.foreach(member_file) do |line| line.strip! lines << line unless(line.blank? || line[/Constituency/]) end lines.each do |line| begin parts = line.split("\t") constituency_name = parts[0].strip member_name = parts[1].strip if is_vacant?(member_name) log "Constituency is vacant: #{constituency_name}" else existing, updated_constituency = Constituency.load_tsv_line(line) if existing && updated_constituency existing.attributes = updated_constituency.attributes existing.save! elsif updated_constituency log "Cannot find constituency for member for line: #{line}" else # nothing to update end end rescue Exception => e log "Cannot set member_name on constituency for: #{line} | #{e.to_s}" end end end def load_constituencies return if file_not_found(CONSTITUENCY_FILE) Constituency.delete_all Slug.delete_all IO.foreach(CONSTITUENCY_FILE) do |line| constituency_id = line[0..2] constituency_name = line[3..(line.length-1)].strip Constituency.create :name=>constituency_name, :ons_id=>constituency_id end end def parse_postcodes source_file, output_file=POSTCODE_FILE return if file_not_found(source_file) start_timing blank_date = ' ' blank_code = ' ' new_line = "\n" space = ' ' post_codes = [] IO.foreach(source_file) do |line| termination_date = line[29..34] if termination_date == blank_date consistuency_code = line[69..71] unless consistuency_code == blank_code post_code = line[0..6] post_codes << post_code << space << consistuency_code post_codes << new_line end end end log_duration start_timing File.open(output_file,'w') do |file| file.write(post_codes.join('')) end log_duration end def load_postcodes group_size=1000 return if file_not_found(POSTCODE_FILE) index = 0 groups = 0 puts 'saving data to db' Postcode.delete_all columns = [:code, :constituency_id] total = `cat #{POSTCODE_FILE} | wc -l` total = total.strip.to_f include ActionView::Helpers::DateHelper post_codes = [] start_timing IO.foreach(POSTCODE_FILE) do |line| code = line[0..6].tr(' ','') constituency_id = line[8..10] post_codes << [code, constituency_id] index = index.next if (index % group_size) == 0 load_codes(post_codes) groups = groups.next percentage_complete = (group_size * groups) / total log_duration percentage_complete post_codes = [] end end # complete remaining load_codes(post_codes) log_duration 1.0 end def load_postcode_districts PostcodeDistrict.delete_all sql = "SELECT SUBSTRING(code, 1, LENGTH(code)-3) " + "AS district, constituency_id " + "FROM postcodes " + "GROUP BY district, constituency_id;" districts = PostcodeDistrict.find_by_sql(sql) districts.each do |district| PostcodeDistrict.create!(district.attributes) end end def load_manual_postcodes manual_codes = ManualPostcode.all manual_codes.each do |manual_code| Postcode.create :code => manual_code.code, :constituency_id => manual_code.constituency_id, :ons_id => manual_code.ons_id end end private def load_codes(post_codes) post_codes.each do |codes| if BlacklistedPostcode.find_by_code codes[0] puts " (ignoring blacklisted postcode - #{codes[0]})" else Postcode.create :code => codes[0], :ons_id => codes[1] end end end def is_vacant?(name) name == 'Vacant' end def log msg $stderr.puts msg end def file_not_found file_name if File.exist?(file_name) false else log "Data file not found: #{file_name}" true end end end diff --git a/lib/tasks/parse.rake b/lib/tasks/parse.rake index 661942e..21f6f7c 100644 --- a/lib/tasks/parse.rake +++ b/lib/tasks/parse.rake @@ -1,97 +1,111 @@ require File.expand_path(File.dirname(__FILE__) + '/../data_loader') require File.expand_path(File.dirname(__FILE__) + '/../commons_member_biographies') require File.expand_path(File.dirname(__FILE__) + '/../cache_writer') require File.expand_path(File.dirname(__FILE__) + '/../constituency_upmystreet_links') require File.expand_path(File.dirname(__FILE__) + '/../boundary_changes') namespace :fymp do include FindYourMP::DataLoader include FindYourMP::CacheWriter include FindYourMP::BoundaryChanges desc "Create new_constituencies file for boundary changes" task :create_new_constituencies_file => :environment do create_new_constituencies_file end desc "Populate data for constituencies in DB" task :constituencies => :environment do load_constituencies end desc "Populate data for members in DB" task :members => :environment do file = ENV['file'] load_members file end desc "Create cache of all postcode pages" task :make_cache => :environment do make_cache end desc "Parse data file for postcode and constituency ID *only*" task :parse_postcodes do source_file = ENV['source'] if source_file parse_postcodes source_file else puts 'USAGE: rake fymp:parse_postcodes source=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end desc "Parse data file for postcode and constituency ID *only*" task :parse_new_postcodes do old_file = ENV['oldfile'] new_file = ENV['newfile'] output_file = ENV['output'] if old_file && new_file parse_new_postcodes old_file, new_file, output_file else puts 'USAGE: rake fymp:parse_new_postcodes oldfile=data/postcodes.txt newfile=data/pcd_pcon_aug_2009_uk_lu/pcd_pcon_aug_2009_uk_lu.txt output=data/new_postcodes.txt' end end + task :diff_ons_ids => :environment do + old_file = ENV['old'] + new_file = ENV['new'] + if old_file && new_file + diff_ons_ids old_file, new_file + else + puts 'USAGE: rake fymp:diff_ons_ids old=data/constituencies.txt new=data/new_constituencies.txt' + end + end + + task :patch_ons_ids => :environment do + patch_ons_ids + end + desc "Update postcodes from data files for postcode and constituency ID *only*" task :diff_postcodes => :environment do old_file = ENV['old'] new_file = ENV['new'] if old_file && new_file diff_postcodes old_file, new_file else puts 'USAGE: rake fymp:diff_postcodes old=data/NSPDF_FEB_2009_UK_1M.txt new=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end desc "Only analyze potential postcode update and log db discrepancies" task :analyze_postcode_update => :environment do analyze_postcode_update end desc "Update postcodes from data files for postcode and constituency ID *only*" task :update_postcodes => :environment do puts 'USAGE: rake fymp:update_postcodes' update_postcodes end desc "Populate data for postcode and constituency ID in DB" task :populate => :environment do load_postcodes end desc "Populate the postcode districts table" task :load_postcode_districts => :environment do load_postcode_districts end desc "Populate the manually added postcodes" task :load_manual_postcodes => :environment do load_manual_postcodes end desc "Populate the upmystreet lookup table" task :load_upmystreet_lookup => :environment do load_upmystreetcodes end end
robertbrook/findyourmp
55477900f6150ed158161338a31b8d0273b19cc1
more prominent link to member biography pages
diff --git a/app/views/constituencies/_member.haml b/app/views/constituencies/_member.haml index 7903e72..6797771 100644 --- a/app/views/constituencies/_member.haml +++ b/app/views/constituencies/_member.haml @@ -1,15 +1,20 @@ .text - if @constituency.no_sitting_member? %p There is no sitting Member of Parliament for this constituency. - else - member_name = h(@constituency.member_name) .row_item .row_label Member for this constituency .row_value - if @constituency.member_biography_url? = link_to member_name, @constituency.member_biography_url - else = member_name .row_item .row_label Party .row_value= h(@constituency.member_party) + - if @constituency.member_biography_url? + %p + %br + = link_to "More information about #{member_name} MP", @constituency.member_biography_url +
robertbrook/findyourmp
4fd2aab8670ba571a48513194450cd8e4ceccc28
fixed failing features
diff --git a/app/views/layouts/_search_form.haml b/app/views/layouts/_search_form.haml index fc9c04c..6958d89 100644 --- a/app/views/layouts/_search_form.haml +++ b/app/views/layouts/_search_form.haml @@ -1,10 +1,10 @@ -- form_tag(search_url, :method => :get) do +- form_tag(search_url, :method => :get, :class => "search") do = text_field_tag 'q', (@last_search_term ? h(sanitize(@last_search_term)) : ''), :size => 24 = submit_tag 'Find MP' - if flash[:not_found] && flash[:last_search_term] %div.text.flash - if flash[:last_search_term].strip.size < 3 = "<p>Sorry: we need more than two letters to search</p>" - else = "<p>Sorry: we couldn't find a constituency or MP when we searched for <code>#{h(sanitize(flash[:last_search_term]))}</code>. If you were searching for a postcode, please go back and check the postcode you entered, and ensure you have entered a <strong>complete</strong> postcode. If you were looking for a Member you may wish to check the <a class=\"warn\" href=\"http://www.parliament.uk/directories/hciolists/alms.cfm\">alphabetical list of Members</a> instead.</p> <p>If you are an expatriate, in an overseas territory, a Crown dependency or in the Armed Forces without a postcode, this service cannot be used to find your MP.</p><p>If you have entered a valid postcode which has not found an MP or constituency, please contact the House of Commons Information Office on 020 7219 4272 or email <a href=\"mailto:hcinfo@parliament.uk\" class=\"warn\">hcinfo@parliament.uk</a></p>" diff --git a/features/edit_constituency_data.feature b/features/edit_constituency_data.feature index 3ffc12c..df25604 100644 --- a/features/edit_constituency_data.feature +++ b/features/edit_constituency_data.feature @@ -1,41 +1,39 @@ Feature: Edit constituency data In order to have correct information on website as a admin user want to edit constituency and member data Scenario: Follow the "edit" link from constituency page Given I am logged in as an admin user And I follow "Edit constituencies" And I follow "Aberdeen North" Then I should see Edit Constituency Form Scenario: Edit constituency and member details Given I am logged in as an admin user And I am on the Constituency edit page for "Aberdeen North" When I fill in "Constituency" with "Aberdeen East" And I fill in "Member" with "William Wallace" And I fill in "Member party" with "SNP" And I fill in "Member email" with "bill@parl.uk" And I fill in "Member biography url" with "http://the.re" - And I fill in "Member website" with "http://it.is" And I press "Update" Then I should see "Aberdeen East" And I should see "William Wallace" And I should see "SNP" And I should see link to "http://the.re" - And I should see link to "http://it.is" Scenario: Edit member email to be empty Given I am logged in as an admin user And I am on the Constituency edit page for "Aberdeen North" When I fill in "Member email" with "" And I press "Update" Then I should see "Frank Doran" Scenario: Set member requested contact url Given I am logged in as an admin user And I am on the Constituency edit page for "Aberdeen North" When I fill in "Requested contact url" with "http://member.requested.url/" And I press "Update" Then I should see "Frank Doran" diff --git a/features/step_definitions/find_mp_from_postcode_steps.rb b/features/step_definitions/find_mp_from_postcode_steps.rb index 47f9b27..e999df7 100644 --- a/features/step_definitions/find_mp_from_postcode_steps.rb +++ b/features/step_definitions/find_mp_from_postcode_steps.rb @@ -1,8 +1,10 @@ -When /^I search for "(.*)"$/ do |postcode_code| - When "I fill in \"q\" with \"#{postcode_code}\"" +When /^I search for "(.*)"$/ do |search_term| + within '.search' do + fill_in("q", :with => search_term) + end And 'I press "Find MP"' end Given /I am on the Front page/ do visit "/" end
robertbrook/findyourmp
2bfedad9536a3fb6c2e8b489afd557acc78f34ad
removed website link; closes gh-11
diff --git a/app/views/constituencies/_member.haml b/app/views/constituencies/_member.haml index 419abc6..7903e72 100644 --- a/app/views/constituencies/_member.haml +++ b/app/views/constituencies/_member.haml @@ -1,20 +1,15 @@ .text - if @constituency.no_sitting_member? %p There is no sitting Member of Parliament for this constituency. - else - member_name = h(@constituency.member_name) .row_item .row_label Member for this constituency .row_value - if @constituency.member_biography_url? = link_to member_name, @constituency.member_biography_url - else = member_name .row_item .row_label Party .row_value= h(@constituency.member_party) - - if @constituency.member_website? - .row_item - .row_label Website - .row_value - = link_to h(@constituency.member_website.sub('http://','').chomp('/')), @constituency.member_website
robertbrook/findyourmp
3d64b4149f0e25efc430da1c3648f3a6f71ffd6c
removed postal address; closes gh-11
diff --git a/app/views/constituencies/_member.haml b/app/views/constituencies/_member.haml index 1a85608..419abc6 100644 --- a/app/views/constituencies/_member.haml +++ b/app/views/constituencies/_member.haml @@ -1,23 +1,20 @@ .text - if @constituency.no_sitting_member? %p There is no sitting Member of Parliament for this constituency. - else - member_name = h(@constituency.member_name) .row_item .row_label Member for this constituency .row_value - if @constituency.member_biography_url? = link_to member_name, @constituency.member_biography_url - else = member_name .row_item .row_label Party .row_value= h(@constituency.member_party) - if @constituency.member_website? .row_item .row_label Website .row_value = link_to h(@constituency.member_website.sub('http://','').chomp('/')), @constituency.member_website - .row_item - .row_label Address - .row_value= "#{member_name}, House of Commons, London SW1A 0AA"
robertbrook/findyourmp
015664e69527a203f998ac67d699ac2f12096ea5
changed the "show" link to read "View page" in the edit screen; closes gh-8
diff --git a/app/views/constituencies/index.haml b/app/views/constituencies/index.haml index eae6986..1ee3ea4 100644 --- a/app/views/constituencies/index.haml +++ b/app/views/constituencies/index.haml @@ -1,25 +1,25 @@ - @crumbtrail = link_to_admin_home - @title = 'Constituencies' = button_to("Hide all members", :action => 'hide_members') = button_to("Unhide all members", :action => 'unhide_members') %table.text %tbody - constituencies = sort_constituencies(@constituencies) - for constituency in constituencies %tr %td= h constituency.code %td= link_to h(constituency.name), edit_constituency_path(constituency) %td - unless constituency.member_name.blank? - if constituency.member_visible = h constituency.member_name - else %span.hidden_member= h(constituency.member_name) + ' (hidden)' %td - = link_to 'Show', constituency_path(constituency) + = link_to 'View page', constituency_path(constituency) - #%td= link_to 'Destroy', constituency_path(constituency), :confirm => 'Are you sure?', :method => :delete - # %p.text= link_to 'New constituency', new_constituency_path \ No newline at end of file
robertbrook/findyourmp
da326be02600def1585d239c623587939e733264
blacklist handling postcodes with a space correctly; blacklist add button no longer says "search"
diff --git a/app/controllers/blacklisted_postcodes_controller.rb b/app/controllers/blacklisted_postcodes_controller.rb index bdd60c3..23c4429 100644 --- a/app/controllers/blacklisted_postcodes_controller.rb +++ b/app/controllers/blacklisted_postcodes_controller.rb @@ -1,40 +1,40 @@ class BlacklistedPostcodesController < ApplicationController before_filter :require_admin_user def index @blacklist = BlacklistedPostcode.all end def restore - code = params[:code] + code = params[:code].squeeze(' ').gsub(' ', '') blacklisted_code = BlacklistedPostcode.find_by_code code unless blacklisted_code.nil? blacklisted_code.restore end redirect_to :blacklisted_postcodes end def new if request.post? if params[:commit] == 'Confirm' code = flash[:code] postcode = Postcode.find_by_code code flash[:code] = nil postcode.blacklist unless postcode.nil? redirect_to :blacklisted_postcodes else if params[:blacklist] - code = params[:blacklist][:code] + code = params[:blacklist][:code].squeeze(' ').gsub(' ', '') unless code.nil? flash[:code] = code @postcode = Postcode.find_by_code code end end end end end end \ No newline at end of file diff --git a/app/views/blacklisted_postcodes/new.haml b/app/views/blacklisted_postcodes/new.haml index 6164e45..cef682d 100644 --- a/app/views/blacklisted_postcodes/new.haml +++ b/app/views/blacklisted_postcodes/new.haml @@ -1,25 +1,25 @@ -@title = 'Blacklisted postcodes' - @crumbtrail = link_to_admin_home - form_tag('/admin/blacklist/new', :method => :post) do = text_field 'blacklist', 'code' - = submit_tag 'Search' + = submit_tag 'Add to blacklist' %br %div.text -if request.post? -if @postcode You are about to blacklist <code> = @postcode.code </code>, please click to confirm -form_tag('/admin/blacklist/new', :method => :post) do =submit_tag 'Confirm' -else - Sorry this postcode does not exist, please try again + Sorry this postcode is not currently in the database, please try again %p.text = link_to 'Return to list', blacklisted_postcodes_path %p.text %br = link_to 'Admin home', admin_path \ No newline at end of file
robertbrook/findyourmp
f0acf2b2ea550e9c3ba789ba2e5a746030d53f33
restoring the prototype.js file
diff --git a/public/javascripts/prototype.js b/public/javascripts/prototype.js new file mode 100644 index 0000000..dfe8ab4 --- /dev/null +++ b/public/javascripts/prototype.js @@ -0,0 +1,4320 @@ +/* Prototype JavaScript framework, version 1.6.0.3 + * (c) 2005-2008 Sam Stephenson + * + * Prototype is freely distributable under the terms of an MIT-style license. + * For details, see the Prototype web site: http://www.prototypejs.org/ + * + *--------------------------------------------------------------------------*/ + +var Prototype = { + Version: '1.6.0.3', + + Browser: { + IE: !!(window.attachEvent && + navigator.userAgent.indexOf('Opera') === -1), + Opera: navigator.userAgent.indexOf('Opera') > -1, + WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1, + Gecko: navigator.userAgent.indexOf('Gecko') > -1 && + navigator.userAgent.indexOf('KHTML') === -1, + MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/) + }, + + BrowserFeatures: { + XPath: !!document.evaluate, + SelectorsAPI: !!document.querySelector, + ElementExtensions: !!window.HTMLElement, + SpecificElementExtensions: + document.createElement('div')['__proto__'] && + document.createElement('div')['__proto__'] !== + document.createElement('form')['__proto__'] + }, + + ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>', + JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/, + + emptyFunction: function() { }, + K: function(x) { return x } +}; + +if (Prototype.Browser.MobileSafari) + Prototype.BrowserFeatures.SpecificElementExtensions = false; + + +/* Based on Alex Arnell's inheritance implementation. */ +var Class = { + create: function() { + var parent = null, properties = $A(arguments); + if (Object.isFunction(properties[0])) + parent = properties.shift(); + + function klass() { + this.initialize.apply(this, arguments); + } + + Object.extend(klass, Class.Methods); + klass.superclass = parent; + klass.subclasses = []; + + if (parent) { + var subclass = function() { }; + subclass.prototype = parent.prototype; + klass.prototype = new subclass; + parent.subclasses.push(klass); + } + + for (var i = 0; i < properties.length; i++) + klass.addMethods(properties[i]); + + if (!klass.prototype.initialize) + klass.prototype.initialize = Prototype.emptyFunction; + + klass.prototype.constructor = klass; + + return klass; + } +}; + +Class.Methods = { + addMethods: function(source) { + var ancestor = this.superclass && this.superclass.prototype; + var properties = Object.keys(source); + + if (!Object.keys({ toString: true }).length) + properties.push("toString", "valueOf"); + + for (var i = 0, length = properties.length; i < length; i++) { + var property = properties[i], value = source[property]; + if (ancestor && Object.isFunction(value) && + value.argumentNames().first() == "$super") { + var method = value; + value = (function(m) { + return function() { return ancestor[m].apply(this, arguments) }; + })(property).wrap(method); + + value.valueOf = method.valueOf.bind(method); + value.toString = method.toString.bind(method); + } + this.prototype[property] = value; + } + + return this; + } +}; + +var Abstract = { }; + +Object.extend = function(destination, source) { + for (var property in source) + destination[property] = source[property]; + return destination; +}; + +Object.extend(Object, { + inspect: function(object) { + try { + if (Object.isUndefined(object)) return 'undefined'; + if (object === null) return 'null'; + return object.inspect ? object.inspect() : String(object); + } catch (e) { + if (e instanceof RangeError) return '...'; + throw e; + } + }, + + toJSON: function(object) { + var type = typeof object; + switch (type) { + case 'undefined': + case 'function': + case 'unknown': return; + case 'boolean': return object.toString(); + } + + if (object === null) return 'null'; + if (object.toJSON) return object.toJSON(); + if (Object.isElement(object)) return; + + var results = []; + for (var property in object) { + var value = Object.toJSON(object[property]); + if (!Object.isUndefined(value)) + results.push(property.toJSON() + ': ' + value); + } + + return '{' + results.join(', ') + '}'; + }, + + toQueryString: function(object) { + return $H(object).toQueryString(); + }, + + toHTML: function(object) { + return object && object.toHTML ? object.toHTML() : String.interpret(object); + }, + + keys: function(object) { + var keys = []; + for (var property in object) + keys.push(property); + return keys; + }, + + values: function(object) { + var values = []; + for (var property in object) + values.push(object[property]); + return values; + }, + + clone: function(object) { + return Object.extend({ }, object); + }, + + isElement: function(object) { + return !!(object && object.nodeType == 1); + }, + + isArray: function(object) { + return object != null && typeof object == "object" && + 'splice' in object && 'join' in object; + }, + + isHash: function(object) { + return object instanceof Hash; + }, + + isFunction: function(object) { + return typeof object == "function"; + }, + + isString: function(object) { + return typeof object == "string"; + }, + + isNumber: function(object) { + return typeof object == "number"; + }, + + isUndefined: function(object) { + return typeof object == "undefined"; + } +}); + +Object.extend(Function.prototype, { + argumentNames: function() { + var names = this.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1] + .replace(/\s+/g, '').split(','); + return names.length == 1 && !names[0] ? [] : names; + }, + + bind: function() { + if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this; + var __method = this, args = $A(arguments), object = args.shift(); + return function() { + return __method.apply(object, args.concat($A(arguments))); + } + }, + + bindAsEventListener: function() { + var __method = this, args = $A(arguments), object = args.shift(); + return function(event) { + return __method.apply(object, [event || window.event].concat(args)); + } + }, + + curry: function() { + if (!arguments.length) return this; + var __method = this, args = $A(arguments); + return function() { + return __method.apply(this, args.concat($A(arguments))); + } + }, + + delay: function() { + var __method = this, args = $A(arguments), timeout = args.shift() * 1000; + return window.setTimeout(function() { + return __method.apply(__method, args); + }, timeout); + }, + + defer: function() { + var args = [0.01].concat($A(arguments)); + return this.delay.apply(this, args); + }, + + wrap: function(wrapper) { + var __method = this; + return function() { + return wrapper.apply(this, [__method.bind(this)].concat($A(arguments))); + } + }, + + methodize: function() { + if (this._methodized) return this._methodized; + var __method = this; + return this._methodized = function() { + return __method.apply(null, [this].concat($A(arguments))); + }; + } +}); + +Date.prototype.toJSON = function() { + return '"' + this.getUTCFullYear() + '-' + + (this.getUTCMonth() + 1).toPaddedString(2) + '-' + + this.getUTCDate().toPaddedString(2) + 'T' + + this.getUTCHours().toPaddedString(2) + ':' + + this.getUTCMinutes().toPaddedString(2) + ':' + + this.getUTCSeconds().toPaddedString(2) + 'Z"'; +}; + +var Try = { + these: function() { + var returnValue; + + for (var i = 0, length = arguments.length; i < length; i++) { + var lambda = arguments[i]; + try { + returnValue = lambda(); + break; + } catch (e) { } + } + + return returnValue; + } +}; + +RegExp.prototype.match = RegExp.prototype.test; + +RegExp.escape = function(str) { + return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); +}; + +/*--------------------------------------------------------------------------*/ + +var PeriodicalExecuter = Class.create({ + initialize: function(callback, frequency) { + this.callback = callback; + this.frequency = frequency; + this.currentlyExecuting = false; + + this.registerCallback(); + }, + + registerCallback: function() { + this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); + }, + + execute: function() { + this.callback(this); + }, + + stop: function() { + if (!this.timer) return; + clearInterval(this.timer); + this.timer = null; + }, + + onTimerEvent: function() { + if (!this.currentlyExecuting) { + try { + this.currentlyExecuting = true; + this.execute(); + } finally { + this.currentlyExecuting = false; + } + } + } +}); +Object.extend(String, { + interpret: function(value) { + return value == null ? '' : String(value); + }, + specialChar: { + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '\\': '\\\\' + } +}); + +Object.extend(String.prototype, { + gsub: function(pattern, replacement) { + var result = '', source = this, match; + replacement = arguments.callee.prepareReplacement(replacement); + + while (source.length > 0) { + if (match = source.match(pattern)) { + result += source.slice(0, match.index); + result += String.interpret(replacement(match)); + source = source.slice(match.index + match[0].length); + } else { + result += source, source = ''; + } + } + return result; + }, + + sub: function(pattern, replacement, count) { + replacement = this.gsub.prepareReplacement(replacement); + count = Object.isUndefined(count) ? 1 : count; + + return this.gsub(pattern, function(match) { + if (--count < 0) return match[0]; + return replacement(match); + }); + }, + + scan: function(pattern, iterator) { + this.gsub(pattern, iterator); + return String(this); + }, + + truncate: function(length, truncation) { + length = length || 30; + truncation = Object.isUndefined(truncation) ? '...' : truncation; + return this.length > length ? + this.slice(0, length - truncation.length) + truncation : String(this); + }, + + strip: function() { + return this.replace(/^\s+/, '').replace(/\s+$/, ''); + }, + + stripTags: function() { + return this.replace(/<\/?[^>]+>/gi, ''); + }, + + stripScripts: function() { + return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); + }, + + extractScripts: function() { + var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); + var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); + return (this.match(matchAll) || []).map(function(scriptTag) { + return (scriptTag.match(matchOne) || ['', ''])[1]; + }); + }, + + evalScripts: function() { + return this.extractScripts().map(function(script) { return eval(script) }); + }, + + escapeHTML: function() { + var self = arguments.callee; + self.text.data = this; + return self.div.innerHTML; + }, + + unescapeHTML: function() { + var div = new Element('div'); + div.innerHTML = this.stripTags(); + return div.childNodes[0] ? (div.childNodes.length > 1 ? + $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) : + div.childNodes[0].nodeValue) : ''; + }, + + toQueryParams: function(separator) { + var match = this.strip().match(/([^?#]*)(#.*)?$/); + if (!match) return { }; + + return match[1].split(separator || '&').inject({ }, function(hash, pair) { + if ((pair = pair.split('='))[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) { + if (!Object.isArray(hash[key])) hash[key] = [hash[key]]; + hash[key].push(value); + } + else hash[key] = value; + } + return hash; + }); + }, + + toArray: function() { + return this.split(''); + }, + + succ: function() { + return this.slice(0, this.length - 1) + + String.fromCharCode(this.charCodeAt(this.length - 1) + 1); + }, + + times: function(count) { + return count < 1 ? '' : new Array(count + 1).join(this); + }, + + camelize: function() { + var parts = this.split('-'), len = parts.length; + if (len == 1) return parts[0]; + + var camelized = this.charAt(0) == '-' + ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) + : parts[0]; + + for (var i = 1; i < len; i++) + camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1); + + return camelized; + }, + + capitalize: function() { + return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); + }, + + underscore: function() { + return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase(); + }, + + dasherize: function() { + return this.gsub(/_/,'-'); + }, + + inspect: function(useDoubleQuotes) { + var escapedString = this.gsub(/[\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, '\\\'') + "'"; + }, + + toJSON: function() { + return this.inspect(true); + }, + + unfilterJSON: function(filter) { + return this.sub(filter || Prototype.JSONFilter, '#{1}'); + }, + + isJSON: function() { + var str = this; + if (str.blank()) return false; + str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''); + return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str); + }, + + evalJSON: function(sanitize) { + var json = this.unfilterJSON(); + try { + if (!sanitize || json.isJSON()) return eval('(' + json + ')'); + } catch (e) { } + throw new SyntaxError('Badly formed JSON string: ' + this.inspect()); + }, + + include: function(pattern) { + return this.indexOf(pattern) > -1; + }, + + startsWith: function(pattern) { + return this.indexOf(pattern) === 0; + }, + + endsWith: function(pattern) { + var d = this.length - pattern.length; + return d >= 0 && this.lastIndexOf(pattern) === d; + }, + + empty: function() { + return this == ''; + }, + + blank: function() { + return /^\s*$/.test(this); + }, + + interpolate: function(object, pattern) { + return new Template(this, pattern).evaluate(object); + } +}); + +if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, { + escapeHTML: function() { + return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); + }, + unescapeHTML: function() { + return this.stripTags().replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>'); + } +}); + +String.prototype.gsub.prepareReplacement = function(replacement) { + if (Object.isFunction(replacement)) return replacement; + var template = new Template(replacement); + return function(match) { return template.evaluate(match) }; +}; + +String.prototype.parseQuery = String.prototype.toQueryParams; + +Object.extend(String.prototype.escapeHTML, { + div: document.createElement('div'), + text: document.createTextNode('') +}); + +String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text); + +var Template = Class.create({ + initialize: function(template, pattern) { + this.template = template.toString(); + this.pattern = pattern || Template.Pattern; + }, + + evaluate: function(object) { + if (Object.isFunction(object.toTemplateReplacements)) + object = object.toTemplateReplacements(); + + return this.template.gsub(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].startsWith('[') ? 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 + String.interpret(ctx); + }); + } +}); +Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; + +var $break = { }; + +var Enumerable = { + each: function(iterator, context) { + var index = 0; + try { + this._each(function(value) { + iterator.call(context, value, index++); + }); + } catch (e) { + if (e != $break) throw e; + } + return this; + }, + + eachSlice: function(number, iterator, context) { + var index = -number, slices = [], array = this.toArray(); + if (number < 1) return array; + while ((index += number) < array.length) + slices.push(array.slice(index, index+number)); + return slices.collect(iterator, context); + }, + + all: function(iterator, context) { + iterator = iterator || Prototype.K; + var result = true; + this.each(function(value, index) { + result = result && !!iterator.call(context, value, index); + if (!result) throw $break; + }); + return result; + }, + + any: function(iterator, context) { + iterator = iterator || Prototype.K; + var result = false; + this.each(function(value, index) { + if (result = !!iterator.call(context, value, index)) + throw $break; + }); + return result; + }, + + collect: function(iterator, context) { + iterator = iterator || Prototype.K; + var results = []; + this.each(function(value, index) { + results.push(iterator.call(context, value, index)); + }); + return results; + }, + + detect: function(iterator, context) { + var result; + this.each(function(value, index) { + if (iterator.call(context, value, index)) { + result = value; + throw $break; + } + }); + return result; + }, + + findAll: function(iterator, context) { + var results = []; + this.each(function(value, index) { + if (iterator.call(context, value, index)) + results.push(value); + }); + return results; + }, + + grep: function(filter, iterator, context) { + iterator = iterator || Prototype.K; + var results = []; + + if (Object.isString(filter)) + filter = new RegExp(filter); + + this.each(function(value, index) { + if (filter.match(value)) + results.push(iterator.call(context, value, index)); + }); + return results; + }, + + include: function(object) { + if (Object.isFunction(this.indexOf)) + if (this.indexOf(object) != -1) return true; + + var found = false; + this.each(function(value) { + if (value == object) { + found = true; + throw $break; + } + }); + return found; + }, + + inGroupsOf: function(number, fillWith) { + fillWith = Object.isUndefined(fillWith) ? null : fillWith; + return this.eachSlice(number, function(slice) { + while(slice.length < number) slice.push(fillWith); + return slice; + }); + }, + + inject: function(memo, iterator, context) { + this.each(function(value, index) { + memo = iterator.call(context, memo, value, index); + }); + return memo; + }, + + invoke: function(method) { + var args = $A(arguments).slice(1); + return this.map(function(value) { + return value[method].apply(value, args); + }); + }, + + max: function(iterator, context) { + iterator = iterator || Prototype.K; + var result; + this.each(function(value, index) { + value = iterator.call(context, value, index); + if (result == null || value >= result) + result = value; + }); + return result; + }, + + min: function(iterator, context) { + iterator = iterator || Prototype.K; + var result; + this.each(function(value, index) { + value = iterator.call(context, value, index); + if (result == null || value < result) + result = value; + }); + return result; + }, + + partition: function(iterator, context) { + iterator = iterator || Prototype.K; + var trues = [], falses = []; + this.each(function(value, index) { + (iterator.call(context, value, index) ? + trues : falses).push(value); + }); + return [trues, falses]; + }, + + pluck: function(property) { + var results = []; + this.each(function(value) { + results.push(value[property]); + }); + return results; + }, + + reject: function(iterator, context) { + var results = []; + this.each(function(value, index) { + if (!iterator.call(context, value, index)) + results.push(value); + }); + return results; + }, + + sortBy: function(iterator, context) { + return this.map(function(value, index) { + return { + value: value, + criteria: iterator.call(context, value, index) + }; + }).sort(function(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }).pluck('value'); + }, + + toArray: function() { + return this.map(); + }, + + zip: function() { + var iterator = Prototype.K, args = $A(arguments); + if (Object.isFunction(args.last())) + iterator = args.pop(); + + var collections = [this].concat(args).map($A); + return this.map(function(value, index) { + return iterator(collections.pluck(index)); + }); + }, + + size: function() { + return this.toArray().length; + }, + + inspect: function() { + return '#<Enumerable:' + this.toArray().inspect() + '>'; + } +}; + +Object.extend(Enumerable, { + map: Enumerable.collect, + find: Enumerable.detect, + select: Enumerable.findAll, + filter: Enumerable.findAll, + member: Enumerable.include, + entries: Enumerable.toArray, + every: Enumerable.all, + some: Enumerable.any +}); +function $A(iterable) { + if (!iterable) return []; + if (iterable.toArray) return iterable.toArray(); + var length = iterable.length || 0, results = new Array(length); + while (length--) results[length] = iterable[length]; + return results; +} + +if (Prototype.Browser.WebKit) { + $A = function(iterable) { + if (!iterable) return []; + // In Safari, only use the `toArray` method if it's not a NodeList. + // A NodeList is a function, has an function `item` property, and a numeric + // `length` property. Adapted from Google Doctype. + if (!(typeof iterable === 'function' && typeof iterable.length === + 'number' && typeof iterable.item === 'function') && iterable.toArray) + return iterable.toArray(); + var length = iterable.length || 0, results = new Array(length); + while (length--) results[length] = iterable[length]; + return results; + }; +} + +Array.from = $A; + +Object.extend(Array.prototype, Enumerable); + +if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse; + +Object.extend(Array.prototype, { + _each: function(iterator) { + for (var i = 0, length = this.length; i < length; i++) + iterator(this[i]); + }, + + clear: function() { + this.length = 0; + return this; + }, + + first: function() { + return this[0]; + }, + + last: function() { + return this[this.length - 1]; + }, + + compact: function() { + return this.select(function(value) { + return value != null; + }); + }, + + flatten: function() { + return this.inject([], function(array, value) { + return array.concat(Object.isArray(value) ? + value.flatten() : [value]); + }); + }, + + without: function() { + var values = $A(arguments); + return this.select(function(value) { + return !values.include(value); + }); + }, + + reverse: function(inline) { + return (inline !== false ? this : this.toArray())._reverse(); + }, + + reduce: function() { + return this.length > 1 ? this : this[0]; + }, + + uniq: function(sorted) { + return this.inject([], function(array, value, index) { + if (0 == index || (sorted ? array.last() != value : !array.include(value))) + array.push(value); + return array; + }); + }, + + intersect: function(array) { + return this.uniq().findAll(function(item) { + return array.detect(function(value) { return item === value }); + }); + }, + + clone: function() { + return [].concat(this); + }, + + size: function() { + return this.length; + }, + + inspect: function() { + return '[' + this.map(Object.inspect).join(', ') + ']'; + }, + + toJSON: function() { + var results = []; + this.each(function(object) { + var value = Object.toJSON(object); + if (!Object.isUndefined(value)) results.push(value); + }); + return '[' + results.join(', ') + ']'; + } +}); + +// use native browser JS 1.6 implementation if available +if (Object.isFunction(Array.prototype.forEach)) + Array.prototype._each = Array.prototype.forEach; + +if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) { + i || (i = 0); + var length = this.length; + if (i < 0) i = length + i; + for (; i < length; i++) + if (this[i] === item) return i; + return -1; +}; + +if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) { + i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1; + var n = this.slice(0, i).reverse().indexOf(item); + return (n < 0) ? n : i - n - 1; +}; + +Array.prototype.toArray = Array.prototype.clone; + +function $w(string) { + if (!Object.isString(string)) return []; + string = string.strip(); + return string ? string.split(/\s+/) : []; +} + +if (Prototype.Browser.Opera){ + Array.prototype.concat = function() { + var array = []; + for (var i = 0, length = this.length; i < length; i++) array.push(this[i]); + for (var i = 0, length = arguments.length; i < length; i++) { + if (Object.isArray(arguments[i])) { + for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++) + array.push(arguments[i][j]); + } else { + array.push(arguments[i]); + } + } + return array; + }; +} +Object.extend(Number.prototype, { + toColorPart: function() { + return this.toPaddedString(2, 16); + }, + + succ: function() { + return this + 1; + }, + + times: function(iterator, context) { + $R(0, this, true).each(iterator, context); + return this; + }, + + toPaddedString: function(length, radix) { + var string = this.toString(radix || 10); + return '0'.times(length - string.length) + string; + }, + + toJSON: function() { + return isFinite(this) ? this.toString() : 'null'; + } +}); + +$w('abs round ceil floor').each(function(method){ + Number.prototype[method] = Math[method].methodize(); +}); +function $H(object) { + return new Hash(object); +}; + +var Hash = Class.create(Enumerable, (function() { + + function toQueryPair(key, value) { + if (Object.isUndefined(value)) return key; + return key + '=' + encodeURIComponent(String.interpret(value)); + } + + return { + initialize: function(object) { + this._object = Object.isHash(object) ? object.toObject() : Object.clone(object); + }, + + _each: function(iterator) { + for (var key in this._object) { + var value = this._object[key], pair = [key, value]; + pair.key = key; + pair.value = value; + iterator(pair); + } + }, + + set: function(key, value) { + return this._object[key] = value; + }, + + get: function(key) { + // simulating poorly supported hasOwnProperty + if (this._object[key] !== Object.prototype[key]) + return this._object[key]; + }, + + unset: function(key) { + var value = this._object[key]; + delete this._object[key]; + return value; + }, + + toObject: function() { + return Object.clone(this._object); + }, + + keys: function() { + return this.pluck('key'); + }, + + values: function() { + return this.pluck('value'); + }, + + index: function(value) { + var match = this.detect(function(pair) { + return pair.value === value; + }); + return match && match.key; + }, + + merge: function(object) { + return this.clone().update(object); + }, + + update: function(object) { + return new Hash(object).inject(this, function(result, pair) { + result.set(pair.key, pair.value); + return result; + }); + }, + + toQueryString: function() { + return this.inject([], function(results, pair) { + var key = encodeURIComponent(pair.key), values = pair.value; + + if (values && typeof values == 'object') { + if (Object.isArray(values)) + return results.concat(values.map(toQueryPair.curry(key))); + } else results.push(toQueryPair(key, values)); + return results; + }).join('&'); + }, + + inspect: function() { + return '#<Hash:{' + this.map(function(pair) { + return pair.map(Object.inspect).join(': '); + }).join(', ') + '}>'; + }, + + toJSON: function() { + return Object.toJSON(this.toObject()); + }, + + clone: function() { + return new Hash(this); + } + } +})()); + +Hash.prototype.toTemplateReplacements = Hash.prototype.toObject; +Hash.from = $H; +var ObjectRange = Class.create(Enumerable, { + initialize: function(start, end, exclusive) { + this.start = start; + this.end = end; + this.exclusive = exclusive; + }, + + _each: function(iterator) { + var value = this.start; + while (this.include(value)) { + iterator(value); + value = value.succ(); + } + }, + + include: function(value) { + if (value < this.start) + return false; + if (this.exclusive) + return value < this.end; + return value <= this.end; + } +}); + +var $R = function(start, end, exclusive) { + return new ObjectRange(start, end, exclusive); +}; + +var Ajax = { + getTransport: function() { + return Try.these( + function() {return new XMLHttpRequest()}, + function() {return new ActiveXObject('Msxml2.XMLHTTP')}, + function() {return new ActiveXObject('Microsoft.XMLHTTP')} + ) || false; + }, + + activeRequestCount: 0 +}; + +Ajax.Responders = { + responders: [], + + _each: function(iterator) { + this.responders._each(iterator); + }, + + register: function(responder) { + if (!this.include(responder)) + this.responders.push(responder); + }, + + unregister: function(responder) { + this.responders = this.responders.without(responder); + }, + + dispatch: function(callback, request, transport, json) { + this.each(function(responder) { + if (Object.isFunction(responder[callback])) { + try { + responder[callback].apply(responder, [request, transport, json]); + } catch (e) { } + } + }); + } +}; + +Object.extend(Ajax.Responders, Enumerable); + +Ajax.Responders.register({ + onCreate: function() { Ajax.activeRequestCount++ }, + onComplete: function() { Ajax.activeRequestCount-- } +}); + +Ajax.Base = Class.create({ + initialize: function(options) { + this.options = { + method: 'post', + asynchronous: true, + contentType: 'application/x-www-form-urlencoded', + encoding: 'UTF-8', + parameters: '', + evalJSON: true, + evalJS: true + }; + Object.extend(this.options, options || { }); + + this.options.method = this.options.method.toLowerCase(); + + if (Object.isString(this.options.parameters)) + this.options.parameters = this.options.parameters.toQueryParams(); + else if (Object.isHash(this.options.parameters)) + this.options.parameters = this.options.parameters.toObject(); + } +}); + +Ajax.Request = Class.create(Ajax.Base, { + _complete: false, + + initialize: function($super, url, options) { + $super(options); + this.transport = Ajax.getTransport(); + this.request(url); + }, + + request: function(url) { + this.url = url; + this.method = this.options.method; + var params = Object.clone(this.options.parameters); + + if (!['get', 'post'].include(this.method)) { + // simulate other verbs over post + params['_method'] = this.method; + this.method = 'post'; + } + + this.parameters = params; + + if (params = Object.toQueryString(params)) { + // when GET, append parameters to URL + if (this.method == 'get') + this.url += (this.url.include('?') ? '&' : '?') + params; + else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) + params += '&_='; + } + + try { + var response = new Ajax.Response(this); + if (this.options.onCreate) this.options.onCreate(response); + Ajax.Responders.dispatch('onCreate', this, response); + + this.transport.open(this.method.toUpperCase(), this.url, + this.options.asynchronous); + + if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1); + + this.transport.onreadystatechange = this.onStateChange.bind(this); + this.setRequestHeaders(); + + this.body = this.method == 'post' ? (this.options.postBody || params) : null; + this.transport.send(this.body); + + /* Force Firefox to handle ready state 4 for synchronous requests */ + if (!this.options.asynchronous && this.transport.overrideMimeType) + this.onStateChange(); + + } + catch (e) { + this.dispatchException(e); + } + }, + + onStateChange: function() { + var readyState = this.transport.readyState; + if (readyState > 1 && !((readyState == 4) && this._complete)) + this.respondToReadyState(this.transport.readyState); + }, + + setRequestHeaders: function() { + var headers = { + 'X-Requested-With': 'XMLHttpRequest', + 'X-Prototype-Version': Prototype.Version, + 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' + }; + + if (this.method == 'post') { + headers['Content-type'] = this.options.contentType + + (this.options.encoding ? '; charset=' + this.options.encoding : ''); + + /* Force "Connection: close" for older Mozilla browsers to work + * around a bug where XMLHttpRequest sends an incorrect + * Content-length header. See Mozilla Bugzilla #246651. + */ + if (this.transport.overrideMimeType && + (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) + headers['Connection'] = 'close'; + } + + // user-defined headers + if (typeof this.options.requestHeaders == 'object') { + var extras = this.options.requestHeaders; + + if (Object.isFunction(extras.push)) + for (var i = 0, length = extras.length; i < length; i += 2) + headers[extras[i]] = extras[i+1]; + else + $H(extras).each(function(pair) { headers[pair.key] = pair.value }); + } + + for (var name in headers) + this.transport.setRequestHeader(name, headers[name]); + }, + + success: function() { + var status = this.getStatus(); + return !status || (status >= 200 && status < 300); + }, + + getStatus: function() { + try { + return this.transport.status || 0; + } catch (e) { return 0 } + }, + + respondToReadyState: function(readyState) { + var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this); + + if (state == 'Complete') { + try { + this._complete = true; + (this.options['on' + response.status] + || this.options['on' + (this.success() ? 'Success' : 'Failure')] + || Prototype.emptyFunction)(response, response.headerJSON); + } catch (e) { + this.dispatchException(e); + } + + var contentType = response.getHeader('Content-type'); + if (this.options.evalJS == 'force' + || (this.options.evalJS && this.isSameOrigin() && contentType + && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))) + this.evalResponse(); + } + + try { + (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON); + Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON); + } catch (e) { + this.dispatchException(e); + } + + if (state == 'Complete') { + // avoid memory leak in MSIE: clean up + this.transport.onreadystatechange = Prototype.emptyFunction; + } + }, + + isSameOrigin: function() { + var m = this.url.match(/^\s*https?:\/\/[^\/]*/); + return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({ + protocol: location.protocol, + domain: document.domain, + port: location.port ? ':' + location.port : '' + })); + }, + + getHeader: function(name) { + try { + return this.transport.getResponseHeader(name) || null; + } catch (e) { return null } + }, + + evalResponse: function() { + try { + return eval((this.transport.responseText || '').unfilterJSON()); + } catch (e) { + this.dispatchException(e); + } + }, + + dispatchException: function(exception) { + (this.options.onException || Prototype.emptyFunction)(this, exception); + Ajax.Responders.dispatch('onException', this, exception); + } +}); + +Ajax.Request.Events = + ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; + +Ajax.Response = Class.create({ + initialize: function(request){ + this.request = request; + var transport = this.transport = request.transport, + readyState = this.readyState = transport.readyState; + + if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) { + this.status = this.getStatus(); + this.statusText = this.getStatusText(); + this.responseText = String.interpret(transport.responseText); + this.headerJSON = this._getHeaderJSON(); + } + + if(readyState == 4) { + var xml = transport.responseXML; + this.responseXML = Object.isUndefined(xml) ? null : xml; + this.responseJSON = this._getResponseJSON(); + } + }, + + status: 0, + statusText: '', + + getStatus: Ajax.Request.prototype.getStatus, + + getStatusText: function() { + try { + return this.transport.statusText || ''; + } catch (e) { return '' } + }, + + getHeader: Ajax.Request.prototype.getHeader, + + getAllHeaders: function() { + try { + return this.getAllResponseHeaders(); + } catch (e) { return null } + }, + + getResponseHeader: function(name) { + return this.transport.getResponseHeader(name); + }, + + getAllResponseHeaders: function() { + return this.transport.getAllResponseHeaders(); + }, + + _getHeaderJSON: function() { + var json = this.getHeader('X-JSON'); + if (!json) return null; + json = decodeURIComponent(escape(json)); + try { + return json.evalJSON(this.request.options.sanitizeJSON || + !this.request.isSameOrigin()); + } catch (e) { + this.request.dispatchException(e); + } + }, + + _getResponseJSON: function() { + var options = this.request.options; + if (!options.evalJSON || (options.evalJSON != 'force' && + !(this.getHeader('Content-type') || '').include('application/json')) || + this.responseText.blank()) + return null; + try { + return this.responseText.evalJSON(options.sanitizeJSON || + !this.request.isSameOrigin()); + } catch (e) { + this.request.dispatchException(e); + } + } +}); + +Ajax.Updater = Class.create(Ajax.Request, { + initialize: function($super, container, url, options) { + this.container = { + success: (container.success || container), + failure: (container.failure || (container.success ? null : container)) + }; + + options = Object.clone(options); + var onComplete = options.onComplete; + options.onComplete = (function(response, json) { + this.updateContent(response.responseText); + if (Object.isFunction(onComplete)) onComplete(response, json); + }).bind(this); + + $super(url, options); + }, + + updateContent: function(responseText) { + var receiver = this.container[this.success() ? 'success' : 'failure'], + options = this.options; + + if (!options.evalScripts) responseText = responseText.stripScripts(); + + if (receiver = $(receiver)) { + if (options.insertion) { + if (Object.isString(options.insertion)) { + var insertion = { }; insertion[options.insertion] = responseText; + receiver.insert(insertion); + } + else options.insertion(receiver, responseText); + } + else receiver.update(responseText); + } + } +}); + +Ajax.PeriodicalUpdater = Class.create(Ajax.Base, { + initialize: function($super, container, url, options) { + $super(options); + this.onComplete = this.options.onComplete; + + this.frequency = (this.options.frequency || 2); + this.decay = (this.options.decay || 1); + + this.updater = { }; + this.container = container; + this.url = url; + + this.start(); + }, + + start: function() { + this.options.onComplete = this.updateComplete.bind(this); + this.onTimerEvent(); + }, + + stop: function() { + this.updater.options.onComplete = undefined; + clearTimeout(this.timer); + (this.onComplete || Prototype.emptyFunction).apply(this, arguments); + }, + + updateComplete: function(response) { + if (this.options.decay) { + this.decay = (response.responseText == this.lastText ? + this.decay * this.options.decay : 1); + + this.lastText = response.responseText; + } + this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency); + }, + + onTimerEvent: function() { + this.updater = new Ajax.Updater(this.container, this.url, this.options); + } +}); +function $(element) { + if (arguments.length > 1) { + for (var i = 0, elements = [], length = arguments.length; i < length; i++) + elements.push($(arguments[i])); + return elements; + } + if (Object.isString(element)) + element = document.getElementById(element); + return Element.extend(element); +} + +if (Prototype.BrowserFeatures.XPath) { + document._getElementsByXPath = function(expression, parentElement) { + var results = []; + var query = document.evaluate(expression, $(parentElement) || document, + null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + for (var i = 0, length = query.snapshotLength; i < length; i++) + results.push(Element.extend(query.snapshotItem(i))); + return results; + }; +} + +/*--------------------------------------------------------------------------*/ + +if (!window.Node) var Node = { }; + +if (!Node.ELEMENT_NODE) { + // DOM level 2 ECMAScript Language Binding + Object.extend(Node, { + ELEMENT_NODE: 1, + ATTRIBUTE_NODE: 2, + TEXT_NODE: 3, + CDATA_SECTION_NODE: 4, + ENTITY_REFERENCE_NODE: 5, + ENTITY_NODE: 6, + PROCESSING_INSTRUCTION_NODE: 7, + COMMENT_NODE: 8, + DOCUMENT_NODE: 9, + DOCUMENT_TYPE_NODE: 10, + DOCUMENT_FRAGMENT_NODE: 11, + NOTATION_NODE: 12 + }); +} + +(function() { + var element = this.Element; + this.Element = function(tagName, attributes) { + attributes = attributes || { }; + tagName = tagName.toLowerCase(); + var cache = Element.cache; + if (Prototype.Browser.IE && attributes.name) { + tagName = '<' + tagName + ' name="' + attributes.name + '">'; + delete attributes.name; + return Element.writeAttribute(document.createElement(tagName), attributes); + } + if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName)); + return Element.writeAttribute(cache[tagName].cloneNode(false), attributes); + }; + Object.extend(this.Element, element || { }); + if (element) this.Element.prototype = element.prototype; +}).call(window); + +Element.cache = { }; + +Element.Methods = { + visible: function(element) { + return $(element).style.display != 'none'; + }, + + toggle: function(element) { + element = $(element); + Element[Element.visible(element) ? 'hide' : 'show'](element); + return element; + }, + + hide: function(element) { + element = $(element); + element.style.display = 'none'; + return element; + }, + + show: function(element) { + element = $(element); + element.style.display = ''; + return element; + }, + + remove: function(element) { + element = $(element); + element.parentNode.removeChild(element); + return element; + }, + + update: function(element, content) { + element = $(element); + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) return element.update().insert(content); + content = Object.toHTML(content); + element.innerHTML = content.stripScripts(); + content.evalScripts.bind(content).defer(); + return element; + }, + + replace: function(element, content) { + element = $(element); + if (content && content.toElement) content = content.toElement(); + else if (!Object.isElement(content)) { + content = Object.toHTML(content); + var range = element.ownerDocument.createRange(); + range.selectNode(element); + content.evalScripts.bind(content).defer(); + content = range.createContextualFragment(content.stripScripts()); + } + element.parentNode.replaceChild(content, element); + return element; + }, + + insert: function(element, insertions) { + element = $(element); + + if (Object.isString(insertions) || Object.isNumber(insertions) || + Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML))) + insertions = {bottom:insertions}; + + var content, insert, tagName, childNodes; + + for (var position in insertions) { + content = insertions[position]; + position = position.toLowerCase(); + insert = Element._insertionTranslations[position]; + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) { + insert(element, content); + continue; + } + + content = Object.toHTML(content); + + tagName = ((position == 'before' || position == 'after') + ? element.parentNode : element).tagName.toUpperCase(); + + childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + + if (position == 'top' || position == 'after') childNodes.reverse(); + childNodes.each(insert.curry(element)); + + content.evalScripts.bind(content).defer(); + } + + return element; + }, + + wrap: function(element, wrapper, attributes) { + element = $(element); + if (Object.isElement(wrapper)) + $(wrapper).writeAttribute(attributes || { }); + else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes); + else wrapper = new Element('div', wrapper); + if (element.parentNode) + element.parentNode.replaceChild(wrapper, element); + wrapper.appendChild(element); + return wrapper; + }, + + inspect: function(element) { + element = $(element); + var result = '<' + element.tagName.toLowerCase(); + $H({'id': 'id', 'className': 'class'}).each(function(pair) { + var property = pair.first(), attribute = pair.last(); + var value = (element[property] || '').toString(); + if (value) result += ' ' + attribute + '=' + value.inspect(true); + }); + return result + '>'; + }, + + recursivelyCollect: function(element, property) { + element = $(element); + var elements = []; + while (element = element[property]) + if (element.nodeType == 1) + elements.push(Element.extend(element)); + return elements; + }, + + ancestors: function(element) { + return $(element).recursivelyCollect('parentNode'); + }, + + descendants: function(element) { + return $(element).select("*"); + }, + + firstDescendant: function(element) { + element = $(element).firstChild; + while (element && element.nodeType != 1) element = element.nextSibling; + return $(element); + }, + + immediateDescendants: function(element) { + if (!(element = $(element).firstChild)) return []; + while (element && element.nodeType != 1) element = element.nextSibling; + if (element) return [element].concat($(element).nextSiblings()); + return []; + }, + + previousSiblings: function(element) { + return $(element).recursivelyCollect('previousSibling'); + }, + + nextSiblings: function(element) { + return $(element).recursivelyCollect('nextSibling'); + }, + + siblings: function(element) { + element = $(element); + return element.previousSiblings().reverse().concat(element.nextSiblings()); + }, + + match: function(element, selector) { + if (Object.isString(selector)) + selector = new Selector(selector); + return selector.match($(element)); + }, + + up: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return $(element.parentNode); + var ancestors = element.ancestors(); + return Object.isNumber(expression) ? ancestors[expression] : + Selector.findElement(ancestors, expression, index); + }, + + down: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return element.firstDescendant(); + return Object.isNumber(expression) ? element.descendants()[expression] : + Element.select(element, expression)[index || 0]; + }, + + previous: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element)); + var previousSiblings = element.previousSiblings(); + return Object.isNumber(expression) ? previousSiblings[expression] : + Selector.findElement(previousSiblings, expression, index); + }, + + next: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element)); + var nextSiblings = element.nextSiblings(); + return Object.isNumber(expression) ? nextSiblings[expression] : + Selector.findElement(nextSiblings, expression, index); + }, + + select: function() { + var args = $A(arguments), element = $(args.shift()); + return Selector.findChildElements(element, args); + }, + + adjacent: function() { + var args = $A(arguments), element = $(args.shift()); + return Selector.findChildElements(element.parentNode, args).without(element); + }, + + identify: function(element) { + element = $(element); + var id = element.readAttribute('id'), self = arguments.callee; + if (id) return id; + do { id = 'anonymous_element_' + self.counter++ } while ($(id)); + element.writeAttribute('id', id); + return id; + }, + + readAttribute: function(element, name) { + element = $(element); + if (Prototype.Browser.IE) { + var t = Element._attributeTranslations.read; + if (t.values[name]) return t.values[name](element, name); + if (t.names[name]) name = t.names[name]; + if (name.include(':')) { + return (!element.attributes || !element.attributes[name]) ? null : + element.attributes[name].value; + } + } + return element.getAttribute(name); + }, + + writeAttribute: function(element, name, value) { + element = $(element); + var attributes = { }, t = Element._attributeTranslations.write; + + if (typeof name == 'object') attributes = name; + else attributes[name] = Object.isUndefined(value) ? true : value; + + for (var attr in attributes) { + name = t.names[attr] || attr; + value = attributes[attr]; + if (t.values[attr]) name = t.values[attr](element, value); + if (value === false || value === null) + element.removeAttribute(name); + else if (value === true) + element.setAttribute(name, name); + else element.setAttribute(name, value); + } + return element; + }, + + getHeight: function(element) { + return $(element).getDimensions().height; + }, + + getWidth: function(element) { + return $(element).getDimensions().width; + }, + + classNames: function(element) { + return new Element.ClassNames(element); + }, + + hasClassName: function(element, className) { + if (!(element = $(element))) return; + var elementClassName = element.className; + return (elementClassName.length > 0 && (elementClassName == className || + new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName))); + }, + + addClassName: function(element, className) { + if (!(element = $(element))) return; + if (!element.hasClassName(className)) + element.className += (element.className ? ' ' : '') + className; + return element; + }, + + removeClassName: function(element, className) { + if (!(element = $(element))) return; + element.className = element.className.replace( + new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip(); + return element; + }, + + toggleClassName: function(element, className) { + if (!(element = $(element))) return; + return element[element.hasClassName(className) ? + 'removeClassName' : 'addClassName'](className); + }, + + // removes whitespace-only text node children + cleanWhitespace: function(element) { + element = $(element); + var node = element.firstChild; + while (node) { + var nextNode = node.nextSibling; + if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) + element.removeChild(node); + node = nextNode; + } + return element; + }, + + empty: function(element) { + return $(element).innerHTML.blank(); + }, + + descendantOf: function(element, ancestor) { + element = $(element), ancestor = $(ancestor); + + if (element.compareDocumentPosition) + return (element.compareDocumentPosition(ancestor) & 8) === 8; + + if (ancestor.contains) + return ancestor.contains(element) && ancestor !== element; + + while (element = element.parentNode) + if (element == ancestor) return true; + + return false; + }, + + scrollTo: function(element) { + element = $(element); + var pos = element.cumulativeOffset(); + window.scrollTo(pos[0], pos[1]); + return element; + }, + + getStyle: function(element, style) { + element = $(element); + style = style == 'float' ? 'cssFloat' : style.camelize(); + var value = element.style[style]; + if (!value || value == 'auto') { + var css = document.defaultView.getComputedStyle(element, null); + value = css ? css[style] : null; + } + if (style == 'opacity') return value ? parseFloat(value) : 1.0; + return value == 'auto' ? null : value; + }, + + getOpacity: function(element) { + return $(element).getStyle('opacity'); + }, + + setStyle: function(element, styles) { + element = $(element); + var elementStyle = element.style, match; + if (Object.isString(styles)) { + element.style.cssText += ';' + styles; + return styles.include('opacity') ? + element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element; + } + for (var property in styles) + if (property == 'opacity') element.setOpacity(styles[property]); + else + elementStyle[(property == 'float' || property == 'cssFloat') ? + (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') : + property] = styles[property]; + + return element; + }, + + setOpacity: function(element, value) { + element = $(element); + element.style.opacity = (value == 1 || value === '') ? '' : + (value < 0.00001) ? 0 : value; + return element; + }, + + getDimensions: function(element) { + element = $(element); + var display = element.getStyle('display'); + if (display != 'none' && display != null) // Safari bug + return {width: element.offsetWidth, height: element.offsetHeight}; + + // All *Width and *Height properties give 0 on elements with display none, + // so enable the element temporarily + var els = element.style; + var originalVisibility = els.visibility; + var originalPosition = els.position; + var originalDisplay = els.display; + els.visibility = 'hidden'; + els.position = 'absolute'; + els.display = 'block'; + var originalWidth = element.clientWidth; + var originalHeight = element.clientHeight; + els.display = originalDisplay; + els.position = originalPosition; + els.visibility = originalVisibility; + return {width: originalWidth, height: originalHeight}; + }, + + makePositioned: function(element) { + element = $(element); + var pos = Element.getStyle(element, 'position'); + if (pos == 'static' || !pos) { + element._madePositioned = true; + element.style.position = 'relative'; + // Opera returns the offset relative to the positioning context, when an + // element is position relative but top and left have not been defined + if (Prototype.Browser.Opera) { + element.style.top = 0; + element.style.left = 0; + } + } + return element; + }, + + undoPositioned: function(element) { + element = $(element); + if (element._madePositioned) { + element._madePositioned = undefined; + element.style.position = + element.style.top = + element.style.left = + element.style.bottom = + element.style.right = ''; + } + return element; + }, + + makeClipping: function(element) { + element = $(element); + if (element._overflow) return element; + element._overflow = Element.getStyle(element, 'overflow') || 'auto'; + if (element._overflow !== 'hidden') + element.style.overflow = 'hidden'; + return element; + }, + + undoClipping: function(element) { + element = $(element); + if (!element._overflow) return element; + element.style.overflow = element._overflow == 'auto' ? '' : element._overflow; + element._overflow = null; + return element; + }, + + cumulativeOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + } while (element); + return Element._returnOffset(valueL, valueT); + }, + + positionedOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + if (element) { + if (element.tagName.toUpperCase() == 'BODY') break; + var p = Element.getStyle(element, 'position'); + if (p !== 'static') break; + } + } while (element); + return Element._returnOffset(valueL, valueT); + }, + + absolutize: function(element) { + element = $(element); + if (element.getStyle('position') == 'absolute') return element; + // Position.prepare(); // To be done manually by Scripty when it needs it. + + var offsets = element.positionedOffset(); + var top = offsets[1]; + var left = offsets[0]; + var width = element.clientWidth; + var height = element.clientHeight; + + element._originalLeft = left - parseFloat(element.style.left || 0); + element._originalTop = top - parseFloat(element.style.top || 0); + element._originalWidth = element.style.width; + element._originalHeight = element.style.height; + + element.style.position = 'absolute'; + element.style.top = top + 'px'; + element.style.left = left + 'px'; + element.style.width = width + 'px'; + element.style.height = height + 'px'; + return element; + }, + + relativize: function(element) { + element = $(element); + if (element.getStyle('position') == 'relative') return element; + // Position.prepare(); // To be done manually by Scripty when it needs it. + + element.style.position = 'relative'; + var top = parseFloat(element.style.top || 0) - (element._originalTop || 0); + var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); + + element.style.top = top + 'px'; + element.style.left = left + 'px'; + element.style.height = element._originalHeight; + element.style.width = element._originalWidth; + return element; + }, + + cumulativeScrollOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.scrollTop || 0; + valueL += element.scrollLeft || 0; + element = element.parentNode; + } while (element); + return Element._returnOffset(valueL, valueT); + }, + + getOffsetParent: function(element) { + if (element.offsetParent) return $(element.offsetParent); + if (element == document.body) return $(element); + + while ((element = element.parentNode) && element != document.body) + if (Element.getStyle(element, 'position') != 'static') + return $(element); + + return $(document.body); + }, + + viewportOffset: function(forElement) { + var valueT = 0, valueL = 0; + + var element = forElement; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + + // Safari fix + if (element.offsetParent == document.body && + Element.getStyle(element, 'position') == 'absolute') break; + + } while (element = element.offsetParent); + + element = forElement; + do { + if (!Prototype.Browser.Opera || (element.tagName && (element.tagName.toUpperCase() == 'BODY'))) { + valueT -= element.scrollTop || 0; + valueL -= element.scrollLeft || 0; + } + } while (element = element.parentNode); + + return Element._returnOffset(valueL, valueT); + }, + + clonePosition: function(element, source) { + var options = Object.extend({ + setLeft: true, + setTop: true, + setWidth: true, + setHeight: true, + offsetTop: 0, + offsetLeft: 0 + }, arguments[2] || { }); + + // find page position of source + source = $(source); + var p = source.viewportOffset(); + + // find coordinate system to use + element = $(element); + var delta = [0, 0]; + var parent = null; + // delta [0,0] will do fine with position: fixed elements, + // position:absolute needs offsetParent deltas + if (Element.getStyle(element, 'position') == 'absolute') { + parent = element.getOffsetParent(); + delta = parent.viewportOffset(); + } + + // correct by body offsets (fixes Safari) + if (parent == document.body) { + delta[0] -= document.body.offsetLeft; + delta[1] -= document.body.offsetTop; + } + + // set position + if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; + if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px'; + if (options.setWidth) element.style.width = source.offsetWidth + 'px'; + if (options.setHeight) element.style.height = source.offsetHeight + 'px'; + return element; + } +}; + +Element.Methods.identify.counter = 1; + +Object.extend(Element.Methods, { + getElementsBySelector: Element.Methods.select, + childElements: Element.Methods.immediateDescendants +}); + +Element._attributeTranslations = { + write: { + names: { + className: 'class', + htmlFor: 'for' + }, + values: { } + } +}; + +if (Prototype.Browser.Opera) { + Element.Methods.getStyle = Element.Methods.getStyle.wrap( + function(proceed, element, style) { + switch (style) { + case 'left': case 'top': case 'right': case 'bottom': + if (proceed(element, 'position') === 'static') return null; + case 'height': case 'width': + // returns '0px' for hidden elements; we want it to return null + if (!Element.visible(element)) return null; + + // returns the border-box dimensions rather than the content-box + // dimensions, so we subtract padding and borders from the value + var dim = parseInt(proceed(element, style), 10); + + if (dim !== element['offset' + style.capitalize()]) + return dim + 'px'; + + var properties; + if (style === 'height') { + properties = ['border-top-width', 'padding-top', + 'padding-bottom', 'border-bottom-width']; + } + else { + properties = ['border-left-width', 'padding-left', + 'padding-right', 'border-right-width']; + } + return properties.inject(dim, function(memo, property) { + var val = proceed(element, property); + return val === null ? memo : memo - parseInt(val, 10); + }) + 'px'; + default: return proceed(element, style); + } + } + ); + + Element.Methods.readAttribute = Element.Methods.readAttribute.wrap( + function(proceed, element, attribute) { + if (attribute === 'title') return element.title; + return proceed(element, attribute); + } + ); +} + +else if (Prototype.Browser.IE) { + // IE doesn't report offsets correctly for static elements, so we change them + // to "relative" to get the values, then change them back. + Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap( + function(proceed, element) { + element = $(element); + // IE throws an error if element is not in document + try { element.offsetParent } + catch(e) { return $(document.body) } + var position = element.getStyle('position'); + if (position !== 'static') return proceed(element); + element.setStyle({ position: 'relative' }); + var value = proceed(element); + element.setStyle({ position: position }); + return value; + } + ); + + $w('positionedOffset viewportOffset').each(function(method) { + Element.Methods[method] = Element.Methods[method].wrap( + function(proceed, element) { + element = $(element); + try { element.offsetParent } + catch(e) { return Element._returnOffset(0,0) } + var position = element.getStyle('position'); + if (position !== 'static') return proceed(element); + // Trigger hasLayout on the offset parent so that IE6 reports + // accurate offsetTop and offsetLeft values for position: fixed. + var offsetParent = element.getOffsetParent(); + if (offsetParent && offsetParent.getStyle('position') === 'fixed') + offsetParent.setStyle({ zoom: 1 }); + element.setStyle({ position: 'relative' }); + var value = proceed(element); + element.setStyle({ position: position }); + return value; + } + ); + }); + + Element.Methods.cumulativeOffset = Element.Methods.cumulativeOffset.wrap( + function(proceed, element) { + try { element.offsetParent } + catch(e) { return Element._returnOffset(0,0) } + return proceed(element); + } + ); + + Element.Methods.getStyle = function(element, style) { + element = $(element); + style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize(); + var value = element.style[style]; + if (!value && element.currentStyle) value = element.currentStyle[style]; + + if (style == 'opacity') { + if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/)) + if (value[1]) return parseFloat(value[1]) / 100; + return 1.0; + } + + if (value == 'auto') { + if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none')) + return element['offset' + style.capitalize()] + 'px'; + return null; + } + return value; + }; + + Element.Methods.setOpacity = function(element, value) { + function stripAlpha(filter){ + return filter.replace(/alpha\([^\)]*\)/gi,''); + } + element = $(element); + var currentStyle = element.currentStyle; + if ((currentStyle && !currentStyle.hasLayout) || + (!currentStyle && element.style.zoom == 'normal')) + element.style.zoom = 1; + + var filter = element.getStyle('filter'), style = element.style; + if (value == 1 || value === '') { + (filter = stripAlpha(filter)) ? + style.filter = filter : style.removeAttribute('filter'); + return element; + } else if (value < 0.00001) value = 0; + style.filter = stripAlpha(filter) + + 'alpha(opacity=' + (value * 100) + ')'; + return element; + }; + + Element._attributeTranslations = { + read: { + names: { + 'class': 'className', + 'for': 'htmlFor' + }, + values: { + _getAttr: function(element, attribute) { + return element.getAttribute(attribute, 2); + }, + _getAttrNode: function(element, attribute) { + var node = element.getAttributeNode(attribute); + return node ? node.value : ""; + }, + _getEv: function(element, attribute) { + attribute = element.getAttribute(attribute); + return attribute ? attribute.toString().slice(23, -2) : null; + }, + _flag: function(element, attribute) { + return $(element).hasAttribute(attribute) ? attribute : null; + }, + style: function(element) { + return element.style.cssText.toLowerCase(); + }, + title: function(element) { + return element.title; + } + } + } + }; + + Element._attributeTranslations.write = { + names: Object.extend({ + cellpadding: 'cellPadding', + cellspacing: 'cellSpacing' + }, Element._attributeTranslations.read.names), + values: { + checked: function(element, value) { + element.checked = !!value; + }, + + style: function(element, value) { + element.style.cssText = value ? value : ''; + } + } + }; + + Element._attributeTranslations.has = {}; + + $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' + + 'encType maxLength readOnly longDesc frameBorder').each(function(attr) { + Element._attributeTranslations.write.names[attr.toLowerCase()] = attr; + Element._attributeTranslations.has[attr.toLowerCase()] = attr; + }); + + (function(v) { + Object.extend(v, { + href: v._getAttr, + src: v._getAttr, + type: v._getAttr, + action: v._getAttrNode, + disabled: v._flag, + checked: v._flag, + readonly: v._flag, + multiple: v._flag, + onload: v._getEv, + onunload: v._getEv, + onclick: v._getEv, + ondblclick: v._getEv, + onmousedown: v._getEv, + onmouseup: v._getEv, + onmouseover: v._getEv, + onmousemove: v._getEv, + onmouseout: v._getEv, + onfocus: v._getEv, + onblur: v._getEv, + onkeypress: v._getEv, + onkeydown: v._getEv, + onkeyup: v._getEv, + onsubmit: v._getEv, + onreset: v._getEv, + onselect: v._getEv, + onchange: v._getEv + }); + })(Element._attributeTranslations.read.values); +} + +else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) { + Element.Methods.setOpacity = function(element, value) { + element = $(element); + element.style.opacity = (value == 1) ? 0.999999 : + (value === '') ? '' : (value < 0.00001) ? 0 : value; + return element; + }; +} + +else if (Prototype.Browser.WebKit) { + Element.Methods.setOpacity = function(element, value) { + element = $(element); + element.style.opacity = (value == 1 || value === '') ? '' : + (value < 0.00001) ? 0 : value; + + if (value == 1) + if(element.tagName.toUpperCase() == 'IMG' && element.width) { + element.width++; element.width--; + } else try { + var n = document.createTextNode(' '); + element.appendChild(n); + element.removeChild(n); + } catch (e) { } + + return element; + }; + + // Safari returns margins on body which is incorrect if the child is absolutely + // positioned. For performance reasons, redefine Element#cumulativeOffset for + // KHTML/WebKit only. + Element.Methods.cumulativeOffset = function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + if (element.offsetParent == document.body) + if (Element.getStyle(element, 'position') == 'absolute') break; + + element = element.offsetParent; + } while (element); + + return Element._returnOffset(valueL, valueT); + }; +} + +if (Prototype.Browser.IE || Prototype.Browser.Opera) { + // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements + Element.Methods.update = function(element, content) { + element = $(element); + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) return element.update().insert(content); + + content = Object.toHTML(content); + var tagName = element.tagName.toUpperCase(); + + if (tagName in Element._insertionTranslations.tags) { + $A(element.childNodes).each(function(node) { element.removeChild(node) }); + Element._getContentFromAnonymousElement(tagName, content.stripScripts()) + .each(function(node) { element.appendChild(node) }); + } + else element.innerHTML = content.stripScripts(); + + content.evalScripts.bind(content).defer(); + return element; + }; +} + +if ('outerHTML' in document.createElement('div')) { + Element.Methods.replace = function(element, content) { + element = $(element); + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) { + element.parentNode.replaceChild(content, element); + return element; + } + + content = Object.toHTML(content); + var parent = element.parentNode, tagName = parent.tagName.toUpperCase(); + + if (Element._insertionTranslations.tags[tagName]) { + var nextSibling = element.next(); + var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + parent.removeChild(element); + if (nextSibling) + fragments.each(function(node) { parent.insertBefore(node, nextSibling) }); + else + fragments.each(function(node) { parent.appendChild(node) }); + } + else element.outerHTML = content.stripScripts(); + + content.evalScripts.bind(content).defer(); + return element; + }; +} + +Element._returnOffset = function(l, t) { + var result = [l, t]; + result.left = l; + result.top = t; + return result; +}; + +Element._getContentFromAnonymousElement = function(tagName, html) { + var div = new Element('div'), t = Element._insertionTranslations.tags[tagName]; + if (t) { + div.innerHTML = t[0] + html + t[1]; + t[2].times(function() { div = div.firstChild }); + } else div.innerHTML = html; + return $A(div.childNodes); +}; + +Element._insertionTranslations = { + before: function(element, node) { + element.parentNode.insertBefore(node, element); + }, + top: function(element, node) { + element.insertBefore(node, element.firstChild); + }, + bottom: function(element, node) { + element.appendChild(node); + }, + after: function(element, node) { + element.parentNode.insertBefore(node, element.nextSibling); + }, + tags: { + TABLE: ['<table>', '</table>', 1], + TBODY: ['<table><tbody>', '</tbody></table>', 2], + TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3], + TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4], + SELECT: ['<select>', '</select>', 1] + } +}; + +(function() { + Object.extend(this.tags, { + THEAD: this.tags.TBODY, + TFOOT: this.tags.TBODY, + TH: this.tags.TD + }); +}).call(Element._insertionTranslations); + +Element.Methods.Simulated = { + hasAttribute: function(element, attribute) { + attribute = Element._attributeTranslations.has[attribute] || attribute; + var node = $(element).getAttributeNode(attribute); + return !!(node && node.specified); + } +}; + +Element.Methods.ByTag = { }; + +Object.extend(Element, Element.Methods); + +if (!Prototype.BrowserFeatures.ElementExtensions && + document.createElement('div')['__proto__']) { + window.HTMLElement = { }; + window.HTMLElement.prototype = document.createElement('div')['__proto__']; + Prototype.BrowserFeatures.ElementExtensions = true; +} + +Element.extend = (function() { + if (Prototype.BrowserFeatures.SpecificElementExtensions) + return Prototype.K; + + var Methods = { }, ByTag = Element.Methods.ByTag; + + var extend = Object.extend(function(element) { + if (!element || element._extendedByPrototype || + element.nodeType != 1 || element == window) return element; + + var methods = Object.clone(Methods), + tagName = element.tagName.toUpperCase(), property, value; + + // extend methods for specific tags + if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]); + + for (property in methods) { + value = methods[property]; + if (Object.isFunction(value) && !(property in element)) + element[property] = value.methodize(); + } + + element._extendedByPrototype = Prototype.emptyFunction; + return element; + + }, { + refresh: function() { + // extend methods for all tags (Safari doesn't need this) + if (!Prototype.BrowserFeatures.ElementExtensions) { + Object.extend(Methods, Element.Methods); + Object.extend(Methods, Element.Methods.Simulated); + } + } + }); + + extend.refresh(); + return extend; +})(); + +Element.hasAttribute = function(element, attribute) { + if (element.hasAttribute) return element.hasAttribute(attribute); + return Element.Methods.Simulated.hasAttribute(element, attribute); +}; + +Element.addMethods = function(methods) { + var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag; + + if (!methods) { + Object.extend(Form, Form.Methods); + Object.extend(Form.Element, Form.Element.Methods); + Object.extend(Element.Methods.ByTag, { + "FORM": Object.clone(Form.Methods), + "INPUT": Object.clone(Form.Element.Methods), + "SELECT": Object.clone(Form.Element.Methods), + "TEXTAREA": Object.clone(Form.Element.Methods) + }); + } + + if (arguments.length == 2) { + var tagName = methods; + methods = arguments[1]; + } + + if (!tagName) Object.extend(Element.Methods, methods || { }); + else { + if (Object.isArray(tagName)) tagName.each(extend); + else extend(tagName); + } + + function extend(tagName) { + tagName = tagName.toUpperCase(); + if (!Element.Methods.ByTag[tagName]) + Element.Methods.ByTag[tagName] = { }; + Object.extend(Element.Methods.ByTag[tagName], methods); + } + + function copy(methods, destination, onlyIfAbsent) { + onlyIfAbsent = onlyIfAbsent || false; + for (var property in methods) { + var value = methods[property]; + if (!Object.isFunction(value)) continue; + if (!onlyIfAbsent || !(property in destination)) + destination[property] = value.methodize(); + } + } + + function findDOMClass(tagName) { + var klass; + var trans = { + "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph", + "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList", + "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading", + "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote", + "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION": + "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD": + "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR": + "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET": + "FrameSet", "IFRAME": "IFrame" + }; + if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element'; + if (window[klass]) return window[klass]; + klass = 'HTML' + tagName + 'Element'; + if (window[klass]) return window[klass]; + klass = 'HTML' + tagName.capitalize() + 'Element'; + if (window[klass]) return window[klass]; + + window[klass] = { }; + window[klass].prototype = document.createElement(tagName)['__proto__']; + return window[klass]; + } + + if (F.ElementExtensions) { + copy(Element.Methods, HTMLElement.prototype); + copy(Element.Methods.Simulated, HTMLElement.prototype, true); + } + + if (F.SpecificElementExtensions) { + for (var tag in Element.Methods.ByTag) { + var klass = findDOMClass(tag); + if (Object.isUndefined(klass)) continue; + copy(T[tag], klass.prototype); + } + } + + Object.extend(Element, Element.Methods); + delete Element.ByTag; + + if (Element.extend.refresh) Element.extend.refresh(); + Element.cache = { }; +}; + +document.viewport = { + getDimensions: function() { + var dimensions = { }, B = Prototype.Browser; + $w('width height').each(function(d) { + var D = d.capitalize(); + if (B.WebKit && !document.evaluate) { + // Safari <3.0 needs self.innerWidth/Height + dimensions[d] = self['inner' + D]; + } else if (B.Opera && parseFloat(window.opera.version()) < 9.5) { + // Opera <9.5 needs document.body.clientWidth/Height + dimensions[d] = document.body['client' + D] + } else { + dimensions[d] = document.documentElement['client' + D]; + } + }); + return dimensions; + }, + + getWidth: function() { + return this.getDimensions().width; + }, + + getHeight: function() { + return this.getDimensions().height; + }, + + getScrollOffsets: function() { + return Element._returnOffset( + window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, + window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop); + } +}; +/* Portions of the Selector class are derived from Jack Slocum's DomQuery, + * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style + * license. Please see http://www.yui-ext.com/ for more information. */ + +var Selector = Class.create({ + initialize: function(expression) { + this.expression = expression.strip(); + + if (this.shouldUseSelectorsAPI()) { + this.mode = 'selectorsAPI'; + } else if (this.shouldUseXPath()) { + this.mode = 'xpath'; + this.compileXPathMatcher(); + } else { + this.mode = "normal"; + this.compileMatcher(); + } + + }, + + shouldUseXPath: function() { + if (!Prototype.BrowserFeatures.XPath) return false; + + var e = this.expression; + + // Safari 3 chokes on :*-of-type and :empty + if (Prototype.Browser.WebKit && + (e.include("-of-type") || e.include(":empty"))) + return false; + + // XPath can't do namespaced attributes, nor can it read + // the "checked" property from DOM nodes + if ((/(\[[\w-]*?:|:checked)/).test(e)) + return false; + + return true; + }, + + shouldUseSelectorsAPI: function() { + if (!Prototype.BrowserFeatures.SelectorsAPI) return false; + + if (!Selector._div) Selector._div = new Element('div'); + + // Make sure the browser treats the selector as valid. Test on an + // isolated element to minimize cost of this check. + try { + Selector._div.querySelector(this.expression); + } catch(e) { + return false; + } + + return true; + }, + + compileMatcher: function() { + var e = this.expression, ps = Selector.patterns, h = Selector.handlers, + c = Selector.criteria, le, p, m; + + if (Selector._cache[e]) { + this.matcher = Selector._cache[e]; + return; + } + + this.matcher = ["this.matcher = function(root) {", + "var r = root, h = Selector.handlers, c = false, n;"]; + + while (e && le != e && (/\S/).test(e)) { + le = e; + for (var i in ps) { + p = ps[i]; + if (m = e.match(p)) { + this.matcher.push(Object.isFunction(c[i]) ? c[i](m) : + new Template(c[i]).evaluate(m)); + e = e.replace(m[0], ''); + break; + } + } + } + + this.matcher.push("return h.unique(n);\n}"); + eval(this.matcher.join('\n')); + Selector._cache[this.expression] = this.matcher; + }, + + compileXPathMatcher: function() { + var e = this.expression, ps = Selector.patterns, + x = Selector.xpath, le, m; + + if (Selector._cache[e]) { + this.xpath = Selector._cache[e]; return; + } + + this.matcher = ['.//*']; + while (e && le != e && (/\S/).test(e)) { + le = e; + for (var i in ps) { + if (m = e.match(ps[i])) { + this.matcher.push(Object.isFunction(x[i]) ? x[i](m) : + new Template(x[i]).evaluate(m)); + e = e.replace(m[0], ''); + break; + } + } + } + + this.xpath = this.matcher.join(''); + Selector._cache[this.expression] = this.xpath; + }, + + findElements: function(root) { + root = root || document; + var e = this.expression, results; + + switch (this.mode) { + case 'selectorsAPI': + // querySelectorAll queries document-wide, then filters to descendants + // of the context element. That's not what we want. + // Add an explicit context to the selector if necessary. + if (root !== document) { + var oldId = root.id, id = $(root).identify(); + e = "#" + id + " " + e; + } + + results = $A(root.querySelectorAll(e)).map(Element.extend); + root.id = oldId; + + return results; + case 'xpath': + return document._getElementsByXPath(this.xpath, root); + default: + return this.matcher(root); + } + }, + + match: function(element) { + this.tokens = []; + + var e = this.expression, ps = Selector.patterns, as = Selector.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]) { + this.tokens.push([i, Object.clone(m)]); + e = e.replace(m[0], ''); + } else { + // reluctantly do a document-wide search + // and look for a match in the array + return this.findElements(document).include(element); + } + } + } + } + + var match = true, name, matches; + for (var i = 0, token; token = this.tokens[i]; i++) { + name = token[0], matches = token[1]; + if (!Selector.assertions[name](element, matches)) { + match = false; break; + } + } + + return match; + }, + + toString: function() { + return this.expression; + }, + + inspect: function() { + return "#<Selector:" + this.expression.inspect() + ">"; + } +}); + +Object.extend(Selector, { + _cache: { }, + + xpath: { + descendant: "//*", + child: "/*", + adjacent: "/following-sibling::*[1]", + laterSibling: '/following-sibling::*', + tagName: function(m) { + if (m[1] == '*') return ''; + return "[local-name()='" + m[1].toLowerCase() + + "' or local-name()='" + m[1].toUpperCase() + "']"; + }, + className: "[contains(concat(' ', @class, ' '), ' #{1} ')]", + id: "[@id='#{1}']", + attrPresence: function(m) { + m[1] = m[1].toLowerCase(); + return new Template("[@#{1}]").evaluate(m); + }, + attr: function(m) { + m[1] = m[1].toLowerCase(); + m[3] = m[5] || m[6]; + return new Template(Selector.xpath.operators[m[2]]).evaluate(m); + }, + pseudo: function(m) { + var h = Selector.xpath.pseudos[m[1]]; + if (!h) return ''; + if (Object.isFunction(h)) return h(m); + return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m); + }, + operators: { + '=': "[@#{1}='#{3}']", + '!=': "[@#{1}!='#{3}']", + '^=': "[starts-with(@#{1}, '#{3}')]", + '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']", + '*=': "[contains(@#{1}, '#{3}')]", + '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]", + '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]" + }, + pseudos: { + 'first-child': '[not(preceding-sibling::*)]', + 'last-child': '[not(following-sibling::*)]', + 'only-child': '[not(preceding-sibling::* or following-sibling::*)]', + 'empty': "[count(*) = 0 and (count(text()) = 0)]", + 'checked': "[@checked]", + 'disabled': "[(@disabled) and (@type!='hidden')]", + 'enabled': "[not(@disabled) and (@type!='hidden')]", + 'not': function(m) { + var e = m[6], p = Selector.patterns, + x = Selector.xpath, le, v; + + var exclusion = []; + while (e && le != e && (/\S/).test(e)) { + le = e; + for (var i in p) { + if (m = e.match(p[i])) { + v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m); + exclusion.push("(" + v.substring(1, v.length - 1) + ")"); + e = e.replace(m[0], ''); + break; + } + } + } + return "[not(" + exclusion.join(" and ") + ")]"; + }, + 'nth-child': function(m) { + return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m); + }, + 'nth-last-child': function(m) { + return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m); + }, + 'nth-of-type': function(m) { + return Selector.xpath.pseudos.nth("position() ", m); + }, + 'nth-last-of-type': function(m) { + return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m); + }, + 'first-of-type': function(m) { + m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m); + }, + 'last-of-type': function(m) { + m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m); + }, + 'only-of-type': function(m) { + var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m); + }, + nth: function(fragment, m) { + var mm, formula = m[6], predicate; + if (formula == 'even') formula = '2n+0'; + if (formula == 'odd') formula = '2n+1'; + if (mm = formula.match(/^(\d+)$/)) // digit only + return '[' + fragment + "= " + mm[1] + ']'; + if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b + if (mm[1] == "-") mm[1] = -1; + var a = mm[1] ? Number(mm[1]) : 1; + var b = mm[2] ? Number(mm[2]) : 0; + predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " + + "((#{fragment} - #{b}) div #{a} >= 0)]"; + return new Template(predicate).evaluate({ + fragment: fragment, a: a, b: b }); + } + } + } + }, + + criteria: { + tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;', + className: 'n = h.className(n, r, "#{1}", c); c = false;', + id: 'n = h.id(n, r, "#{1}", c); c = false;', + attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;', + attr: function(m) { + m[3] = (m[5] || m[6]); + return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m); + }, + pseudo: function(m) { + if (m[6]) m[6] = m[6].replace(/"/g, '\\"'); + return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m); + }, + descendant: 'c = "descendant";', + child: 'c = "child";', + adjacent: 'c = "adjacent";', + laterSibling: 'c = "laterSibling";' + }, + + 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|([^'"][^\]]*?)))?\]/ + }, + + // for Selector.match and Element#match + 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 && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]); + } + }, + + handlers: { + // UTILITY FUNCTIONS + // joins two collections + concat: function(a, b) { + for (var i = 0, node; node = b[i]; i++) + a.push(node); + return a; + }, + + // marks an array of nodes for counting + mark: function(nodes) { + var _true = Prototype.emptyFunction; + for (var i = 0, node; node = nodes[i]; i++) + node._countedByPrototype = _true; + return nodes; + }, + + unmark: function(nodes) { + for (var i = 0, node; node = nodes[i]; i++) + node._countedByPrototype = undefined; + return nodes; + }, + + // mark each child node with its position (for nth calls) + // "ofType" flag indicates whether we're indexing for nth-of-type + // rather than nth-child + index: function(parentNode, reverse, ofType) { + parentNode._countedByPrototype = Prototype.emptyFunction; + if (reverse) { + for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) { + var node = nodes[i]; + if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++; + } + } else { + for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++) + if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++; + } + }, + + // filters out duplicates and extends all nodes + unique: function(nodes) { + if (nodes.length == 0) return nodes; + var results = [], n; + for (var i = 0, l = nodes.length; i < l; i++) + if (!(n = nodes[i])._countedByPrototype) { + n._countedByPrototype = Prototype.emptyFunction; + results.push(Element.extend(n)); + } + return Selector.handlers.unmark(results); + }, + + // COMBINATOR FUNCTIONS + descendant: function(nodes) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) + h.concat(results, node.getElementsByTagName('*')); + return results; + }, + + child: function(nodes) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) { + for (var j = 0, child; child = node.childNodes[j]; j++) + if (child.nodeType == 1 && child.tagName != '!') results.push(child); + } + return results; + }, + + adjacent: function(nodes) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + var next = this.nextElementSibling(node); + if (next) results.push(next); + } + return results; + }, + + laterSibling: function(nodes) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) + h.concat(results, Element.nextSiblings(node)); + return results; + }, + + nextElementSibling: function(node) { + while (node = node.nextSibling) + if (node.nodeType == 1) return node; + return null; + }, + + previousElementSibling: function(node) { + while (node = node.previousSibling) + if (node.nodeType == 1) return node; + return null; + }, + + // TOKEN FUNCTIONS + tagName: function(nodes, root, tagName, combinator) { + var uTagName = tagName.toUpperCase(); + var results = [], h = Selector.handlers; + if (nodes) { + if (combinator) { + // fastlane for ordinary descendant combinators + if (combinator == "descendant") { + for (var i = 0, node; node = nodes[i]; i++) + h.concat(results, node.getElementsByTagName(tagName)); + return results; + } else nodes = this[combinator](nodes); + if (tagName == "*") return nodes; + } + for (var i = 0, node; node = nodes[i]; i++) + if (node.tagName.toUpperCase() === uTagName) results.push(node); + return results; + } else return root.getElementsByTagName(tagName); + }, + + id: function(nodes, root, id, combinator) { + var targetNode = $(id), h = Selector.handlers; + if (!targetNode) return []; + if (!nodes && root == document) return [targetNode]; + if (nodes) { + if (combinator) { + if (combinator == 'child') { + for (var i = 0, node; node = nodes[i]; i++) + if (targetNode.parentNode == node) return [targetNode]; + } else if (combinator == 'descendant') { + for (var i = 0, node; node = nodes[i]; i++) + if (Element.descendantOf(targetNode, node)) return [targetNode]; + } else if (combinator == 'adjacent') { + for (var i = 0, node; node = nodes[i]; i++) + if (Selector.handlers.previousElementSibling(targetNode) == node) + return [targetNode]; + } else nodes = h[combinator](nodes); + } + for (var i = 0, node; node = nodes[i]; i++) + if (node == targetNode) return [targetNode]; + return []; + } + return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : []; + }, + + className: function(nodes, root, className, combinator) { + if (nodes && combinator) nodes = this[combinator](nodes); + return Selector.handlers.byClassName(nodes, root, className); + }, + + byClassName: function(nodes, root, className) { + if (!nodes) nodes = Selector.handlers.descendant([root]); + var needle = ' ' + className + ' '; + for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) { + nodeClassName = node.className; + if (nodeClassName.length == 0) continue; + if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle)) + results.push(node); + } + return results; + }, + + attrPresence: function(nodes, root, attr, combinator) { + if (!nodes) nodes = root.getElementsByTagName("*"); + if (nodes && combinator) nodes = this[combinator](nodes); + var results = []; + for (var i = 0, node; node = nodes[i]; i++) + if (Element.hasAttribute(node, attr)) results.push(node); + return results; + }, + + attr: function(nodes, root, attr, value, operator, combinator) { + if (!nodes) nodes = root.getElementsByTagName("*"); + if (nodes && combinator) nodes = this[combinator](nodes); + var handler = Selector.operators[operator], results = []; + for (var i = 0, node; node = nodes[i]; i++) { + var nodeValue = Element.readAttribute(node, attr); + if (nodeValue === null) continue; + if (handler(nodeValue, value)) results.push(node); + } + return results; + }, + + pseudo: function(nodes, name, value, root, combinator) { + if (nodes && combinator) nodes = this[combinator](nodes); + if (!nodes) nodes = root.getElementsByTagName("*"); + return Selector.pseudos[name](nodes, value, root); + } + }, + + pseudos: { + 'first-child': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + if (Selector.handlers.previousElementSibling(node)) continue; + results.push(node); + } + return results; + }, + 'last-child': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + if (Selector.handlers.nextElementSibling(node)) continue; + results.push(node); + } + return results; + }, + 'only-child': function(nodes, value, root) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (!h.previousElementSibling(node) && !h.nextElementSibling(node)) + results.push(node); + return results; + }, + 'nth-child': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root); + }, + 'nth-last-child': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root, true); + }, + 'nth-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root, false, true); + }, + 'nth-last-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root, true, true); + }, + 'first-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, "1", root, false, true); + }, + 'last-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, "1", root, true, true); + }, + 'only-of-type': function(nodes, formula, root) { + var p = Selector.pseudos; + return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root); + }, + + // handles the an+b logic + getIndices: function(a, b, total) { + if (a == 0) return b > 0 ? [b] : []; + return $R(1, total).inject([], function(memo, i) { + if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i); + return memo; + }); + }, + + // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type + nth: function(nodes, formula, root, reverse, ofType) { + if (nodes.length == 0) return []; + if (formula == 'even') formula = '2n+0'; + if (formula == 'odd') formula = '2n+1'; + var h = Selector.handlers, results = [], indexed = [], m; + h.mark(nodes); + for (var i = 0, node; node = nodes[i]; i++) { + if (!node.parentNode._countedByPrototype) { + h.index(node.parentNode, reverse, ofType); + indexed.push(node.parentNode); + } + } + if (formula.match(/^\d+$/)) { // just a number + formula = Number(formula); + for (var i = 0, node; node = nodes[i]; i++) + if (node.nodeIndex == formula) results.push(node); + } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b + if (m[1] == "-") m[1] = -1; + var a = m[1] ? Number(m[1]) : 1; + var b = m[2] ? Number(m[2]) : 0; + var indices = Selector.pseudos.getIndices(a, b, nodes.length); + for (var i = 0, node, l = indices.length; node = nodes[i]; i++) { + for (var j = 0; j < l; j++) + if (node.nodeIndex == indices[j]) results.push(node); + } + } + h.unmark(nodes); + h.unmark(indexed); + return results; + }, + + 'empty': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + // IE treats comments as element nodes + if (node.tagName == '!' || node.firstChild) continue; + results.push(node); + } + return results; + }, + + 'not': function(nodes, selector, root) { + var h = Selector.handlers, selectorType, m; + var exclusions = new Selector(selector).findElements(root); + h.mark(exclusions); + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (!node._countedByPrototype) results.push(node); + h.unmark(exclusions); + return results; + }, + + 'enabled': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (!node.disabled && (!node.type || node.type !== 'hidden')) + results.push(node); + return results; + }, + + 'disabled': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (node.disabled) results.push(node); + return results; + }, + + 'checked': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (node.checked) results.push(node); + return results; + } + }, + + operators: { + '=': function(nv, v) { return nv == v; }, + '!=': function(nv, v) { return nv != v; }, + '^=': function(nv, v) { return nv == v || nv && nv.startsWith(v); }, + '$=': function(nv, v) { return nv == v || nv && nv.endsWith(v); }, + '*=': function(nv, v) { return nv == v || nv && nv.include(v); }, + '$=': function(nv, v) { return nv.endsWith(v); }, + '*=': function(nv, v) { return nv.include(v); }, + '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); }, + '|=': function(nv, v) { return ('-' + (nv || "").toUpperCase() + + '-').include('-' + (v || "").toUpperCase() + '-'); } + }, + + split: function(expression) { + var expressions = []; + expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) { + expressions.push(m[1].strip()); + }); + return expressions; + }, + + matchElements: function(elements, expression) { + var matches = $$(expression), h = Selector.handlers; + h.mark(matches); + for (var i = 0, results = [], element; element = elements[i]; i++) + if (element._countedByPrototype) results.push(element); + h.unmark(matches); + return results; + }, + + findElement: function(elements, expression, index) { + if (Object.isNumber(expression)) { + index = expression; expression = false; + } + return Selector.matchElements(elements, expression || '*')[index || 0]; + }, + + findChildElements: function(element, expressions) { + expressions = Selector.split(expressions.join(',')); + var results = [], h = Selector.handlers; + for (var i = 0, l = expressions.length, selector; i < l; i++) { + selector = new Selector(expressions[i].strip()); + h.concat(results, selector.findElements(element)); + } + return (l > 1) ? h.unique(results) : results; + } +}); + +if (Prototype.Browser.IE) { + Object.extend(Selector.handlers, { + // IE returns comment nodes on getElementsByTagName("*"). + // Filter them out. + concat: function(a, b) { + for (var i = 0, node; node = b[i]; i++) + if (node.tagName !== "!") a.push(node); + return a; + }, + + // IE improperly serializes _countedByPrototype in (inner|outer)HTML. + unmark: function(nodes) { + for (var i = 0, node; node = nodes[i]; i++) + node.removeAttribute('_countedByPrototype'); + return nodes; + } + }); +} + +function $$() { + return Selector.findChildElements(document, $A(arguments)); +} +var Form = { + reset: function(form) { + $(form).reset(); + return form; + }, + + serializeElements: function(elements, options) { + if (typeof options != 'object') options = { hash: !!options }; + else if (Object.isUndefined(options.hash)) options.hash = true; + var key, value, submitted = false, submit = options.submit; + + var data = elements.inject({ }, function(result, element) { + if (!element.disabled && element.name) { + key = element.name; value = $(element).getValue(); + if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted && + submit !== false && (!submit || key == submit) && (submitted = true)))) { + if (key in result) { + // a key is already present; construct an array of values + if (!Object.isArray(result[key])) result[key] = [result[key]]; + result[key].push(value); + } + else result[key] = value; + } + } + return result; + }); + + return options.hash ? data : Object.toQueryString(data); + } +}; + +Form.Methods = { + serialize: function(form, options) { + return Form.serializeElements(Form.getElements(form), options); + }, + + getElements: function(form) { + return $A($(form).getElementsByTagName('*')).inject([], + function(elements, child) { + if (Form.Element.Serializers[child.tagName.toLowerCase()]) + elements.push(Element.extend(child)); + return elements; + } + ); + }, + + getInputs: function(form, typeName, name) { + form = $(form); + var inputs = form.getElementsByTagName('input'); + + if (!typeName && !name) return $A(inputs).map(Element.extend); + + for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) { + var input = inputs[i]; + if ((typeName && input.type != typeName) || (name && input.name != name)) + continue; + matchingInputs.push(Element.extend(input)); + } + + return matchingInputs; + }, + + disable: function(form) { + form = $(form); + Form.getElements(form).invoke('disable'); + return form; + }, + + enable: function(form) { + form = $(form); + Form.getElements(form).invoke('enable'); + return form; + }, + + findFirstElement: function(form) { + var elements = $(form).getElements().findAll(function(element) { + return 'hidden' != element.type && !element.disabled; + }); + var firstByIndex = elements.findAll(function(element) { + return element.hasAttribute('tabIndex') && element.tabIndex >= 0; + }).sortBy(function(element) { return element.tabIndex }).first(); + + return firstByIndex ? firstByIndex : elements.find(function(element) { + return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase()); + }); + }, + + focusFirstElement: function(form) { + form = $(form); + form.findFirstElement().activate(); + return form; + }, + + request: function(form, options) { + form = $(form), options = Object.clone(options || { }); + + var params = options.parameters, action = form.readAttribute('action') || ''; + if (action.blank()) action = window.location.href; + options.parameters = form.serialize(true); + + if (params) { + if (Object.isString(params)) params = params.toQueryParams(); + Object.extend(options.parameters, params); + } + + if (form.hasAttribute('method') && !options.method) + options.method = form.method; + + return new Ajax.Request(action, options); + } +}; + +/*--------------------------------------------------------------------------*/ + +Form.Element = { + focus: function(element) { + $(element).focus(); + return element; + }, + + select: function(element) { + $(element).select(); + return element; + } +}; + +Form.Element.Methods = { + serialize: function(element) { + element = $(element); + if (!element.disabled && element.name) { + var value = element.getValue(); + if (value != undefined) { + var pair = { }; + pair[element.name] = value; + return Object.toQueryString(pair); + } + } + return ''; + }, + + getValue: function(element) { + element = $(element); + var method = element.tagName.toLowerCase(); + return Form.Element.Serializers[method](element); + }, + + setValue: function(element, value) { + element = $(element); + var method = element.tagName.toLowerCase(); + Form.Element.Serializers[method](element, value); + return element; + }, + + clear: function(element) { + $(element).value = ''; + return element; + }, + + present: function(element) { + return $(element).value != ''; + }, + + activate: function(element) { + element = $(element); + try { + element.focus(); + if (element.select && (element.tagName.toLowerCase() != 'input' || + !['button', 'reset', 'submit'].include(element.type))) + element.select(); + } catch (e) { } + return element; + }, + + disable: function(element) { + element = $(element); + element.disabled = true; + return element; + }, + + enable: function(element) { + element = $(element); + element.disabled = false; + return element; + } +}; + +/*--------------------------------------------------------------------------*/ + +var Field = Form.Element; +var $F = Form.Element.Methods.getValue; + +/*--------------------------------------------------------------------------*/ + +Form.Element.Serializers = { + input: function(element, value) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + return Form.Element.Serializers.inputSelector(element, value); + default: + return Form.Element.Serializers.textarea(element, value); + } + }, + + inputSelector: function(element, value) { + if (Object.isUndefined(value)) return element.checked ? element.value : null; + else element.checked = !!value; + }, + + textarea: function(element, value) { + if (Object.isUndefined(value)) return element.value; + else element.value = value; + }, + + select: function(element, value) { + if (Object.isUndefined(value)) + return this[element.type == 'select-one' ? + 'selectOne' : 'selectMany'](element); + else { + var opt, currentValue, single = !Object.isArray(value); + for (var i = 0, length = element.length; i < length; i++) { + opt = element.options[i]; + currentValue = this.optionValue(opt); + if (single) { + if (currentValue == value) { + opt.selected = true; + return; + } + } + else opt.selected = value.include(currentValue); + } + } + }, + + selectOne: function(element) { + var index = element.selectedIndex; + return index >= 0 ? this.optionValue(element.options[index]) : null; + }, + + selectMany: function(element) { + var values, length = element.length; + if (!length) return null; + + for (var i = 0, values = []; i < length; i++) { + var opt = element.options[i]; + if (opt.selected) values.push(this.optionValue(opt)); + } + return values; + }, + + optionValue: function(opt) { + // extend element because hasAttribute may not be native + return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text; + } +}; + +/*--------------------------------------------------------------------------*/ + +Abstract.TimedObserver = Class.create(PeriodicalExecuter, { + initialize: function($super, element, frequency, callback) { + $super(callback, frequency); + this.element = $(element); + this.lastValue = this.getValue(); + }, + + execute: function() { + var value = this.getValue(); + if (Object.isString(this.lastValue) && Object.isString(value) ? + this.lastValue != value : String(this.lastValue) != String(value)) { + this.callback(this.element, value); + this.lastValue = value; + } + } +}); + +Form.Element.Observer = Class.create(Abstract.TimedObserver, { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.Observer = Class.create(Abstract.TimedObserver, { + getValue: function() { + return Form.serialize(this.element); + } +}); + +/*--------------------------------------------------------------------------*/ + +Abstract.EventObserver = Class.create({ + initialize: function(element, callback) { + this.element = $(element); + this.callback = callback; + + this.lastValue = this.getValue(); + if (this.element.tagName.toLowerCase() == 'form') + this.registerFormCallbacks(); + else + this.registerCallback(this.element); + }, + + onElementEvent: function() { + var value = this.getValue(); + if (this.lastValue != value) { + this.callback(this.element, value); + this.lastValue = value; + } + }, + + registerFormCallbacks: function() { + Form.getElements(this.element).each(this.registerCallback, this); + }, + + registerCallback: function(element) { + if (element.type) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + Event.observe(element, 'click', this.onElementEvent.bind(this)); + break; + default: + Event.observe(element, 'change', this.onElementEvent.bind(this)); + break; + } + } + } +}); + +Form.Element.EventObserver = Class.create(Abstract.EventObserver, { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.EventObserver = Class.create(Abstract.EventObserver, { + getValue: function() { + return Form.serialize(this.element); + } +}); +if (!window.Event) var Event = { }; + +Object.extend(Event, { + KEY_BACKSPACE: 8, + KEY_TAB: 9, + KEY_RETURN: 13, + KEY_ESC: 27, + KEY_LEFT: 37, + KEY_UP: 38, + KEY_RIGHT: 39, + KEY_DOWN: 40, + KEY_DELETE: 46, + KEY_HOME: 36, + KEY_END: 35, + KEY_PAGEUP: 33, + KEY_PAGEDOWN: 34, + KEY_INSERT: 45, + + cache: { }, + + relatedTarget: function(event) { + var element; + switch(event.type) { + case 'mouseover': element = event.fromElement; break; + case 'mouseout': element = event.toElement; break; + default: return null; + } + return Element.extend(element); + } +}); + +Event.Methods = (function() { + var isButton; + + if (Prototype.Browser.IE) { + var buttonMap = { 0: 1, 1: 4, 2: 2 }; + isButton = function(event, code) { + return event.button == buttonMap[code]; + }; + + } else if (Prototype.Browser.WebKit) { + isButton = function(event, code) { + switch (code) { + case 0: return event.which == 1 && !event.metaKey; + case 1: return event.which == 1 && event.metaKey; + default: return false; + } + }; + + } else { + isButton = function(event, code) { + return event.which ? (event.which === code + 1) : (event.button === code); + }; + } + + return { + isLeftClick: function(event) { return isButton(event, 0) }, + isMiddleClick: function(event) { return isButton(event, 1) }, + isRightClick: function(event) { return isButton(event, 2) }, + + element: function(event) { + event = Event.extend(event); + + var node = event.target, + type = event.type, + currentTarget = event.currentTarget; + + if (currentTarget && currentTarget.tagName) { + // Firefox screws up the "click" event when moving between radio buttons + // via arrow keys. It also screws up the "load" and "error" events on images, + // reporting the document as the target instead of the original image. + if (type === 'load' || type === 'error' || + (type === 'click' && currentTarget.tagName.toLowerCase() === 'input' + && currentTarget.type === 'radio')) + node = currentTarget; + } + if (node.nodeType == Node.TEXT_NODE) node = node.parentNode; + return Element.extend(node); + }, + + findElement: function(event, expression) { + var element = Event.element(event); + if (!expression) return element; + var elements = [element].concat(element.ancestors()); + return Selector.findElement(elements, expression, 0); + }, + + pointer: function(event) { + var docElement = document.documentElement, + body = document.body || { scrollLeft: 0, scrollTop: 0 }; + return { + x: event.pageX || (event.clientX + + (docElement.scrollLeft || body.scrollLeft) - + (docElement.clientLeft || 0)), + y: event.pageY || (event.clientY + + (docElement.scrollTop || body.scrollTop) - + (docElement.clientTop || 0)) + }; + }, + + pointerX: function(event) { return Event.pointer(event).x }, + pointerY: function(event) { return Event.pointer(event).y }, + + stop: function(event) { + Event.extend(event); + event.preventDefault(); + event.stopPropagation(); + event.stopped = true; + } + }; +})(); + +Event.extend = (function() { + var methods = Object.keys(Event.Methods).inject({ }, function(m, name) { + m[name] = Event.Methods[name].methodize(); + return m; + }); + + if (Prototype.Browser.IE) { + Object.extend(methods, { + stopPropagation: function() { this.cancelBubble = true }, + preventDefault: function() { this.returnValue = false }, + inspect: function() { return "[object Event]" } + }); + + return function(event) { + if (!event) return false; + if (event._extendedByPrototype) return event; + + event._extendedByPrototype = Prototype.emptyFunction; + var pointer = Event.pointer(event); + Object.extend(event, { + target: event.srcElement, + relatedTarget: Event.relatedTarget(event), + pageX: pointer.x, + pageY: pointer.y + }); + return Object.extend(event, methods); + }; + + } else { + Event.prototype = Event.prototype || document.createEvent("HTMLEvents")['__proto__']; + Object.extend(Event.prototype, methods); + return Prototype.K; + } +})(); + +Object.extend(Event, (function() { + var cache = Event.cache; + + function getEventID(element) { + if (element._prototypeEventID) return element._prototypeEventID[0]; + arguments.callee.id = arguments.callee.id || 1; + return element._prototypeEventID = [++arguments.callee.id]; + } + + function getDOMEventName(eventName) { + if (eventName && eventName.include(':')) return "dataavailable"; + return eventName; + } + + function getCacheForID(id) { + return cache[id] = cache[id] || { }; + } + + function getWrappersForEventName(id, eventName) { + var c = getCacheForID(id); + return c[eventName] = c[eventName] || []; + } + + function createWrapper(element, eventName, handler) { + var id = getEventID(element); + var c = getWrappersForEventName(id, eventName); + if (c.pluck("handler").include(handler)) return false; + + var wrapper = function(event) { + if (!Event || !Event.extend || + (event.eventName && event.eventName != eventName)) + return false; + + Event.extend(event); + handler.call(element, event); + }; + + wrapper.handler = handler; + c.push(wrapper); + return wrapper; + } + + function findWrapper(id, eventName, handler) { + var c = getWrappersForEventName(id, eventName); + return c.find(function(wrapper) { return wrapper.handler == handler }); + } + + function destroyWrapper(id, eventName, handler) { + var c = getCacheForID(id); + if (!c[eventName]) return false; + c[eventName] = c[eventName].without(findWrapper(id, eventName, handler)); + } + + function destroyCache() { + for (var id in cache) + for (var eventName in cache[id]) + cache[id][eventName] = null; + } + + + // Internet Explorer needs to remove event handlers on page unload + // in order to avoid memory leaks. + if (window.attachEvent) { + window.attachEvent("onunload", destroyCache); + } + + // Safari has a dummy event handler on page unload so that it won't + // use its bfcache. Safari <= 3.1 has an issue with restoring the "document" + // object when page is returned to via the back button using its bfcache. + if (Prototype.Browser.WebKit) { + window.addEventListener('unload', Prototype.emptyFunction, false); + } + + return { + observe: function(element, eventName, handler) { + element = $(element); + var name = getDOMEventName(eventName); + + var wrapper = createWrapper(element, eventName, handler); + if (!wrapper) return element; + + if (element.addEventListener) { + element.addEventListener(name, wrapper, false); + } else { + element.attachEvent("on" + name, wrapper); + } + + return element; + }, + + stopObserving: function(element, eventName, handler) { + element = $(element); + var id = getEventID(element), name = getDOMEventName(eventName); + + if (!handler && eventName) { + getWrappersForEventName(id, eventName).each(function(wrapper) { + element.stopObserving(eventName, wrapper.handler); + }); + return element; + + } else if (!eventName) { + Object.keys(getCacheForID(id)).each(function(eventName) { + element.stopObserving(eventName); + }); + return element; + } + + var wrapper = findWrapper(id, eventName, handler); + if (!wrapper) return element; + + if (element.removeEventListener) { + element.removeEventListener(name, wrapper, false); + } else { + element.detachEvent("on" + name, wrapper); + } + + destroyWrapper(id, eventName, handler); + + return element; + }, + + fire: function(element, eventName, memo) { + element = $(element); + if (element == document && document.createEvent && !element.dispatchEvent) + element = document.documentElement; + + var event; + if (document.createEvent) { + event = document.createEvent("HTMLEvents"); + event.initEvent("dataavailable", true, true); + } else { + event = document.createEventObject(); + event.eventType = "ondataavailable"; + } + + event.eventName = eventName; + event.memo = memo || { }; + + if (document.createEvent) { + element.dispatchEvent(event); + } else { + element.fireEvent(event.eventType, event); + } + + return Event.extend(event); + } + }; +})()); + +Object.extend(Event, Event.Methods); + +Element.addMethods({ + fire: Event.fire, + observe: Event.observe, + stopObserving: Event.stopObserving +}); + +Object.extend(document, { + fire: Element.Methods.fire.methodize(), + observe: Element.Methods.observe.methodize(), + stopObserving: Element.Methods.stopObserving.methodize(), + loaded: false +}); + +(function() { + /* Support for the DOMContentLoaded event is based on work by Dan Webb, + Matthias Miller, Dean Edwards and John Resig. */ + + var timer; + + function fireContentLoadedEvent() { + if (document.loaded) return; + if (timer) window.clearInterval(timer); + document.fire("dom:loaded"); + document.loaded = true; + } + + if (document.addEventListener) { + if (Prototype.Browser.WebKit) { + timer = window.setInterval(function() { + if (/loaded|complete/.test(document.readyState)) + fireContentLoadedEvent(); + }, 0); + + Event.observe(window, "load", fireContentLoadedEvent); + + } else { + document.addEventListener("DOMContentLoaded", + fireContentLoadedEvent, false); + } + + } else { + document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>"); + $("__onDOMContentLoaded").onreadystatechange = function() { + if (this.readyState == "complete") { + this.onreadystatechange = null; + fireContentLoadedEvent(); + } + }; + } +})(); +/*------------------------------- DEPRECATED -------------------------------*/ + +Hash.toQueryString = Object.toQueryString; + +var Toggle = { display: Element.toggle }; + +Element.Methods.childOf = Element.Methods.descendantOf; + +var Insertion = { + Before: function(element, content) { + return Element.insert(element, {before:content}); + }, + + Top: function(element, content) { + return Element.insert(element, {top:content}); + }, + + Bottom: function(element, content) { + return Element.insert(element, {bottom:content}); + }, + + After: function(element, content) { + return Element.insert(element, {after:content}); + } +}; + +var $continue = new Error('"throw $continue" is deprecated, use "return" instead'); + +// This should be moved to script.aculo.us; notice the deprecated methods +// further below, that map to the newer Element methods. +var Position = { + // set to true if needed, warning: firefox performance problems + // NOT neeeded for page scrolling, only if draggable contained in + // scrollable elements + includeScrollOffsets: false, + + // must be called before calling withinIncludingScrolloffset, every time the + // page is scrolled + prepare: function() { + this.deltaX = window.pageXOffset + || document.documentElement.scrollLeft + || document.body.scrollLeft + || 0; + this.deltaY = window.pageYOffset + || document.documentElement.scrollTop + || document.body.scrollTop + || 0; + }, + + // caches x/y coordinate pair to use with overlap + within: function(element, x, y) { + if (this.includeScrollOffsets) + return this.withinIncludingScrolloffsets(element, x, y); + this.xcomp = x; + this.ycomp = y; + this.offset = Element.cumulativeOffset(element); + + return (y >= this.offset[1] && + y < this.offset[1] + element.offsetHeight && + x >= this.offset[0] && + x < this.offset[0] + element.offsetWidth); + }, + + withinIncludingScrolloffsets: function(element, x, y) { + var offsetcache = Element.cumulativeScrollOffset(element); + + this.xcomp = x + offsetcache[0] - this.deltaX; + this.ycomp = y + offsetcache[1] - this.deltaY; + this.offset = Element.cumulativeOffset(element); + + return (this.ycomp >= this.offset[1] && + this.ycomp < this.offset[1] + element.offsetHeight && + this.xcomp >= this.offset[0] && + this.xcomp < this.offset[0] + element.offsetWidth); + }, + + // within must be called directly before + overlap: function(mode, element) { + if (!mode) return 0; + if (mode == 'vertical') + return ((this.offset[1] + element.offsetHeight) - this.ycomp) / + element.offsetHeight; + if (mode == 'horizontal') + return ((this.offset[0] + element.offsetWidth) - this.xcomp) / + element.offsetWidth; + }, + + // Deprecation layer -- use newer Element methods now (1.5.2). + + cumulativeOffset: Element.Methods.cumulativeOffset, + + positionedOffset: Element.Methods.positionedOffset, + + absolutize: function(element) { + Position.prepare(); + return Element.absolutize(element); + }, + + relativize: function(element) { + Position.prepare(); + return Element.relativize(element); + }, + + realOffset: Element.Methods.cumulativeScrollOffset, + + offsetParent: Element.Methods.getOffsetParent, + + page: Element.Methods.viewportOffset, + + clone: function(source, target, options) { + options = options || { }; + return Element.clonePosition(target, source, options); + } +}; + +/*--------------------------------------------------------------------------*/ + +if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){ + function iter(name) { + return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]"; + } + + instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ? + function(element, className) { + className = className.toString().strip(); + var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className); + return cond ? document._getElementsByXPath('.//*' + cond, element) : []; + } : function(element, className) { + className = className.toString().strip(); + var elements = [], classNames = (/\s/.test(className) ? $w(className) : null); + if (!classNames && !className) return elements; + + var nodes = $(element).getElementsByTagName('*'); + className = ' ' + className + ' '; + + for (var i = 0, child, cn; child = nodes[i]; i++) { + if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) || + (classNames && classNames.all(function(name) { + return !name.toString().blank() && cn.include(' ' + name + ' '); + })))) + elements.push(Element.extend(child)); + } + return elements; + }; + + return function(className, parentElement) { + return $(parentElement || document.body).getElementsByClassName(className); + }; +}(Element.Methods); + +/*--------------------------------------------------------------------------*/ + +Element.ClassNames = Class.create(); +Element.ClassNames.prototype = { + initialize: function(element) { + this.element = $(element); + }, + + _each: function(iterator) { + this.element.className.split(/\s+/).select(function(name) { + return name.length > 0; + })._each(iterator); + }, + + set: function(className) { + this.element.className = className; + }, + + add: function(classNameToAdd) { + if (this.include(classNameToAdd)) return; + this.set($A(this).concat(classNameToAdd).join(' ')); + }, + + remove: function(classNameToRemove) { + if (!this.include(classNameToRemove)) return; + this.set($A(this).without(classNameToRemove).join(' ')); + }, + + toString: function() { + return $A(this).join(' '); + } +}; + +Object.extend(Element.ClassNames.prototype, Enumerable); + +/*--------------------------------------------------------------------------*/ + +Element.addMethods(); \ No newline at end of file
robertbrook/findyourmp
3a3e16962b6ff620c6dd46eeb8fb43669144a7c4
fixed broken links
diff --git a/app/views/layouts/application.rhtml b/app/views/layouts/application.rhtml index c441437..8ff88db 100644 --- a/app/views/layouts/application.rhtml +++ b/app/views/layouts/application.rhtml @@ -1,248 +1,248 @@ <!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"> <head> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> <link rel="stylesheet" type="text/css" media="projection,screen" href="/stylesheets/reset.css" /> <link rel="stylesheet" type="text/css" media="projection,screen" href="/stylesheets/grid.css" /> <link rel="stylesheet" type="text/css" media="projection,screen" href="/stylesheets/main.css" /> <link rel="stylesheet" type="text/css" media="projection,screen" href="/stylesheets/mlo.css" /> <link rel="stylesheet" type="text/css" media="projection,screen" href="/stylesheets/fymp.css" /> <link rel="stylesheet" type="text/css" media="print" href="/stylesheets/print.css" /> <!--[if IE 8]> <link rel="stylesheet" type="text/css" media="projection,screen" href="/stylesheets/ie8.css" /> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" media="projection,screen" href="/stylesheets/ie7.css" /> <![endif]--> <!--[if lte IE 6]> <link rel="stylesheet" type="text/css" media="projection,screen" href="/stylesheets/ie6.css" /> <![endif]--> <script type="text/javascript" src="/javascripts/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="/javascripts/jquery.equalheights.js"></script> <script type="text/javascript" src="/javascripts/parliament-uk.js"></script> <script type="text/javascript" src="/javascripts/swfobject.js"></script> <% if @show_postcode_autodiscovery_links %> <%= auto_discovery_link_tag(:xml, @url_for_this + ".xml") %> <%= auto_discovery_link_tag(:json, @url_for_this + ".json") %> <%= auto_discovery_link_tag(:js, @url_for_this + ".js") %> <%= auto_discovery_link_tag(:text, @url_for_this + ".text") %> <%= auto_discovery_link_tag(:csv, @url_for_this + ".csv") %> <%= auto_discovery_link_tag(:yaml, @url_for_this + ".yaml") %> <% end %> <% if @javascript %> <%= javascript_include_tag @javascript %> <% end %> <script type="text/javascript"> /*<![CDATA[*/ $(document).ready(function(){ var settings = { main:{ advancedSearchAjaxUrl: '/AJAX/MemberNames.ashx', calendarListingAjaxUrl: '/AJAX/CalendarMonth.ashx', publicationsAndRecordsInitialShow: 3 }, woa:{ ajaxFlashZoomArtworkUrl: '/AJAX/ImageZoom.ashx' }, masterPage: 'threecolumn', pageType: 'main-generic-content', pageInstanceId: '29500' } parliamentUK.init(settings); }); /*]]>*/ </script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title><%= @title ? "#{@title} Find Your MP" : "Search (Find Your MP)" %> - UK Parliament</title> <meta name="keywords" content="UK Parliament, Find your MP, Find my MP, Member of Parliament" /> <% if @meta_description %><meta name="description" content="<%= @meta_description %>" /><% end %> <% if @nofollow %><meta name="robots" content="NOINDEX, NOFOLLOW" /><% end %> <meta name="language" content="English" /> <meta name="viewport" content="width=940" /> <meta name="sections" content="Parliament home page~MPs, Lords &amp; offices~MPs~Find your MP" /> <title> Find your MP - UK Parliament </title> </head> <body class="mlo"> <script type="text/javascript"> /*<![CDATA[*/ //load any sub-site JavaScript files (if required) parliamentUK.loadSubSiteJavaScript($(document.body).attr('class')); /*]]>*/ </script> <div id="wrapper" class="commons"> <div id="header"> - <a href="/"><img src="/images/parliament-uk-logo.gif" alt="Parliament UK" /></a> + <a href="http://www.parliament.uk"><img src="/images/parliament-uk-logo.gif" alt="Parliament UK" /></a> <fieldset class="site-search"> <ul> - <li><a id="ctl00_ctl00_ctlGlobalHeader_ctlNavigationLinks_rptLinks_ctl01_hypLink" href="/site-information/accessibility/">Accessibility</a></li> - <li><a id="ctl00_ctl00_ctlGlobalHeader_ctlNavigationLinks_rptLinks_ctl02_hypLink" href="/site-information/contact-us/">Contact us</a></li> - <li><a id="ctl00_ctl00_ctlGlobalHeader_ctlNavigationLinks_rptLinks_ctl03_hypLink" href="/site-information/rss-feeds/">RSS feeds</a></li> - <li class="last"><a id="ctl00_ctl00_ctlGlobalHeader_ctlNavigationLinks_rptLinks_ctl04_hypLink" href="/site-information/email-alerts/">Email alerts</a></li> + <li><a id="ctl00_ctl00_ctlGlobalHeader_ctlNavigationLinks_rptLinks_ctl01_hypLink" href="http://www.parliament.uk/site-information/accessibility/">Accessibility</a></li> + <li><a id="ctl00_ctl00_ctlGlobalHeader_ctlNavigationLinks_rptLinks_ctl02_hypLink" href="http://www.parliament.uk/site-information/contact-us/">Contact us</a></li> + <li><a id="ctl00_ctl00_ctlGlobalHeader_ctlNavigationLinks_rptLinks_ctl03_hypLink" href="http://www.parliament.uk/site-information/rss-feeds/">RSS feeds</a></li> + <li class="last"><a id="ctl00_ctl00_ctlGlobalHeader_ctlNavigationLinks_rptLinks_ctl04_hypLink" href="http://www.parliament.uk/site-information/email-alerts/">Email alerts</a></li> </ul> <form method="get" action="http://www.parliament.uk/search/results"> <h4 class="marker">Site search</h4> <ol> <li> <label for="q" id="q" class="access">Search</label> <input name="q" type="text" id="q" /> </li> </ol> <input type="submit" value="Search" /> <ul id="search-options"> - <li class="last"><a href="/search/advanced/">Advanced search</a></li> + <li class="last"><a href="http://www.parliament.uk/search/advanced/">Advanced search</a></li> </ul> </fieldset> </form> <div id="navigation"> <ul id="level-1"> <li><a href="http://www.parliament.uk/">Home</a></li> <li><a href="http://www.parliament.uk/business/">Parliamentary business</a></li> <li class="over"><a href="http://www.parliament.uk/mps-lords-and-offices/">MPs, Lords &amp; offices</a></li> <li><a href="http://www.parliament.uk/about/">About Parliament</a></li> <li><a href="http://www.parliament.uk/get-involved/">Get involved</a></li> <li><a href="http://www.parliament.uk/visiting/">Visiting</a></li> <li class="last"><a href="http://www.parliament.uk/education/">Education</a></li> </ul> <ul id="level-2"> <li><a href="http://www.parliament.uk/mps-lords-and-offices/lords/">Lords</a></li> <li class="over"><a href="http://www.parliament.uk/mps-lords-and-offices/mps/">MPs</a></li> <li><a href="http://www.parliament.uk/mps-lords-and-offices/offices/">Parliamentary offices</a></li> <li><a href="http://www.parliament.uk/mps-lords-and-offices/members-allowances/">Members' allowances</a></li> <li><a href="http://www.parliament.uk/mps-lords-and-offices/standards-and-interests/">Standards &amp; financial interests</a></li> <li><a href="http://www.parliament.uk/mps-lords-and-offices/government-and-opposition/">Government &amp; opposition</a></li> </ul> </div> <div id="breadcrumb"> <div class="inner"> <strong>You are here:</strong> <ul><li><a href="http://www.parliament.uk/">Parliament home page</a><ul><li><a href="http://www.parliament.uk/mps-lords-and-offices/">MPs, Lords &amp; offices</a><ul><li><a href="http://www.parliament.uk/mps-lords-and-offices/mps/">MPs</a><ul><li><%= @crumbtrail ? "<a href=\"/\">Find your MP</a> #{@crumbtrail}" : "Find your MP" %></li></ul></li></ul></li></ul></li></ul> </div> </div> </div> <h4 class="marker">Navigation</h4> <div id="secondary-navigation"> <ul> - <li class="grand-parent"><a href="/mps-lords-and-offices/mps/">MPs</a> + <li class="grand-parent"><a href="http://www.parliament.uk/mps-lords-and-offices/mps/">MPs</a> <ul> <li class="parent"> - <a href="/mps-lords-and-offices/mps/Find-your-MP/">Find your MP</a> + <a href="http://www.parliament.uk/mps-lords-and-offices/mps/Find-your-MP/">Find your MP</a> <ul> - <li><a href="/mps-lords-and-offices/mps/Find-your-MP/help/">Help with Find your MP</a></li> + <li><a href="http://www.parliament.uk/mps-lords-and-offices/mps/Find-your-MP/help/">Help with Find your MP</a></li> </ul> </li> </ul> </li> </ul> </div> <div id="content" class="three-column"> <% if !is_admin? && RAILS_ENV != 'test' && @title != 'API' %> <div id="content-small"> <%else%> <div id="admin-content"> <%end%> <h4 class="marker">Main content</h4> <h1 id="ctl00_ctl00_SiteSpecificPlaceholder_ctlHeadingH1_h1Item"><!-- Start Indexing --> Find your MP<!-- Stop Indexing --> </h1> <div class="inner"> <!-- Start Indexing --> <div id="ctl00_ctl00_SiteSpecificPlaceholder_PageContent_ctlMainBody_wrapperDiv" class="rte"> <h2><%= @title ? "#{@title}" : "Search" %></h2> <% if flash[:notice] %> <div class="text <%= flash[:notice][/Successful/] ? 'info' : 'flash' %>"> <%= flash[:notice] %> </div> <% end %> <div><%= yield %></div> <!-- Stop Indexing --> </div> </div> </div> <% if !is_admin? && RAILS_ENV != 'test' && @title != 'API' %> <div id="panel"> <div class="local-module"> <h2>Related information</h2> <strong>Commons Information Office</strong> <p> Contact us to find out more about the work, history and membership of the House of Commons <ul class="square-bullets"> <li>E: <a href="mailto:hcinfo@parliament.uk">hcinfo@parliament.uk</a></li> <li>T: 020 7219 4272</li> </ul> More information about this office can be found on the <a href="http://www.parliament.uk/mps-lords-and-offices/offices/commons/hcio/">House of Commons Information Office page</a>. </p> </div> </div> <%end%> </div> <div id="footer"> <h4 class="marker">Footer links</h4> <ul> - <li><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl01_hypLink" href="/site-information/azindex/">A-Z index</a></li> - <li><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl02_hypLink" href="/site-information/glossary/">Glossary</a></li> - <li><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl03_hypLink" href="/site-information/contact-us/">Contact us</a></li> - <li><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl04_hypLink" href="/site-information/foi/">Freedom of Information</a></li> - <li><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl05_hypLink" href="/site-information/job-opportunities/">Jobs</a></li> - <li><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl06_hypLink" href="/site-information/using-this-website/">Using this website</a></li> + <li><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl01_hypLink" href="http://www.parliament.uk/site-information/azindex/">A-Z index</a></li> + <li><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl02_hypLink" href="http://www.parliament.uk/site-information/glossary/">Glossary</a></li> + <li><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl03_hypLink" href="http://www.parliament.uk/site-information/contact-us/">Contact us</a></li> + <li><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl04_hypLink" href="http://www.parliament.uk/site-information/foi/">Freedom of Information</a></li> + <li><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl05_hypLink" href="http://www.parliament.uk/site-information/job-opportunities/">Jobs</a></li> + <li><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl06_hypLink" href="http://www.parliament.uk/site-information/using-this-website/">Using this website</a></li> <% if is_admin? %> <li><%= link_to "Logout", user_session_path, :method => :delete %></li> <li><%= link_to 'Admin home', admin_path %></li> <% elsif RAILS_ENV == 'test' %> <li><%= link_to "Log In", new_user_session_path %></li> <% end %> - <li class="last"><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl07_hypLink" href="/site-information/copyright/">Copyright</a></li> + <li class="last"><a id="ctl00_ctl00_ctlGlobalFooter_ctlNavigationLinks_rptLinks_ctl07_hypLink" href="http://www.parliament.uk/site-information/copyright/">Copyright</a></li> </ul> </div> </div> <% if RAILS_ENV == 'production' %> <script type="text/javascript"> /*<![CDATA[*/ var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); /*]]>*/ </script> <script type="text/javascript"> /*<![CDATA[*/ if(tracking.enabled){ try{ var pageTracker = _gat._getTracker(tracking.accountID); pageTracker._trackPageview(); } catch(err){} } /*]]>*/ </script> <script type="text/javascript" src="/javascripts/lbi_ga.js"></script> <%end%> </body> </html>
robertbrook/findyourmp
f4c43bfb5ea90a195087fa223d7cce5279c1f418
fixed failing features
diff --git a/features/contact_mp.feature b/features/contact_mp.feature deleted file mode 100644 index c4fc4c6..0000000 --- a/features/contact_mp.feature +++ /dev/null @@ -1,79 +0,0 @@ -Feature: Contact MP - In order to contact my MP - as a constituent - want to send message via Web form - - Scenario: Follow the "send a message" link from postcode page - Given my MP is contactable via email - And I am on my Postcode page - When I follow "Email Frank Doran" - Then I should see Message Form - - Scenario: Follow the "send a message" link from constituency page - Given my MP is contactable via email - And I am on my Constituency page - When I follow "Email Frank Doran" - Then I should see Message Form - - Scenario: Preview message with compulsory field missing and see generic warning - Given I am on a new Message page - When I preview message without "Your email address" - And I should see "1 error prohibited this message from being previewed" - And I should see "Preview your message before sending" button - - Scenario Outline: Preview message with compulsory field missing and see detailed warning - Given I am on a new Message page - When I preview message without "<field_missing>" - Then I should see "<warning_message>" - - Examples: - | field_missing | warning_message | - | Your email address | Please enter your email address | - | Your full name | Please enter your full name | - | Your subject | Please enter your subject | - | Your message | Please enter your message | - - Scenario: Preview message with invalid email and see detailed warning - Given I am on a new Message page - When I preview message with an invalid sender email - Then I should see "1 error prohibited this message from being previewed" - And I should see "Please enter a valid email address" - - Scenario: Preview message with invalid email and see detailed warning - Given I am on a new Message page - When I preview message with a parliament.uk sender email - Then I should see "1 error prohibited this message from being previewed" - And I should see "Please enter a non parliament.uk email address" - - Scenario: Preview message with invalid postcode and see detailed warning - Given I am on a new Message page - When I preview message with an invalid postcode - Then I should see "1 error prohibited this message from being previewed" - And I should see "Please enter a valid postcode" - - Scenario: Preview message - Given I am on a new Message page - When I preview message - Then I should see "Re-edit your message" button - And I should see "Send message" button - - Scenario: Re-edit message - Given I am on a preview Message page - When I re-edit message - Then I should see "Preview your message before sending" button - When I preview message - Then I should see "Re-edit your message" button - And I should see "Send message" button - - Scenario: Send message - Given I am on a preview Message page - When I send message - Then I should see "Your message has been sent." - - Scenario: My MP is not contactable via email - Given I am on the Front page - And the MP in constituency "Motherwell and Wishaw" is not contactable via email - When I search for "Motherwell and Wishaw" - Then I should see "Mr Frank Roy" - And I should see "Mr Frank Roy cannot be contacted by email" - And I should see "from this website." diff --git a/features/edit_constituency_data.feature b/features/edit_constituency_data.feature index 8cbb0ac..3ffc12c 100644 --- a/features/edit_constituency_data.feature +++ b/features/edit_constituency_data.feature @@ -1,46 +1,41 @@ Feature: Edit constituency data In order to have correct information on website as a admin user want to edit constituency and member data Scenario: Follow the "edit" link from constituency page Given I am logged in as an admin user And I follow "Edit constituencies" And I follow "Aberdeen North" Then I should see Edit Constituency Form Scenario: Edit constituency and member details Given I am logged in as an admin user And I am on the Constituency edit page for "Aberdeen North" When I fill in "Constituency" with "Aberdeen East" And I fill in "Member" with "William Wallace" And I fill in "Member party" with "SNP" And I fill in "Member email" with "bill@parl.uk" And I fill in "Member biography url" with "http://the.re" And I fill in "Member website" with "http://it.is" And I press "Update" Then I should see "Aberdeen East" And I should see "William Wallace" And I should see "SNP" And I should see link to "http://the.re" And I should see link to "http://it.is" - And I should see "Email William Wallace" Scenario: Edit member email to be empty Given I am logged in as an admin user And I am on the Constituency edit page for "Aberdeen North" When I fill in "Member email" with "" And I press "Update" Then I should see "Frank Doran" - And I should see "Frank Doran cannot be contacted by email" - And I should see "from this website." - And I should not see "Email Frank Doran" Scenario: Set member requested contact url Given I am logged in as an admin user And I am on the Constituency edit page for "Aberdeen North" When I fill in "Requested contact url" with "http://member.requested.url/" And I press "Update" Then I should see "Frank Doran" - And I should see "Contact Frank Doran" diff --git a/features/find_mp_from_constituency_name.feature b/features/find_mp_from_constituency_name.feature index d3e1982..32021a9 100644 --- a/features/find_mp_from_constituency_name.feature +++ b/features/find_mp_from_constituency_name.feature @@ -1,66 +1,65 @@ Feature: Find MP from constituency name In order to contact my MP as a constituent want to find my MP using my constituency name Scenario: Enter a valid constituency name Given I am on the Front page When I search for "Aberdeen North" Then I should see "Aberdeen North" And I should see "Frank Doran" Scenario: Enter an invalid constituency name Given I am on the Front page When I search for "Tamaki" Then I should see html "Sorry: we couldn't find a constituency or MP when we searched for <code>Tamaki</code>." Scenario: Enter part of a valid constituency name that returns multiple results Given I am on the Front page When I search for "Aberdeen" Then I should see html "<strong class="highlight">Aberdeen</strong> North" And I should see html "<strong class="highlight">Aberdeen</strong> South" And I should see "Frank Doran" And I should see "Miss Anne Begg" When I follow "Aberdeen South" Then I should see "Aberdeen South" And I should see "Miss Anne Begg" Scenario: Enter a partial constituency name that returns a single result Given I am on the Front page When I search for "North" Then I should see "Aberdeen North" And I should not see "Aberdeen South" And I should see "Frank Doran" - And I should see "Email Frank Doran" And I should not see "Edit" Scenario: Enter a valid constituency with no sitting MP Given I am on the Front page When I search for "Glenrothes" Then I should see "Glenrothes" And I should see "There is no sitting Member of Parliament for this constituency." Scenario: Enter a single letter search term Given I am on the Front page When I search for "a" Then I should see "Sorry: we need more than two letters to search" And I should not see "berdeen North" And I should not see "berdeen South" Scenario: Enter a single letter search term Given I am on the Front page When I search for "ab" Then I should see "Sorry: we need more than two letters to search" And I should not see "erdeen North" And I should not see "erdeen South" Scenario: Enter a single letter search term Given I am on the Front page When I search for "abe" Then I should see html "<strong class="highlight">Abe</strong>rdeen North</a>" And I should see html "<strong class="highlight">Abe</strong>rdeen South</a>" Scenario: Enter a constituency name that returns no results Given I am on the Front page When I search for "Isle of Wight" Then I should see html "Sorry: we couldn't find a constituency or MP when we searched for <code>Isle of Wight</code>." diff --git a/features/find_mp_from_constituency_name_as_admin.feature b/features/find_mp_from_constituency_name_as_admin.feature index 2db1591..f03ffc8 100644 --- a/features/find_mp_from_constituency_name_as_admin.feature +++ b/features/find_mp_from_constituency_name_as_admin.feature @@ -1,13 +1,12 @@ Feature: Find MP from partial constituency name In order to edit MP details as a admin user want to find an MP using a partial constituency name Scenario: Enter a partial constituency name Given I am logged in as an admin user And I am on the Front page When I search for "North" Then I should see "Aberdeen North" And I should see "Frank Doran" - And I should see "Email Frank Doran" And I should not see "Edit"
robertbrook/findyourmp
b2d69fd0fa988dc6152f5d250f32b43b2d6b09d7
restored mapping for constituencies
diff --git a/config/routes.rb b/config/routes.rb index fa0f6d8..d181b7a 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,53 +1,55 @@ ActionController::Routing::Routes.draw do |map| + map.resources :constituencies + map.resource :account, :controller => "users" map.resources :users map.resource :user_session map.resource :constituency_list map.resources :password_resets map.root :controller => "postcodes" map.connect '/postcodes/:postcode.:format', :controller => "postcodes", :action => 'show' map.connect '/postcodes/:postcode', :controller => "postcodes", :action => 'show' map.connect '/search/:q.:format', :controller => "search", :action => 'show' map.connect '/search/:q', :controller => "search", :action => 'show' map.search '/search', :controller => "search", :action => 'index' map.connect '/constituencies/hide_members', :conditions => { :method => :post }, :controller => "constituencies", :action => 'hide_members' map.connect '/constituencies/unhide_members', :conditions => { :method => :post }, :controller => "constituencies", :action => 'unhide_members' map.admin '/admin', :controller => 'admin', :action => 'index' map.connect '/admin/sent', :controller => 'admin', :action => 'sent' map.connect '/admin/sent/:yyyy_mm', :controller => 'admin', :action => 'sent_by_month' map.connect '/admin/waiting_to_be_sent', :controller => 'admin', :action => 'waiting_to_be_sent' map.connect '/admin/stats', :controller => 'admin', :action => 'stats' map.shutdown '/admin/shutdown', :controller => 'admin', :action => 'shutdown' map.mailserver_status '/admin/mailserver_status', :controller => 'admin', :action => 'mailserver_status' map.blacklisted_postcodes '/admin/blacklist', :controller => 'blacklisted_postcodes', :action => 'index' map.connect '/admin/blacklist/restore/:code', :controller => 'blacklisted_postcodes', :action => 'restore' map.connect '/admin/blacklist/new', :controller => 'blacklisted_postcodes', :action => 'new' map.manual_postcodes '/admin/manual_postcodes', :controller => 'manual_postcodes', :action => 'index' map.connect '/admin/manual_postcodes/remove/:code', :controller => 'manual_postcodes', :action => 'remove' map.connect '/admin/manual_postcodes/new', :controller => 'manual_postcodes', :action => 'new' map.api '/api', :controller => 'api', :action => 'index' map.connect 'api/search', :controller => 'api', :action => 'search' map.connect 'api/postcodes', :controller => 'api', :action => 'postcodes' map.connect 'api/constituencies', :controller => 'api', :action => 'constituencies' map.connect '/commons/constituency/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/member/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/postcode/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/constituency/cons/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/member/cons/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/email/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/l/', :controller => 'postcodes', :action => 'redir' map.connect '/commons/', :controller => 'postcodes', :action => 'redir' map.connect '*bad_route', :controller => 'application', :action => 'render_not_found' end
robertbrook/findyourmp
9e0f497fd0c1ff6611bf8b83b7e16633489c489b
removed message routes
diff --git a/config/routes.rb b/config/routes.rb index 07a876a..fa0f6d8 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,58 +1,53 @@ ActionController::Routing::Routes.draw do |map| - map.resources :constituencies do |constituency| - constituency.resources :messages, :only => [:new, :create, :index] - end - map.connect '/constituencies/:constituency_id/messages/new', :conditions => { :method => :post }, :controller => 'messages', :action => 'new' - map.resource :account, :controller => "users" map.resources :users map.resource :user_session map.resource :constituency_list map.resources :password_resets map.root :controller => "postcodes" map.connect '/postcodes/:postcode.:format', :controller => "postcodes", :action => 'show' map.connect '/postcodes/:postcode', :controller => "postcodes", :action => 'show' map.connect '/search/:q.:format', :controller => "search", :action => 'show' map.connect '/search/:q', :controller => "search", :action => 'show' map.search '/search', :controller => "search", :action => 'index' map.connect '/constituencies/hide_members', :conditions => { :method => :post }, :controller => "constituencies", :action => 'hide_members' map.connect '/constituencies/unhide_members', :conditions => { :method => :post }, :controller => "constituencies", :action => 'unhide_members' map.admin '/admin', :controller => 'admin', :action => 'index' map.connect '/admin/sent', :controller => 'admin', :action => 'sent' map.connect '/admin/sent/:yyyy_mm', :controller => 'admin', :action => 'sent_by_month' map.connect '/admin/waiting_to_be_sent', :controller => 'admin', :action => 'waiting_to_be_sent' map.connect '/admin/stats', :controller => 'admin', :action => 'stats' map.shutdown '/admin/shutdown', :controller => 'admin', :action => 'shutdown' map.mailserver_status '/admin/mailserver_status', :controller => 'admin', :action => 'mailserver_status' map.blacklisted_postcodes '/admin/blacklist', :controller => 'blacklisted_postcodes', :action => 'index' map.connect '/admin/blacklist/restore/:code', :controller => 'blacklisted_postcodes', :action => 'restore' map.connect '/admin/blacklist/new', :controller => 'blacklisted_postcodes', :action => 'new' map.manual_postcodes '/admin/manual_postcodes', :controller => 'manual_postcodes', :action => 'index' map.connect '/admin/manual_postcodes/remove/:code', :controller => 'manual_postcodes', :action => 'remove' map.connect '/admin/manual_postcodes/new', :controller => 'manual_postcodes', :action => 'new' map.api '/api', :controller => 'api', :action => 'index' map.connect 'api/search', :controller => 'api', :action => 'search' map.connect 'api/postcodes', :controller => 'api', :action => 'postcodes' map.connect 'api/constituencies', :controller => 'api', :action => 'constituencies' map.connect '/commons/constituency/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/member/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/postcode/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/constituency/cons/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/member/cons/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/email/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/l/', :controller => 'postcodes', :action => 'redir' map.connect '/commons/', :controller => 'postcodes', :action => 'redir' map.connect '*bad_route', :controller => 'application', :action => 'render_not_found' end
robertbrook/findyourmp
19cea3a3eb23d336238953e15057037df127ce40
fixed failing specs
diff --git a/app/models/constituency.rb b/app/models/constituency.rb index 23b37ed..68cd8be 100755 --- a/app/models/constituency.rb +++ b/app/models/constituency.rb @@ -1,213 +1,213 @@ class Constituency < ActiveRecord::Base include ActionController::UrlWriter has_friendly_id :name, :use_slug => true, :strip_diacritics => true has_many :postcodes has_many :postcode_districts has_many :messages validate :valid_email? class << self def all_constituencies all.select{|c| c.name != 'Example'} end def remove_quotes text unless text text = "" end text.strip[/^"?([^"]+)"?$/,1] end def load_tsv_line line parts = line.split("\t") constituency_name = remove_quotes(parts[0]) member_name = remove_quotes(parts[1]) member_party = remove_quotes(parts[2]) member_bio_url = remove_quotes(parts[3]) member_contact = remove_quotes(parts[4]) member_website = remove_quotes(parts[5]) member_contact = "" unless member_contact existing = Constituency.find_by_constituency_name(constituency_name) new_constituency = nil if existing non_matching = (existing.member_name != member_name || existing.member_party != member_party || existing.member_biography_url != member_bio_url) non_matching = non_matching || ( member_contact[/http:\/\//] ? (existing.member_requested_contact_url.to_s.strip != member_contact.to_s.strip) : (existing.member_email.to_s.strip != member_contact.to_s.strip) ) if non_matching new_constituency = Constituency.new(existing.attributes) new_constituency.member_name = member_name new_constituency.member_party = member_party new_constituency.member_biography_url = member_bio_url if member_contact[/http:\/\//] new_constituency.member_requested_contact_url = member_contact else new_constituency.member_email = member_contact.chomp('.') end new_constituency.member_website = member_website end [existing, new_constituency] else [nil, nil] end end def find_all_constituency_and_member_matches term term = term.squeeze(' ').gsub('"','') constituencies = Constituency.find_all_name_or_member_name_matches(term) members = constituencies.clone if term[/[A-Z][a-z].*/] constituencies = constituencies.select { |c| c.name.include? term } members = members.select { |c| c.member_name.include? term } else constituencies = constituencies.select { |c| c.name.downcase.include? term.downcase } members = members.select { |c| c.member_name? && c.member_name.downcase.include?(term.downcase) } end constituencies = constituencies.sort_by(&:name) members = members.sort_by(&:member_name) return [constituencies, members] end def find_all_name_or_member_name_matches term term = term.squeeze(' ').gsub('"','') matches_name_or_member_name = %Q|name like "%#{term}%" or | + %Q|(member_name like "%#{term}%" and member_visible = 1)| constituencies = find(:all, :conditions => matches_name_or_member_name) constituencies.delete_if{|c| c.name == 'Example'} if case_sensitive(term) constituencies.delete_if do |c| !c.name.include?(term) && !c.member_name.include?(term) end end constituencies end def case_sensitive term term.gsub('"','')[/^([A-Z][a-z]+[ ]+)*([A-Z][a-z]+)$/] ? true : false end def find_by_constituency_name name name.gsub!(' - ','-') if name[/^(.+), City of$/] name = "City of #{$1}" end constituency = find_by_name(name) unless constituency name.gsub!('&', 'and') if name == "Regent's Park and Kensington North" name = "Regent's Park and North Kensington" end if name[/^(.+), The$/] name = "The #{$1}" end name.tr!('-', ' ') name.gsub!('ô','o') name.gsub!('and#244;', 'o') constituency = find_by_name(name) - - unless constituency - name.gsub!('St ', 'St. ') - constituency = find_by_name(name) - end + end + + unless constituency + name.gsub!('St ', 'St. ') + constituency = find_by_name(name) end unless constituency puts "" puts "not found: #{name}" end constituency end end def show_message_form? member_name? && member_email? && !member_requested_contact_url? end def code if ons_id.nil? '' elsif ons_id.length == 1 "00#{ons_id}" elsif ons_id.length == 2 "0#{ons_id}" else ons_id.to_s end end def no_sitting_member? (!member_name?) || (!member_visible) end def to_tsv_line %Q|"#{name}"\t"#{member_name}"\t"#{member_party}"\t"#{member_biography_url}"\t"#{member_email}"\t"#{member_website}"| end def to_json host, port if no_sitting_member? %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "No sitting member", "member_party": "", "member_biography_url": "", "member_website": "", "uri": "#{object_url(host, port, "json")}" } }| else %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "#{member_name}", "member_party": "#{member_party}", "member_biography_url": "#{member_biography_url}", "member_website": "#{member_website}", "uri": "#{object_url(host, port, "json")}" } }| end end def to_text host, port, format="txt" if no_sitting_member? %Q|constituency_name: #{name}\nmember_name: No sitting member\nmember_party: \nmember_biography_url: \nmember_website: \nuri: #{object_url(host, port, format)}| else %Q|constituency_name: #{name}\nmember_name: #{member_name}\nmember_party: #{member_party}\nmember_biography_url: #{member_biography_url}\nmember_website: #{member_website}\nuri: #{object_url(host, port, format)}| end end def to_csv host, port headers = 'constituency_name,member_name,member_party,member_biography_url,member_website,uri' values = to_csv_value(host, port) "#{headers}\n#{values}\n" end def to_csv_value host, port if no_sitting_member? %Q|"#{name}","No sitting member","","","","#{object_url(host, port, format, "csv")}"| else %Q|"#{name}","#{member_name}","#{member_party}","#{member_biography_url}","#{member_website}","#{object_url(host, port, "csv")}"| end end def to_output_yaml host, port "---\n#{to_text(host, port, "yaml")}" end def member_attribute_changed? attribute, constituency send(attribute).to_s.strip != constituency.send(attribute).to_s.strip end private def valid_email? unless member_email.blank? begin self.member_email = MessageMailer.parse_email(member_email).address rescue errors.add_to_base("Member email must be a valid email") end end end def object_url host, port, format=nil if port.to_s == "80" url_for :host=> host, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false else url_for :host=> host, :port=> port, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false end end end diff --git a/spec/models/constituency_spec.rb b/spec/models/constituency_spec.rb index 88e34fd..d60ab66 100644 --- a/spec/models/constituency_spec.rb +++ b/spec/models/constituency_spec.rb @@ -1,369 +1,368 @@ require File.dirname(__FILE__) + '/../spec_helper' describe Constituency do assert_model_has_many :postcodes assert_model_has_many :messages before do @constituency = Constituency.new @constituency2 = Constituency.new end describe 'when asked for find_all_constituency_and_member_matches' do before do @constituency.name = 'Bethnal Green and Bow' @constituency2.name = 'Aldershot Bow' @constituency.member_name = '' @constituency2.member_name = '' end it 'should sort constituencies by name' do constituencies = [@constituency,@constituency2] Constituency.should_receive(:find_all_name_or_member_name_matches).with('Bow').and_return constituencies constituencies, members = Constituency.find_all_constituency_and_member_matches('Bow') constituencies.should == [@constituency2, @constituency] end it 'should match case of constituency name' do @constituency2.name = 'Aldershotbow' constituencies = [@constituency,@constituency2] Constituency.should_receive(:find_all_name_or_member_name_matches).with('Bow').and_return constituencies constituencies, members = Constituency.find_all_constituency_and_member_matches('Bow') constituencies.should == [@constituency] end it 'should ignore case of search term if not capitalized' do @constituency2.name = 'Aldershotbow' constituencies = [@constituency,@constituency2] Constituency.should_receive(:find_all_name_or_member_name_matches).with('bow').and_return constituencies constituencies, members = Constituency.find_all_constituency_and_member_matches('bow') constituencies.should == [@constituency2,@constituency] end it 'should match case of member name if capitalized' do @constituency.member_name = 'Ian' @constituency2.member_name = 'Sian' constituencies = [@constituency,@constituency2] Constituency.should_receive(:find_all_name_or_member_name_matches).with('Ian').and_return constituencies constituencies, members = Constituency.find_all_constituency_and_member_matches('Ian') members.should == [@constituency] end it 'should not match a hidden member name' do @constituency.member_name = 'Ian' @constituency2.member_name = 'Sian' @constituency.member_visible = false Constituency.should_receive(:find_all_name_or_member_name_matches).with('ian').and_return [@constituency2] constituencies, members = Constituency.find_all_constituency_and_member_matches('ian') members.should == [@constituency2] end end describe 'when asked if member name has changed' do it 'should return true if it has' do @constituency.member_name = 'old' @constituency2.member_name = 'new' @constituency.member_attribute_changed?(:member_name, @constituency2).should be_true end it 'should return false if it hasn\'t' do @constituency.member_name = 'old' @constituency2.member_name = 'old' @constituency.member_attribute_changed?(:member_name, @constituency2).should be_false end end describe 'when asked if member party has changed' do it 'should return true if it has' do @constituency.member_party = 'old' @constituency2.member_party = 'new' @constituency.member_attribute_changed?(:member_party, @constituency2).should be_true end it 'should return false if it hasn\'t' do @constituency.member_party = 'old' @constituency2.member_party = 'old' @constituency.member_attribute_changed?(:member_party, @constituency2).should be_false end end describe 'when asked for find_all_name_or_member_name_matches' do def should_find_all term cleaned_term = term.squeeze(' ').gsub('"','') conditions = %Q|name like "%#{cleaned_term}%" or (member_name like "%#{cleaned_term}%" and member_visible = 1)| @name_match_lc = mock(Constituency, :name => 'Lanark and Hamilton East', :member_name=>'member') @member_match_lc = mock(Constituency, :member_name => 'Ms Emily Thornberry', :name=>'place') @name_match = mock(Constituency, :name => 'Milton Keynes South West', :member_name=>'another member') @member_match = mock(Constituency, :member_name => 'Anne Milton', :name=>'another place') @all_matches = [@name_match_lc, @member_match_lc, @name_match, @member_match] Constituency.should_receive(:find).with(:all, :conditions => conditions).and_return @all_matches end describe 'and search term is lowercase, e.g. "mil"' do it 'should return all matches ignoring case' do term = 'mil' Constituency.case_sensitive(term).should be_false should_find_all term Constituency.find_all_name_or_member_name_matches(term).should == @all_matches end end describe 'and search term is capitalized, e.g. Mil' do it 'should return all matches, case-sensitive' do term = 'Mil' Constituency.case_sensitive(term).should be_true should_find_all term Constituency.find_all_name_or_member_name_matches(term).should == [@name_match, @member_match] end end describe 'and search term is in brackets, e.g. "Mil"' do it 'should return all matches, case-sensitive' do term = '"Mil"' Constituency.case_sensitive(term).should be_true should_find_all term Constituency.find_all_name_or_member_name_matches(term).should == [@name_match, @member_match] end end describe 'and search term is mixedcase, e.g. "MiL"' do it 'should return all matches ignoring case' do term = 'MiL' Constituency.case_sensitive(term).should be_false should_find_all term Constituency.find_all_name_or_member_name_matches(term).should == @all_matches end end end describe 'when asked for find_by_constituency_name' do before do @match_name = mock(Constituency, :name => 'Aberdeen South', :member_name => 'Miss Anne Begg') @match_st = mock(Constituency, :name => 'St. Ives') @match_city = mock(Constituency, :name => 'City of York') @match_north = mock(Constituency, :name => "Regent's Park and North Kensington") @match_the = mock(Constituency, :name => "The Wrekin") end describe 'and search term is valid' do it 'should return a valid constituency' do term = 'Aberdeen South' Constituency.should_receive(:find_by_name).with(term).and_return @match_name Constituency.find_by_constituency_name(term).should == @match_name end end describe 'and search term is St Ives' do - it 'should search for St. Ives' do - term = 'St Ives' - expected = 'St. Ives' - Constituency.should_receive(:find_by_name).with(expected).and_return @match_st - Constituency.find_by_constituency_name(term).name.should == expected + it 'should search for St. Ives if St Ives produces no results' do + Constituency.should_receive(:find_by_name).with("St Ives").exactly(2).times.and_return nil + Constituency.should_receive(:find_by_name).with("St. Ives").and_return @match_st + Constituency.find_by_constituency_name("St Ives").should == @match_st end end describe 'and search term is York, City of' do it 'should return City of York' do term = 'York, City of' expected = 'City of York' Constituency.should_receive(:find_by_name).with(expected).and_return @match_city Constituency.find_by_constituency_name(term).name.should == expected end end describe "and search term is Regent's Park & Kensington North" do it "should return Regent's Park and North Kensington" do term = "Regent's Park & Kensington North" expected = "Regent's Park and North Kensington" Constituency.should_receive(:find_by_name).with(term).and_return nil Constituency.should_receive(:find_by_name).with(expected).and_return @match_north Constituency.find_by_constituency_name(term).name.should == expected end end describe "and search term is Wrekin, The" do it "should return The Wrekin" do term = "Wrekin, The" expected = "The Wrekin" Constituency.should_receive(:find_by_name).with(term).and_return nil Constituency.should_receive(:find_by_name).with(expected).and_return @match_the Constituency.find_by_constituency_name(term).name.should == expected end end end describe 'when asked to load tsv line' do def tsv_line email %Q|"Islington West"\t"Duncan McCloud"\t"Plaid Cymru"\t"http://biographies.parliament.uk/parliament/default.asp?id=25505"\t"#{email}"\t"http://www.m.co.uk/"| end def check_update_constituency contact, contact_type Constituency.should_receive(:find_by_constituency_name).with('Islington West').and_return @constituency @new_constituency = Constituency.new Constituency.should_receive(:new).with(@constituency.attributes).and_return @new_constituency @new_constituency.should_receive(:member_name=).with('Duncan McCloud') @new_constituency.should_receive(:member_party=).with('Plaid Cymru') @new_constituency.should_receive(:member_biography_url=).with('http://biographies.parliament.uk/parliament/default.asp?id=25505') @new_constituency.should_receive(:member_website=).with('http://www.m.co.uk/') @new_constituency.should_receive(contact_type).with(contact.chomp('.')) line = tsv_line(contact) loaded = Constituency.load_tsv_line(line) loaded.should == [@constituency, @new_constituency] loaded[1] end describe 'and constituency exists and tsv line contains broken email/contact url' do it 'should update constituency' do new_constituency = check_update_constituency 'broken.contact.details', :member_email= end end describe 'and constituency exists and tsv line contains email' do it 'should update constituency' do check_update_constituency 'example@email.address.', :member_email= end end describe 'and constituency exists and tsv line contains contact url' do it 'should update constituency' do check_update_constituency 'http://example.contactform.com', :member_requested_contact_url= end it 'should update constituency when contact url ends in html file' do check_update_constituency 'http://www.armp.org.uk/contact.html', :member_requested_contact_url= end end describe 'and constituency doesn\'t already exist' do it 'should create new constituency?' do Constituency.load_tsv_line tsv_line('example@email.address') end end end describe 'when asked for formatted version' do before do @constituency.stub!(:no_sitting_member?).and_return false @constituency.stub!(:friendly_id).and_return "islington-west" @constituency.name = "Islington West" @constituency.id = 999 @constituency.ons_id = 999 @constituency.member_name = "Duncan McCloud" @constituency.member_email = "duncan@mccloud.clan" @constituency.member_party = "Plaid Cymru" @constituency.member_biography_url = "http://biographies.parliament.uk/parliament/default.asp?id=25476" @constituency.member_website = "http://mccloud.uk" end describe 'as tab separated value line' do it 'should return tsv line' do @constituency.to_tsv_line.should == %Q|"Islington West"\t"Duncan McCloud"\t"Plaid Cymru"\t"http://biographies.parliament.uk/parliament/default.asp?id=25476"\t"duncan@mccloud.clan"\t"http://mccloud.uk"| end end describe 'in json' do it 'should create json correctly' do @constituency.to_json('localhost', '3000').should == %Q|{"constituency": {"constituency_name": "Islington West", "member_name": "Duncan McCloud", "member_party": "Plaid Cymru", "member_biography_url": "http://biographies.parliament.uk/parliament/default.asp?id=25476", "member_website": "http://mccloud.uk", "uri": "http://localhost:3000/constituencies/islington-west.json" } }| end end describe 'in text' do it 'should create text correctly' do @constituency.to_text('localhost', '3000').should == %Q|constituency_name: Islington West\nmember_name: Duncan McCloud\nmember_party: Plaid Cymru\nmember_biography_url: http://biographies.parliament.uk/parliament/default.asp?id=25476\nmember_website: http://mccloud.uk\nuri: http://localhost:3000/constituencies/islington-west.txt| end end describe 'in csv' do it 'should create csv correctly' do @constituency.to_csv('localhost', '3000').should == %Q|constituency_name,member_name,member_party,member_biography_url,member_website,uri\n"Islington West","Duncan McCloud","Plaid Cymru","http://biographies.parliament.uk/parliament/default.asp?id=25476","http://mccloud.uk","http://localhost:3000/constituencies/islington-west.csv"\n| end end describe 'in yaml' do it 'should create yaml correctly' do @constituency.to_output_yaml('localhost', '3000').should == %Q|---\nconstituency_name: Islington West\nmember_name: Duncan McCloud\nmember_party: Plaid Cymru\nmember_biography_url: http://biographies.parliament.uk/parliament/default.asp?id=25476\nmember_website: http://mccloud.uk\nuri: http://localhost:3000/constituencies/islington-west.yaml| end end end describe 'with invalid member_email' do it 'should not be valid' do @constituency.member_email = 'bad_email' @constituency.valid?.should be_false end end describe 'with valid member_email' do before do @constituency.member_email = 'ds@example.u.p.co.uk' end it 'should be valid' do @constituency.valid?.should be_true end describe 'and with member_name' do before do @constituency.member_name = 'name' end it 'should have show_message_form? return true' do @constituency.show_message_form?.should be_true end describe 'and with member requested contact url' do before do @constituency.member_requested_contact_url = 'http://here.co.uk/' end it 'should have show_message_form? return false' do @constituency.show_message_form?.should be_false end end end describe 'and without member_name' do it 'should have show_message_form? return true' do @constituency.show_message_form?.should be_false end end end describe 'with member' do before do @member_name = 'Tiberius Kirk' @constituency.member_name = @member_name @constituency.member_visible = true end describe 'when asked for member name' do it 'should return member\'s name' do @constituency.member_name.should == @member_name end it 'should have no_sitting_member? return false' do @constituency.no_sitting_member?.should be_false end end end describe 'vacant' do describe 'when asked for member name' do it 'should return nil' do @constituency.member_name.should be_nil end it 'should have no_sitting_member? return true' do @constituency.no_sitting_member?.should be_true end end end describe 'id is 1' do - before do; @constituency.stub!(:ons_id).and_return 1; end + before do; @constituency.stub!(:ons_id).and_return "1"; end describe 'when asked for code' do it 'should return 001' do @constituency.code.should == '001' end end end describe 'id is 10' do - before do; @constituency.stub!(:ons_id).and_return 10; end + before do; @constituency.stub!(:ons_id).and_return "10"; end describe 'when asked for code' do it 'should return 010' do @constituency.code.should == '010' end end end describe 'id is 100' do - before do; @constituency.stub!(:ons_id).and_return 100; end + before do; @constituency.stub!(:ons_id).and_return "100"; end describe 'when asked for code' do it 'should return 100' do @constituency.code.should == '100' end end end end
robertbrook/findyourmp
337552a1f1e46708c3a72afa1ae1cee3fa9908e5
fixed shared example problem that stopped specs from running
diff --git a/spec/controllers/application_controller_spec.rb b/spec/controllers/application_controller_spec.rb index 31728f2..d64c2d1 100644 --- a/spec/controllers/application_controller_spec.rb +++ b/spec/controllers/application_controller_spec.rb @@ -1,51 +1,51 @@ require File.dirname(__FILE__) + '/../spec_helper' describe ApplicationController do - describe 'returns in correct format', :shared => true do + shared_examples_for "returns in correct format" do it 'should return xml when passed format=xml' do do_get 'xml' response.content_type.should == "application/xml" end it 'should return json when passed format=json' do do_get 'json' response.content_type.should == "application/json" end it 'should return text when passed format=text' do do_get 'text' response.content_type.should == "text/plain" end it 'should return csv when passed format=csv' do do_get 'csv' response.content_type.should =='text/csv' end it 'should return yaml when passed format=yaml' do do_get 'yaml' response.content_type.should =='application/x-yaml' end end describe "when finding route for action" do it 'should display page not found for unknown routes' do params_from(:get, "/bad_url").should == {:controller => "application", :action => "render_not_found", :bad_route=>['bad_url']} end end describe 'converting date to month year string' do it 'should render correctly' do Date.new(2009,2,14).to_s(:month_year).should == 'February 2009' end end describe 'converting time to month year string' do it 'should render correctly' do Date.new(2009,2,14).to_time.to_s(:month_year).should == 'February 2009' end end end
robertbrook/findyourmp
34455ccd49d42502891f24070b22c18eaeb5ee35
footer text added
diff --git a/app/views/layouts/_search_hints.haml b/app/views/layouts/_search_hints.haml index 967e172..9bad49a 100644 --- a/app/views/layouts/_search_hints.haml +++ b/app/views/layouts/_search_hints.haml @@ -1 +1,3 @@ -%p.text This service will recognise postcodes and names of MPs or constituencies, or fragments of these. If you are unsure of the name of your MP or constituency it may be easier to try searching by postcode. \ No newline at end of file +%p.text This service will recognise postcodes and names of MPs or constituencies, or fragments of these. If you are unsure of the name of your MP or constituency it may be easier to try searching by postcode. + +%p.text If you have any queries about the Find Your MP service, please call the House of Commons Information Office on 020 7219 4272. \ No newline at end of file
robertbrook/findyourmp
d80de1b9d8b10b30f3cd6e6eeee560e50e3afdb8
removed telephone and email info/link from html view; changed "Letter" to "Address"
diff --git a/app/views/constituencies/_member.haml b/app/views/constituencies/_member.haml index 57e7cee..1a85608 100644 --- a/app/views/constituencies/_member.haml +++ b/app/views/constituencies/_member.haml @@ -1,37 +1,23 @@ .text - if @constituency.no_sitting_member? %p There is no sitting Member of Parliament for this constituency. - else - member_name = h(@constituency.member_name) .row_item .row_label Member for this constituency .row_value - if @constituency.member_biography_url? = link_to member_name, @constituency.member_biography_url - else = member_name .row_item .row_label Party .row_value= h(@constituency.member_party) - if @constituency.member_website? .row_item .row_label Website .row_value = link_to h(@constituency.member_website.sub('http://','').chomp('/')), @constituency.member_website .row_item - .row_label= @constituency.member_requested_contact_url? ? "Contact" : "Email" - .row_value - - if @constituency.member_requested_contact_url? - = link_to "Contact #{member_name}", @constituency.member_requested_contact_url - - elsif @constituency.member_email? - = %Q|#{link_to("Email #{member_name}", new_constituency_message_url(@constituency) )}| - - else - = "#{member_name} cannot be contacted by email" - %br - from this website. - .row_item - .row_label Telephone - .row_value= "House of Commons Switchboard: 020 7219 3000. Please ask for the office of #{member_name}." - .row_item - .row_label Letter + .row_label Address .row_value= "#{member_name}, House of Commons, London SW1A 0AA"
robertbrook/findyourmp
035f3b8d2c86ac97410d06bd5890d279026cd8a2
fixed bug where constituency containing St was not found by bulk update
diff --git a/app/models/constituency.rb b/app/models/constituency.rb index a2eb45c..23b37ed 100755 --- a/app/models/constituency.rb +++ b/app/models/constituency.rb @@ -1,209 +1,213 @@ class Constituency < ActiveRecord::Base include ActionController::UrlWriter has_friendly_id :name, :use_slug => true, :strip_diacritics => true has_many :postcodes has_many :postcode_districts has_many :messages validate :valid_email? class << self def all_constituencies all.select{|c| c.name != 'Example'} end def remove_quotes text unless text text = "" end text.strip[/^"?([^"]+)"?$/,1] end def load_tsv_line line parts = line.split("\t") constituency_name = remove_quotes(parts[0]) member_name = remove_quotes(parts[1]) member_party = remove_quotes(parts[2]) member_bio_url = remove_quotes(parts[3]) member_contact = remove_quotes(parts[4]) member_website = remove_quotes(parts[5]) member_contact = "" unless member_contact existing = Constituency.find_by_constituency_name(constituency_name) new_constituency = nil if existing non_matching = (existing.member_name != member_name || existing.member_party != member_party || existing.member_biography_url != member_bio_url) non_matching = non_matching || ( member_contact[/http:\/\//] ? (existing.member_requested_contact_url.to_s.strip != member_contact.to_s.strip) : (existing.member_email.to_s.strip != member_contact.to_s.strip) ) if non_matching new_constituency = Constituency.new(existing.attributes) new_constituency.member_name = member_name new_constituency.member_party = member_party new_constituency.member_biography_url = member_bio_url if member_contact[/http:\/\//] new_constituency.member_requested_contact_url = member_contact else new_constituency.member_email = member_contact.chomp('.') end new_constituency.member_website = member_website end [existing, new_constituency] else [nil, nil] end end def find_all_constituency_and_member_matches term term = term.squeeze(' ').gsub('"','') constituencies = Constituency.find_all_name_or_member_name_matches(term) members = constituencies.clone if term[/[A-Z][a-z].*/] constituencies = constituencies.select { |c| c.name.include? term } members = members.select { |c| c.member_name.include? term } else constituencies = constituencies.select { |c| c.name.downcase.include? term.downcase } members = members.select { |c| c.member_name? && c.member_name.downcase.include?(term.downcase) } end constituencies = constituencies.sort_by(&:name) members = members.sort_by(&:member_name) return [constituencies, members] end def find_all_name_or_member_name_matches term term = term.squeeze(' ').gsub('"','') matches_name_or_member_name = %Q|name like "%#{term}%" or | + %Q|(member_name like "%#{term}%" and member_visible = 1)| constituencies = find(:all, :conditions => matches_name_or_member_name) constituencies.delete_if{|c| c.name == 'Example'} if case_sensitive(term) constituencies.delete_if do |c| !c.name.include?(term) && !c.member_name.include?(term) end end constituencies end def case_sensitive term term.gsub('"','')[/^([A-Z][a-z]+[ ]+)*([A-Z][a-z]+)$/] ? true : false end def find_by_constituency_name name - name.gsub!('St ', 'St. ') name.gsub!(' - ','-') if name[/^(.+), City of$/] name = "City of #{$1}" end constituency = find_by_name(name) unless constituency name.gsub!('&', 'and') if name == "Regent's Park and Kensington North" name = "Regent's Park and North Kensington" end if name[/^(.+), The$/] name = "The #{$1}" end name.tr!('-', ' ') name.gsub!('ô','o') name.gsub!('and#244;', 'o') constituency = find_by_name(name) + + unless constituency + name.gsub!('St ', 'St. ') + constituency = find_by_name(name) + end end unless constituency puts "" puts "not found: #{name}" end constituency end end def show_message_form? member_name? && member_email? && !member_requested_contact_url? end def code if ons_id.nil? '' elsif ons_id.length == 1 "00#{ons_id}" elsif ons_id.length == 2 "0#{ons_id}" else ons_id.to_s end end def no_sitting_member? (!member_name?) || (!member_visible) end def to_tsv_line %Q|"#{name}"\t"#{member_name}"\t"#{member_party}"\t"#{member_biography_url}"\t"#{member_email}"\t"#{member_website}"| end def to_json host, port if no_sitting_member? %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "No sitting member", "member_party": "", "member_biography_url": "", "member_website": "", "uri": "#{object_url(host, port, "json")}" } }| else %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "#{member_name}", "member_party": "#{member_party}", "member_biography_url": "#{member_biography_url}", "member_website": "#{member_website}", "uri": "#{object_url(host, port, "json")}" } }| end end def to_text host, port, format="txt" if no_sitting_member? %Q|constituency_name: #{name}\nmember_name: No sitting member\nmember_party: \nmember_biography_url: \nmember_website: \nuri: #{object_url(host, port, format)}| else %Q|constituency_name: #{name}\nmember_name: #{member_name}\nmember_party: #{member_party}\nmember_biography_url: #{member_biography_url}\nmember_website: #{member_website}\nuri: #{object_url(host, port, format)}| end end def to_csv host, port headers = 'constituency_name,member_name,member_party,member_biography_url,member_website,uri' values = to_csv_value(host, port) "#{headers}\n#{values}\n" end def to_csv_value host, port if no_sitting_member? %Q|"#{name}","No sitting member","","","","#{object_url(host, port, format, "csv")}"| else %Q|"#{name}","#{member_name}","#{member_party}","#{member_biography_url}","#{member_website}","#{object_url(host, port, "csv")}"| end end def to_output_yaml host, port "---\n#{to_text(host, port, "yaml")}" end def member_attribute_changed? attribute, constituency send(attribute).to_s.strip != constituency.send(attribute).to_s.strip end private def valid_email? unless member_email.blank? begin self.member_email = MessageMailer.parse_email(member_email).address rescue errors.add_to_base("Member email must be a valid email") end end end def object_url host, port, format=nil if port.to_s == "80" url_for :host=> host, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false else url_for :host=> host, :port=> port, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false end end end
robertbrook/findyourmp
c7ab59b9bd43c06b4e5bf8643df2550c53a404a8
allow null fields to be read from a tsv
diff --git a/app/models/constituency.rb b/app/models/constituency.rb index b351b54..a2eb45c 100755 --- a/app/models/constituency.rb +++ b/app/models/constituency.rb @@ -1,206 +1,209 @@ class Constituency < ActiveRecord::Base include ActionController::UrlWriter has_friendly_id :name, :use_slug => true, :strip_diacritics => true has_many :postcodes has_many :postcode_districts has_many :messages validate :valid_email? class << self def all_constituencies all.select{|c| c.name != 'Example'} end def remove_quotes text + unless text + text = "" + end text.strip[/^"?([^"]+)"?$/,1] end def load_tsv_line line parts = line.split("\t") constituency_name = remove_quotes(parts[0]) member_name = remove_quotes(parts[1]) member_party = remove_quotes(parts[2]) member_bio_url = remove_quotes(parts[3]) member_contact = remove_quotes(parts[4]) member_website = remove_quotes(parts[5]) member_contact = "" unless member_contact existing = Constituency.find_by_constituency_name(constituency_name) new_constituency = nil if existing non_matching = (existing.member_name != member_name || existing.member_party != member_party || existing.member_biography_url != member_bio_url) non_matching = non_matching || ( member_contact[/http:\/\//] ? (existing.member_requested_contact_url.to_s.strip != member_contact.to_s.strip) : (existing.member_email.to_s.strip != member_contact.to_s.strip) ) if non_matching new_constituency = Constituency.new(existing.attributes) new_constituency.member_name = member_name new_constituency.member_party = member_party new_constituency.member_biography_url = member_bio_url if member_contact[/http:\/\//] new_constituency.member_requested_contact_url = member_contact else new_constituency.member_email = member_contact.chomp('.') end new_constituency.member_website = member_website end [existing, new_constituency] else [nil, nil] end end def find_all_constituency_and_member_matches term term = term.squeeze(' ').gsub('"','') constituencies = Constituency.find_all_name_or_member_name_matches(term) members = constituencies.clone if term[/[A-Z][a-z].*/] constituencies = constituencies.select { |c| c.name.include? term } members = members.select { |c| c.member_name.include? term } else constituencies = constituencies.select { |c| c.name.downcase.include? term.downcase } members = members.select { |c| c.member_name? && c.member_name.downcase.include?(term.downcase) } end constituencies = constituencies.sort_by(&:name) members = members.sort_by(&:member_name) return [constituencies, members] end def find_all_name_or_member_name_matches term term = term.squeeze(' ').gsub('"','') matches_name_or_member_name = %Q|name like "%#{term}%" or | + %Q|(member_name like "%#{term}%" and member_visible = 1)| constituencies = find(:all, :conditions => matches_name_or_member_name) constituencies.delete_if{|c| c.name == 'Example'} if case_sensitive(term) constituencies.delete_if do |c| !c.name.include?(term) && !c.member_name.include?(term) end end constituencies end def case_sensitive term term.gsub('"','')[/^([A-Z][a-z]+[ ]+)*([A-Z][a-z]+)$/] ? true : false end def find_by_constituency_name name name.gsub!('St ', 'St. ') name.gsub!(' - ','-') if name[/^(.+), City of$/] name = "City of #{$1}" end constituency = find_by_name(name) unless constituency name.gsub!('&', 'and') if name == "Regent's Park and Kensington North" name = "Regent's Park and North Kensington" end if name[/^(.+), The$/] name = "The #{$1}" end name.tr!('-', ' ') name.gsub!('ô','o') name.gsub!('and#244;', 'o') constituency = find_by_name(name) end unless constituency puts "" puts "not found: #{name}" end constituency end end def show_message_form? member_name? && member_email? && !member_requested_contact_url? end def code if ons_id.nil? '' elsif ons_id.length == 1 "00#{ons_id}" elsif ons_id.length == 2 "0#{ons_id}" else ons_id.to_s end end def no_sitting_member? (!member_name?) || (!member_visible) end def to_tsv_line %Q|"#{name}"\t"#{member_name}"\t"#{member_party}"\t"#{member_biography_url}"\t"#{member_email}"\t"#{member_website}"| end def to_json host, port if no_sitting_member? %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "No sitting member", "member_party": "", "member_biography_url": "", "member_website": "", "uri": "#{object_url(host, port, "json")}" } }| else %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "#{member_name}", "member_party": "#{member_party}", "member_biography_url": "#{member_biography_url}", "member_website": "#{member_website}", "uri": "#{object_url(host, port, "json")}" } }| end end def to_text host, port, format="txt" if no_sitting_member? %Q|constituency_name: #{name}\nmember_name: No sitting member\nmember_party: \nmember_biography_url: \nmember_website: \nuri: #{object_url(host, port, format)}| else %Q|constituency_name: #{name}\nmember_name: #{member_name}\nmember_party: #{member_party}\nmember_biography_url: #{member_biography_url}\nmember_website: #{member_website}\nuri: #{object_url(host, port, format)}| end end def to_csv host, port headers = 'constituency_name,member_name,member_party,member_biography_url,member_website,uri' values = to_csv_value(host, port) "#{headers}\n#{values}\n" end def to_csv_value host, port if no_sitting_member? %Q|"#{name}","No sitting member","","","","#{object_url(host, port, format, "csv")}"| else %Q|"#{name}","#{member_name}","#{member_party}","#{member_biography_url}","#{member_website}","#{object_url(host, port, "csv")}"| end end def to_output_yaml host, port "---\n#{to_text(host, port, "yaml")}" end def member_attribute_changed? attribute, constituency send(attribute).to_s.strip != constituency.send(attribute).to_s.strip end private def valid_email? unless member_email.blank? begin self.member_email = MessageMailer.parse_email(member_email).address rescue errors.add_to_base("Member email must be a valid email") end end end def object_url host, port, format=nil if port.to_s == "80" url_for :host=> host, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false else url_for :host=> host, :port=> port, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false end end end
robertbrook/findyourmp
a740e38b754c4dc16710c91598f00e85ebc8e380
fixing constituency model bug that tried to treat ons_id as a numeric value
diff --git a/app/models/constituency.rb b/app/models/constituency.rb index 8ed63a8..b351b54 100755 --- a/app/models/constituency.rb +++ b/app/models/constituency.rb @@ -1,206 +1,206 @@ class Constituency < ActiveRecord::Base include ActionController::UrlWriter has_friendly_id :name, :use_slug => true, :strip_diacritics => true has_many :postcodes has_many :postcode_districts has_many :messages validate :valid_email? class << self def all_constituencies all.select{|c| c.name != 'Example'} end def remove_quotes text text.strip[/^"?([^"]+)"?$/,1] end def load_tsv_line line parts = line.split("\t") constituency_name = remove_quotes(parts[0]) member_name = remove_quotes(parts[1]) member_party = remove_quotes(parts[2]) member_bio_url = remove_quotes(parts[3]) member_contact = remove_quotes(parts[4]) member_website = remove_quotes(parts[5]) member_contact = "" unless member_contact existing = Constituency.find_by_constituency_name(constituency_name) new_constituency = nil if existing non_matching = (existing.member_name != member_name || existing.member_party != member_party || existing.member_biography_url != member_bio_url) non_matching = non_matching || ( member_contact[/http:\/\//] ? (existing.member_requested_contact_url.to_s.strip != member_contact.to_s.strip) : (existing.member_email.to_s.strip != member_contact.to_s.strip) ) if non_matching new_constituency = Constituency.new(existing.attributes) new_constituency.member_name = member_name new_constituency.member_party = member_party new_constituency.member_biography_url = member_bio_url if member_contact[/http:\/\//] new_constituency.member_requested_contact_url = member_contact else new_constituency.member_email = member_contact.chomp('.') end new_constituency.member_website = member_website end [existing, new_constituency] else [nil, nil] end end def find_all_constituency_and_member_matches term term = term.squeeze(' ').gsub('"','') constituencies = Constituency.find_all_name_or_member_name_matches(term) members = constituencies.clone if term[/[A-Z][a-z].*/] constituencies = constituencies.select { |c| c.name.include? term } members = members.select { |c| c.member_name.include? term } else constituencies = constituencies.select { |c| c.name.downcase.include? term.downcase } members = members.select { |c| c.member_name? && c.member_name.downcase.include?(term.downcase) } end constituencies = constituencies.sort_by(&:name) members = members.sort_by(&:member_name) return [constituencies, members] end def find_all_name_or_member_name_matches term term = term.squeeze(' ').gsub('"','') matches_name_or_member_name = %Q|name like "%#{term}%" or | + %Q|(member_name like "%#{term}%" and member_visible = 1)| constituencies = find(:all, :conditions => matches_name_or_member_name) constituencies.delete_if{|c| c.name == 'Example'} if case_sensitive(term) constituencies.delete_if do |c| !c.name.include?(term) && !c.member_name.include?(term) end end constituencies end def case_sensitive term term.gsub('"','')[/^([A-Z][a-z]+[ ]+)*([A-Z][a-z]+)$/] ? true : false end def find_by_constituency_name name name.gsub!('St ', 'St. ') name.gsub!(' - ','-') if name[/^(.+), City of$/] name = "City of #{$1}" end constituency = find_by_name(name) unless constituency name.gsub!('&', 'and') if name == "Regent's Park and Kensington North" name = "Regent's Park and North Kensington" end if name[/^(.+), The$/] name = "The #{$1}" end name.tr!('-', ' ') name.gsub!('ô','o') name.gsub!('and#244;', 'o') constituency = find_by_name(name) end unless constituency puts "" puts "not found: #{name}" end constituency end end def show_message_form? member_name? && member_email? && !member_requested_contact_url? end def code if ons_id.nil? '' - elsif ons_id < 10 + elsif ons_id.length == 1 "00#{ons_id}" - elsif ons_id < 100 + elsif ons_id.length == 2 "0#{ons_id}" else ons_id.to_s end end def no_sitting_member? (!member_name?) || (!member_visible) end def to_tsv_line %Q|"#{name}"\t"#{member_name}"\t"#{member_party}"\t"#{member_biography_url}"\t"#{member_email}"\t"#{member_website}"| end def to_json host, port if no_sitting_member? %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "No sitting member", "member_party": "", "member_biography_url": "", "member_website": "", "uri": "#{object_url(host, port, "json")}" } }| else %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "#{member_name}", "member_party": "#{member_party}", "member_biography_url": "#{member_biography_url}", "member_website": "#{member_website}", "uri": "#{object_url(host, port, "json")}" } }| end end def to_text host, port, format="txt" if no_sitting_member? %Q|constituency_name: #{name}\nmember_name: No sitting member\nmember_party: \nmember_biography_url: \nmember_website: \nuri: #{object_url(host, port, format)}| else %Q|constituency_name: #{name}\nmember_name: #{member_name}\nmember_party: #{member_party}\nmember_biography_url: #{member_biography_url}\nmember_website: #{member_website}\nuri: #{object_url(host, port, format)}| end end def to_csv host, port headers = 'constituency_name,member_name,member_party,member_biography_url,member_website,uri' values = to_csv_value(host, port) "#{headers}\n#{values}\n" end def to_csv_value host, port if no_sitting_member? %Q|"#{name}","No sitting member","","","","#{object_url(host, port, format, "csv")}"| else %Q|"#{name}","#{member_name}","#{member_party}","#{member_biography_url}","#{member_website}","#{object_url(host, port, "csv")}"| end end def to_output_yaml host, port "---\n#{to_text(host, port, "yaml")}" end def member_attribute_changed? attribute, constituency send(attribute).to_s.strip != constituency.send(attribute).to_s.strip end private def valid_email? unless member_email.blank? begin self.member_email = MessageMailer.parse_email(member_email).address rescue errors.add_to_base("Member email must be a valid email") end end end def object_url host, port, format=nil if port.to_s == "80" url_for :host=> host, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false else url_for :host=> host, :port=> port, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false end end end
robertbrook/findyourmp
1770da4f9e0e6b9360195fde99ca8d45a9bfc468
fixing for latest constituency file
diff --git a/lib/boundary_changes.rb b/lib/boundary_changes.rb index e845dcb..a77e35d 100644 --- a/lib/boundary_changes.rb +++ b/lib/boundary_changes.rb @@ -1,56 +1,57 @@ require File.expand_path(File.dirname(__FILE__) + '/timer') module FindYourMP; end module FindYourMP::BoundaryChanges include FindYourMP::Timer DATA_DIR = File.expand_path(File.dirname(__FILE__) + '/../data') - BOUNDARY_FILE = "#{DATA_DIR}/new_boundary_data.txt" + # RB hacked to point to local recent file + BOUNDARY_FILE = "#{DATA_DIR}/pcd_pcon_aug_2009_uk_lu.txt" def create_new_constituencies_file tab = "\t" new_constituencies = [] new_line = "\n" constituencies_file = "#{DATA_DIR}/new_constituencies.txt" start_timing if File.exist?(constituencies_file) cmd = "mv #{constituencies_file} #{constituencies_file}.#{Time.now.to_i.to_s}" puts cmd `#{cmd}` end constituencies = {} IO.foreach(BOUNDARY_FILE) do |line| ons_id = line[24..26] unless ons_id == ' ' unless constituencies.has_key?("#{ons_id}") if line.length > 27 constituency_name = line[27..line.length] unless constituency_name.strip == "" constituencies.merge!({"#{ons_id}" => "#{constituency_name.strip}"}) end end end end end keys = constituencies.keys.sort line = [] keys.each do |key| new_constituencies << key << tab << constituencies[key] << new_line end log_duration start_timing File.open(constituencies_file,'w') do |file| file.write(new_constituencies.join('')) end log_duration end end \ No newline at end of file diff --git a/lib/tasks/parse.rake b/lib/tasks/parse.rake index ce7ddc8..8e13042 100644 --- a/lib/tasks/parse.rake +++ b/lib/tasks/parse.rake @@ -1,87 +1,85 @@ require File.expand_path(File.dirname(__FILE__) + '/../data_loader') require File.expand_path(File.dirname(__FILE__) + '/../commons_member_biographies') require File.expand_path(File.dirname(__FILE__) + '/../cache_writer') require File.expand_path(File.dirname(__FILE__) + '/../constituency_upmystreet_links') require File.expand_path(File.dirname(__FILE__) + '/../boundary_changes') namespace :fymp do include FindYourMP::DataLoader include FindYourMP::CacheWriter include FindYourMP::BoundaryChanges desc "Create new_constituencies file for boundary changes" task :create_new_constituencies_file => :environment do create_new_constituencies_file end - - desc "Populate data for constituencies in DB" task :constituencies => :environment do load_constituencies end desc "Populate data for members in DB" task :members => :environment do file = ENV['file'] load_members file end desc "Create cache of all postcode pages" task :make_cache => :environment do make_cache end desc "Parse data file for postcode and constituency ID *only*" task :parse_postcodes do source_file = ENV['source'] if source_file parse_postcodes source_file else puts 'USAGE: rake fymp:parse source=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end desc "Update postcodes from data files for postcode and constituency ID *only*" task :diff_postcodes => :environment do old_file = ENV['old'] new_file = ENV['new'] if old_file && new_file diff_postcodes old_file, new_file else puts 'USAGE: rake fymp:diff_postcodes old=data/NSPDF_FEB_2009_UK_1M.txt new=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end desc "Only analyze potential postcode update and log db discrepancies" task :analyze_postcode_update => :environment do analyze_postcode_update end desc "Update postcodes from data files for postcode and constituency ID *only*" task :update_postcodes => :environment do puts 'USAGE: rake fymp:update_postcodes' update_postcodes end desc "Populate data for postcode and constituency ID in DB" task :populate => :environment do load_postcodes end desc "Populate the postcode districts table" task :load_postcode_districts => :environment do load_postcode_districts end desc "Populate the manually added postcodes" task :load_manual_postcodes => :environment do load_manual_postcodes end desc "Populate the upmystreet lookup table" task :load_upmystreet_lookup => :environment do load_upmystreetcodes end end diff --git a/vendor/plugins/xss_terminate b/vendor/plugins/xss_terminate new file mode 160000 index 0000000..724aba5 --- /dev/null +++ b/vendor/plugins/xss_terminate @@ -0,0 +1 @@ +Subproject commit 724aba589e2e753e7b0cfaf3196548f493b169da
robertbrook/findyourmp
f5e5e684e7ce9e3235f57bd6da83482f4411bc14
detangling rake tasks
diff --git a/lib/boundary_changes.rb b/lib/boundary_changes.rb index e845dcb..bc2cf82 100644 --- a/lib/boundary_changes.rb +++ b/lib/boundary_changes.rb @@ -1,56 +1,97 @@ require File.expand_path(File.dirname(__FILE__) + '/timer') module FindYourMP; end module FindYourMP::BoundaryChanges include FindYourMP::Timer DATA_DIR = File.expand_path(File.dirname(__FILE__) + '/../data') BOUNDARY_FILE = "#{DATA_DIR}/new_boundary_data.txt" def create_new_constituencies_file tab = "\t" new_constituencies = [] new_line = "\n" constituencies_file = "#{DATA_DIR}/new_constituencies.txt" start_timing if File.exist?(constituencies_file) cmd = "mv #{constituencies_file} #{constituencies_file}.#{Time.now.to_i.to_s}" puts cmd `#{cmd}` end constituencies = {} IO.foreach(BOUNDARY_FILE) do |line| ons_id = line[24..26] unless ons_id == ' ' unless constituencies.has_key?("#{ons_id}") if line.length > 27 constituency_name = line[27..line.length] unless constituency_name.strip == "" constituencies.merge!({"#{ons_id}" => "#{constituency_name.strip}"}) end end end end end keys = constituencies.keys.sort line = [] keys.each do |key| new_constituencies << key << tab << constituencies[key] << new_line end log_duration start_timing File.open(constituencies_file,'w') do |file| file.write(new_constituencies.join('')) end log_duration end + + + # used to compare a postcodes.txt file generated from the August '09 data + # with the pcd_pcon_aug_2009_uk_lu.txt file to create a new postcodes.txt + # file (in the example given, saved as new_postcodes.txt) + def parse_new_postcodes original_file, new_file, output_file=POSTCODE_FILE + return if file_not_found(original_file) + return if file_not_found(new_file) + start_timing + + blank_date = ' ' + blank_code = ' ' + new_line = "\n" + space = ' ' + post_codes = [] + + new_data = File.open(new_file) + + IO.foreach(original_file) do |line| + #ignore blank lines, Guernsey and Isle of Man postcodes + unless line == "" || line[8..10] == "800" || line[8..10] == "900" + orig_post_code = line[0..6] + post_code = "" + while (post_code != orig_post_code) + data = new_data.readline + post_code = data[0..6] + constituency_code = data[24..26] + end + + post_codes << post_code << space << constituency_code + post_codes << new_line + end + end + log_duration + + start_timing + File.open(output_file,'w') do |file| + file.write(post_codes.join('')) + end + log_duration + end end \ No newline at end of file diff --git a/lib/data_loader.rb b/lib/data_loader.rb index ece4767..66716e8 100644 --- a/lib/data_loader.rb +++ b/lib/data_loader.rb @@ -1,396 +1,356 @@ require File.expand_path(File.dirname(__FILE__) + '/timer') module FindYourMP; end module FindYourMP::DataLoader include FindYourMP::Timer DATA_DIR = File.expand_path(File.dirname(__FILE__) + '/../data') MEMBER_FILE = "#{DATA_DIR}/FYMP_all.txt" CONSTITUENCY_FILE = "#{DATA_DIR}/new_constituencies.txt" POSTCODE_FILE = "#{DATA_DIR}/postcodes.txt" def diff_postcodes old_file, new_file unless File.exist?(old_file) raise "#{old_file} not found" end unless File.exist?(new_file) raise "#{new_file} not found" end old_postcodes = "#{DATA_DIR}/old_postcodes.txt" new_postcodes = "#{DATA_DIR}/new_postcodes.txt" parse_postcodes old_file, old_postcodes parse_postcodes new_file, new_postcodes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if File.exist?(diff_file) cmd = "mv #{diff_file} #{diff_file}.#{Time.now.to_i.to_s}" puts cmd `#{cmd}` end cmd = "diff #{old_postcodes} #{new_postcodes} > #{diff_file}" puts cmd `#{cmd}` end def determine_postcode_changes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if file_not_found(diff_file) puts "Generate or upload #{diff_file}" return end to_delete = {} to_create = {} to_update = {} IO.foreach(diff_file) do |line| parts = line.strip.split(' ') indicator = parts[0] if indicator[/(<|>)/] ons_id = parts.pop postcode = parts.join(' ').sub(indicator, '').strip if indicator == '<' to_delete[postcode] = ons_id elsif indicator == '>' to_create[postcode] = ons_id end end end to_create.keys.each do |postcode| if to_delete.delete(postcode) ons_id = to_create.delete(postcode) to_update[postcode] = ons_id end end puts 'to_delete ' + to_delete.size.to_s + ' e.g. ' + to_delete.to_a.first.inspect puts 'to_update ' + to_update.size.to_s + ' e.g. ' + to_update.to_a.first.inspect puts 'to_create ' + to_create.size.to_s + ' e.g. ' + to_create.to_a.first.inspect puts 'checking we have constituencies... ' (to_delete.values + to_update.values + to_create.values).flatten.uniq.each do |ons_id| unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) raise "unexpected constituency id #{ons_id}" unless constituency end end puts 'all constituencies found' return [to_delete, to_update, to_create] end def update_postcodes to_delete, to_update, to_create = determine_postcode_changes # puts "Update database? y/n" # answer = STDIN.gets # if answer.strip == 'y' do_postcode_update to_delete, to_update, to_create # else # puts 'exiting without database update' # end end def ignore_ons_id?(ons_id) ons_id == '800' || ons_id == '900' end def analyze_postcode_update to_delete, to_update, to_create = determine_postcode_changes already_deleted = [] to_delete.each do |postcode, ons_id| already_deleted << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO DELETE, BUT ALREADY DELETED: #{already_deleted.size}" missing_updates = [] to_update.each do |postcode, ons_id| missing_updates << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO UPDATE, BUT MISSING FROM DB: #{missing_updates.size}" already_there = [] to_create.each do |postcode, ons_id| already_there << [postcode, ons_id] if Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO CREATE, BUT ALREADY IN DB: #{already_there.size}" end def do_postcode_update to_delete, to_update, to_create puts 'do_postcode_update...' total = (to_delete.size + to_update.size + to_create.size).to_f count = 0 include ActionView::Helpers::DateHelper start_timing to_delete.each do |postcode, ons_id| if post_code = Postcode.find_by_code(postcode.sub(' ','')) if ManualPostcode.find_by_code(postcode.sub(' ','')) puts " (ignoring manually added postcode - #{postcode})" else post_code.destroy count = count.next log_duration count / total end else warn "cannot delete postcode, as it was not in database: #{postcode}" end end to_update.each do |postcode, ons_id| post_code = Postcode.find_by_code(postcode.sub(' ','')) if post_code unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) if constituency.nil? raise "cannot update postcode, as constituency was not in database: #{postcode} #{ons_id}" end end if BlacklistedPostcode.find_by_code postcode.sub(' ','') puts " (deleting blacklisted postcode - #{postcode})" post_code.destroy else post_code.ons_id = ons_id.strip.to_i if constituency post_code.constituency_id = constituency.id else post_code.constituency_id = nil end post_code.save end count = count.next log_duration count / total else raise "cannot update postcode, as it was not in database: #{postcode} #{ons_id}" end end to_create.each do |postcode, ons_id| begin if Postcode.exists?(:code => postcode.sub(' ','')) warn 'exists ' + postcode elsif BlacklistedPostcode.find_by_code postcode.sub(' ','') puts " (ignoring blacklisted postcode - #{postcode})" else Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id.strip.to_i end rescue Exception => e raise e end count = count.next log_duration count / total end log_duration end def load_members member_file member_file = MEMBER_FILE unless member_file return if file_not_found(member_file) lines = [] IO.foreach(member_file) do |line| line.strip! lines << line unless(line.blank? || line[/Constituency/]) end lines.each do |line| begin parts = line.split("\t") constituency_name = parts[0].strip member_name = parts[1].strip if is_vacant?(member_name) log "Constituency is vacant: #{constituency_name}" else existing, updated_constituency = Constituency.load_tsv_line(line) if existing && updated_constituency existing.attributes = updated_constituency.attributes existing.save! elsif updated_constituency log "Cannot find constituency for member for line: #{line}" else # nothing to update end end rescue Exception => e log "Cannot set member_name on constituency for: #{line} | #{e.to_s}" end end end def load_constituencies return if file_not_found(CONSTITUENCY_FILE) Constituency.delete_all Slug.delete_all IO.foreach(CONSTITUENCY_FILE) do |line| constituency_id = line[0..2] constituency_name = line[3..(line.length-1)].strip Constituency.create :name=>constituency_name, :ons_id=>constituency_id end end def parse_postcodes source_file, output_file=POSTCODE_FILE return if file_not_found(source_file) start_timing blank_date = ' ' blank_code = ' ' new_line = "\n" space = ' ' post_codes = [] IO.foreach(source_file) do |line| termination_date = line[29..34] if termination_date == blank_date consistuency_code = line[69..71] unless consistuency_code == blank_code post_code = line[0..6] post_codes << post_code << space << consistuency_code post_codes << new_line end end end log_duration start_timing File.open(output_file,'w') do |file| file.write(post_codes.join('')) end log_duration end - # used to compare a postcodes.txt file generated from the August '09 data - # with the pcd_pcon_aug_2009_uk_lu.txt file to create a new postcodes.txt - # file (in the example given, saved as new_postcodes.txt) - def parse_new_postcodes original_file, new_file, output_file=POSTCODE_FILE - return if file_not_found(original_file) - return if file_not_found(new_file) - start_timing - - blank_date = ' ' - blank_code = ' ' - new_line = "\n" - space = ' ' - post_codes = [] - - new_data = File.open(new_file) - - IO.foreach(original_file) do |line| - #ignore blank lines, Guernsey and Isle of Man postcodes - unless line == "" || line[8..10] == "800" || line[8..10] == "900" - orig_post_code = line[0..6] - post_code = "" - while (post_code != orig_post_code) - data = new_data.readline - post_code = data[0..6] - constituency_code = data[24..26] - end - - post_codes << post_code << space << constituency_code - post_codes << new_line - end - end - log_duration - - start_timing - File.open(output_file,'w') do |file| - file.write(post_codes.join('')) - end - log_duration - end - def load_postcodes group_size=1000 return if file_not_found(POSTCODE_FILE) index = 0 groups = 0 puts 'saving data to db' Postcode.delete_all columns = [:code, :constituency_id] total = `cat #{POSTCODE_FILE} | wc -l` total = total.strip.to_f include ActionView::Helpers::DateHelper post_codes = [] start_timing IO.foreach(POSTCODE_FILE) do |line| code = line[0..6].tr(' ','') constituency_id = line[8..10] post_codes << [code, constituency_id] index = index.next if (index % group_size) == 0 load_codes(post_codes) groups = groups.next percentage_complete = (group_size * groups) / total log_duration percentage_complete post_codes = [] end end # complete remaining load_codes(post_codes) log_duration 1.0 end def load_postcode_districts PostcodeDistrict.delete_all sql = "SELECT SUBSTRING(code, 1, LENGTH(code)-3) " + "AS district, constituency_id " + "FROM postcodes " + "GROUP BY district, constituency_id;" districts = PostcodeDistrict.find_by_sql(sql) districts.each do |district| PostcodeDistrict.create!(district.attributes) end end def load_manual_postcodes manual_codes = ManualPostcode.all manual_codes.each do |manual_code| Postcode.create :code => manual_code.code, :constituency_id => manual_code.constituency_id, :ons_id => manual_code.ons_id end end private def load_codes(post_codes) post_codes.each do |codes| if BlacklistedPostcode.find_by_code codes[0] puts " (ignoring blacklisted postcode - #{codes[0]})" else Postcode.create :code => codes[0], :ons_id => codes[1] end end end def is_vacant?(name) name == 'Vacant' end def log msg $stderr.puts msg end def file_not_found file_name if File.exist?(file_name) false else log "Data file not found: #{file_name}" true end end end
robertbrook/findyourmp
09a32c547a96b13f85ab97b672d0ea795c0a5a07
data migration and rake tasks for 2010 constituency data
diff --git a/db/migrate/20100412150417_ons_id_to_string.rb b/db/migrate/20100412150417_ons_id_to_string.rb new file mode 100644 index 0000000..f4e1ec3 --- /dev/null +++ b/db/migrate/20100412150417_ons_id_to_string.rb @@ -0,0 +1,15 @@ +class OnsIdToString < ActiveRecord::Migration + def self.up + change_column :blacklisted_postcodes, :ons_id, :string, :limit => 3 + change_column :constituencies, :ons_id, :string, :limit => 3 + change_column :manual_postcodes, :ons_id, :string, :limit => 3 + change_column :postcodes, :ons_id, :string, :limit => 3 + end + + def self.down + change_column :blacklisted_postcodes, :ons_id, :integer + change_column :constituencies, :ons_id, :integer + change_column :manual_postcodes, :ons_id, :integer + change_column :postcodes, :ons_id, :string + end +end diff --git a/db/schema.rb b/db/schema.rb index 4a8de7f..979225c 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,146 +1,146 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090820151314) do +ActiveRecord::Schema.define(:version => 20100412150417) do create_table "blacklisted_postcodes", :force => true do |t| t.string "code", :limit => 7 t.integer "constituency_id" - t.integer "ons_id" + t.string "ons_id", :limit => 3 t.datetime "created_at" t.datetime "updated_at" end add_index "blacklisted_postcodes", ["code"], :name => "index_blacklisted_postcodes_on_code" create_table "constituencies", :force => true do |t| t.string "name" t.string "member_name" t.string "member_party" t.string "member_email" t.string "member_biography_url" t.boolean "member_visible" t.string "member_website" t.string "member_requested_contact_url" - t.integer "ons_id" + t.string "ons_id", :limit => 3 t.datetime "updated_at" end add_index "constituencies", ["ons_id"], :name => "index_constituencies_on_ons_id" create_table "emails", :force => true do |t| t.string "from" t.string "to" t.integer "last_send_attempt", :default => 0 t.text "mail" t.datetime "created_on" end create_table "manual_postcodes", :force => true do |t| t.string "code", :limit => 7 t.integer "constituency_id" - t.integer "ons_id" + t.string "ons_id", :limit => 3 t.datetime "created_at" t.datetime "updated_at" end add_index "manual_postcodes", ["code"], :name => "index_manual_postcodes_on_code" create_table "message_summaries", :force => true do |t| t.string "constituency_name" t.string "recipient" t.string "recipient_email" t.datetime "created_at" t.datetime "updated_at" t.date "sent_month" t.integer "count" end add_index "message_summaries", ["constituency_name"], :name => "index_message_summaries_on_constituency_name" add_index "message_summaries", ["recipient"], :name => "index_message_summaries_on_recipient" add_index "message_summaries", ["recipient_email"], :name => "index_message_summaries_on_recipient_email" add_index "message_summaries", ["sent_month"], :name => "index_message_summaries_on_sent_month" create_table "messages", :force => true do |t| t.string "constituency_id" t.string "sender_email" t.string "sender" t.string "recipient" t.string "address" t.string "postcode" t.string "subject" t.text "message" t.boolean "sent" t.datetime "created_at" t.datetime "updated_at" t.string "authenticity_token" t.string "recipient_email" t.boolean "sender_is_constituent" t.string "constituency_name" t.string "mailer_error" t.datetime "sent_at" t.string "sender_ip_address" end add_index "messages", ["sent"], :name => "index_messages_on_sent" add_index "messages", ["sent_at"], :name => "index_messages_on_sent_at" create_table "postcode_districts", :force => true do |t| t.string "district", :limit => 4 t.integer "constituency_id" end add_index "postcode_districts", ["district"], :name => "index_postcode_districts_on_district" create_table "postcodes", :force => true do |t| t.string "code", :limit => 7 t.integer "constituency_id" - t.integer "ons_id" + t.string "ons_id", :limit => 3 end add_index "postcodes", ["code"], :name => "index_postcodes_on_code" add_index "postcodes", ["constituency_id"], :name => "index_postcodes_on_constituency_id" add_index "postcodes", ["ons_id"], :name => "index_postcodes_on_ons_id" create_table "slugs", :force => true do |t| t.string "name" t.integer "sluggable_id" t.integer "sequence", :default => 1, :null => false t.string "sluggable_type", :limit => 40 t.string "scope", :limit => 40 t.datetime "created_at" end add_index "slugs", ["name", "sluggable_type", "scope", "sequence"], :name => "index_slugs_on_name_and_sluggable_type_and_scope_and_sequence", :unique => true add_index "slugs", ["sluggable_id"], :name => "index_slugs_on_sluggable_id" create_table "users", :force => true do |t| t.string "login" t.string "crypted_password" t.string "password_salt" t.string "persistence_token" t.integer "login_count" t.datetime "last_request_at" t.datetime "last_login_at" t.datetime "current_login_at" t.string "last_login_ip" t.string "current_login_ip" t.datetime "created_at" t.datetime "updated_at" t.string "perishable_token", :default => "", :null => false t.string "email", :default => "", :null => false t.boolean "admin", :default => false end add_index "users", ["email"], :name => "index_users_on_email" add_index "users", ["perishable_token"], :name => "index_users_on_perishable_token" end diff --git a/lib/data_loader.rb b/lib/data_loader.rb index f9bea11..ece4767 100644 --- a/lib/data_loader.rb +++ b/lib/data_loader.rb @@ -1,356 +1,396 @@ require File.expand_path(File.dirname(__FILE__) + '/timer') module FindYourMP; end module FindYourMP::DataLoader include FindYourMP::Timer DATA_DIR = File.expand_path(File.dirname(__FILE__) + '/../data') MEMBER_FILE = "#{DATA_DIR}/FYMP_all.txt" - CONSTITUENCY_FILE = "#{DATA_DIR}/constituencies.txt" + CONSTITUENCY_FILE = "#{DATA_DIR}/new_constituencies.txt" POSTCODE_FILE = "#{DATA_DIR}/postcodes.txt" def diff_postcodes old_file, new_file unless File.exist?(old_file) raise "#{old_file} not found" end unless File.exist?(new_file) raise "#{new_file} not found" end old_postcodes = "#{DATA_DIR}/old_postcodes.txt" new_postcodes = "#{DATA_DIR}/new_postcodes.txt" parse_postcodes old_file, old_postcodes parse_postcodes new_file, new_postcodes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if File.exist?(diff_file) cmd = "mv #{diff_file} #{diff_file}.#{Time.now.to_i.to_s}" puts cmd `#{cmd}` end cmd = "diff #{old_postcodes} #{new_postcodes} > #{diff_file}" puts cmd `#{cmd}` end def determine_postcode_changes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if file_not_found(diff_file) puts "Generate or upload #{diff_file}" return end to_delete = {} to_create = {} to_update = {} IO.foreach(diff_file) do |line| parts = line.strip.split(' ') indicator = parts[0] if indicator[/(<|>)/] ons_id = parts.pop postcode = parts.join(' ').sub(indicator, '').strip if indicator == '<' to_delete[postcode] = ons_id elsif indicator == '>' to_create[postcode] = ons_id end end end to_create.keys.each do |postcode| if to_delete.delete(postcode) ons_id = to_create.delete(postcode) to_update[postcode] = ons_id end end puts 'to_delete ' + to_delete.size.to_s + ' e.g. ' + to_delete.to_a.first.inspect puts 'to_update ' + to_update.size.to_s + ' e.g. ' + to_update.to_a.first.inspect puts 'to_create ' + to_create.size.to_s + ' e.g. ' + to_create.to_a.first.inspect puts 'checking we have constituencies... ' (to_delete.values + to_update.values + to_create.values).flatten.uniq.each do |ons_id| unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) raise "unexpected constituency id #{ons_id}" unless constituency end end puts 'all constituencies found' return [to_delete, to_update, to_create] end def update_postcodes to_delete, to_update, to_create = determine_postcode_changes # puts "Update database? y/n" # answer = STDIN.gets # if answer.strip == 'y' do_postcode_update to_delete, to_update, to_create # else # puts 'exiting without database update' # end end def ignore_ons_id?(ons_id) ons_id == '800' || ons_id == '900' end def analyze_postcode_update to_delete, to_update, to_create = determine_postcode_changes already_deleted = [] to_delete.each do |postcode, ons_id| already_deleted << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO DELETE, BUT ALREADY DELETED: #{already_deleted.size}" missing_updates = [] to_update.each do |postcode, ons_id| missing_updates << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO UPDATE, BUT MISSING FROM DB: #{missing_updates.size}" already_there = [] to_create.each do |postcode, ons_id| already_there << [postcode, ons_id] if Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO CREATE, BUT ALREADY IN DB: #{already_there.size}" end def do_postcode_update to_delete, to_update, to_create puts 'do_postcode_update...' total = (to_delete.size + to_update.size + to_create.size).to_f count = 0 include ActionView::Helpers::DateHelper start_timing to_delete.each do |postcode, ons_id| if post_code = Postcode.find_by_code(postcode.sub(' ','')) if ManualPostcode.find_by_code(postcode.sub(' ','')) puts " (ignoring manually added postcode - #{postcode})" else post_code.destroy count = count.next log_duration count / total end else warn "cannot delete postcode, as it was not in database: #{postcode}" end end to_update.each do |postcode, ons_id| post_code = Postcode.find_by_code(postcode.sub(' ','')) if post_code unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) if constituency.nil? raise "cannot update postcode, as constituency was not in database: #{postcode} #{ons_id}" end end if BlacklistedPostcode.find_by_code postcode.sub(' ','') puts " (deleting blacklisted postcode - #{postcode})" post_code.destroy else post_code.ons_id = ons_id.strip.to_i if constituency post_code.constituency_id = constituency.id else post_code.constituency_id = nil end post_code.save end count = count.next log_duration count / total else raise "cannot update postcode, as it was not in database: #{postcode} #{ons_id}" end end to_create.each do |postcode, ons_id| begin if Postcode.exists?(:code => postcode.sub(' ','')) warn 'exists ' + postcode elsif BlacklistedPostcode.find_by_code postcode.sub(' ','') puts " (ignoring blacklisted postcode - #{postcode})" else Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id.strip.to_i end rescue Exception => e raise e end count = count.next log_duration count / total end log_duration end def load_members member_file member_file = MEMBER_FILE unless member_file return if file_not_found(member_file) lines = [] IO.foreach(member_file) do |line| line.strip! lines << line unless(line.blank? || line[/Constituency/]) end lines.each do |line| begin parts = line.split("\t") constituency_name = parts[0].strip member_name = parts[1].strip if is_vacant?(member_name) log "Constituency is vacant: #{constituency_name}" else existing, updated_constituency = Constituency.load_tsv_line(line) if existing && updated_constituency existing.attributes = updated_constituency.attributes existing.save! elsif updated_constituency log "Cannot find constituency for member for line: #{line}" else # nothing to update end end rescue Exception => e log "Cannot set member_name on constituency for: #{line} | #{e.to_s}" end end end def load_constituencies return if file_not_found(CONSTITUENCY_FILE) Constituency.delete_all Slug.delete_all IO.foreach(CONSTITUENCY_FILE) do |line| constituency_id = line[0..2] constituency_name = line[3..(line.length-1)].strip Constituency.create :name=>constituency_name, :ons_id=>constituency_id end end def parse_postcodes source_file, output_file=POSTCODE_FILE return if file_not_found(source_file) start_timing blank_date = ' ' blank_code = ' ' new_line = "\n" space = ' ' post_codes = [] IO.foreach(source_file) do |line| termination_date = line[29..34] if termination_date == blank_date consistuency_code = line[69..71] unless consistuency_code == blank_code post_code = line[0..6] post_codes << post_code << space << consistuency_code post_codes << new_line end end end log_duration start_timing File.open(output_file,'w') do |file| file.write(post_codes.join('')) end log_duration end + # used to compare a postcodes.txt file generated from the August '09 data + # with the pcd_pcon_aug_2009_uk_lu.txt file to create a new postcodes.txt + # file (in the example given, saved as new_postcodes.txt) + def parse_new_postcodes original_file, new_file, output_file=POSTCODE_FILE + return if file_not_found(original_file) + return if file_not_found(new_file) + start_timing + + blank_date = ' ' + blank_code = ' ' + new_line = "\n" + space = ' ' + post_codes = [] + + new_data = File.open(new_file) + + IO.foreach(original_file) do |line| + #ignore blank lines, Guernsey and Isle of Man postcodes + unless line == "" || line[8..10] == "800" || line[8..10] == "900" + orig_post_code = line[0..6] + post_code = "" + while (post_code != orig_post_code) + data = new_data.readline + post_code = data[0..6] + constituency_code = data[24..26] + end + + post_codes << post_code << space << constituency_code + post_codes << new_line + end + end + log_duration + + start_timing + File.open(output_file,'w') do |file| + file.write(post_codes.join('')) + end + log_duration + end + def load_postcodes group_size=1000 return if file_not_found(POSTCODE_FILE) index = 0 groups = 0 puts 'saving data to db' Postcode.delete_all columns = [:code, :constituency_id] total = `cat #{POSTCODE_FILE} | wc -l` total = total.strip.to_f include ActionView::Helpers::DateHelper post_codes = [] start_timing IO.foreach(POSTCODE_FILE) do |line| code = line[0..6].tr(' ','') constituency_id = line[8..10] post_codes << [code, constituency_id] index = index.next if (index % group_size) == 0 load_codes(post_codes) groups = groups.next percentage_complete = (group_size * groups) / total log_duration percentage_complete post_codes = [] end end # complete remaining load_codes(post_codes) log_duration 1.0 end def load_postcode_districts PostcodeDistrict.delete_all sql = "SELECT SUBSTRING(code, 1, LENGTH(code)-3) " + "AS district, constituency_id " + "FROM postcodes " + "GROUP BY district, constituency_id;" districts = PostcodeDistrict.find_by_sql(sql) districts.each do |district| PostcodeDistrict.create!(district.attributes) end end def load_manual_postcodes manual_codes = ManualPostcode.all manual_codes.each do |manual_code| Postcode.create :code => manual_code.code, :constituency_id => manual_code.constituency_id, :ons_id => manual_code.ons_id end end private def load_codes(post_codes) post_codes.each do |codes| if BlacklistedPostcode.find_by_code codes[0] puts " (ignoring blacklisted postcode - #{codes[0]})" else Postcode.create :code => codes[0], :ons_id => codes[1] end end end def is_vacant?(name) name == 'Vacant' end def log msg $stderr.puts msg end def file_not_found file_name if File.exist?(file_name) false else log "Data file not found: #{file_name}" true end end end diff --git a/lib/tasks/parse.rake b/lib/tasks/parse.rake index ce7ddc8..51b49b2 100644 --- a/lib/tasks/parse.rake +++ b/lib/tasks/parse.rake @@ -1,87 +1,99 @@ require File.expand_path(File.dirname(__FILE__) + '/../data_loader') require File.expand_path(File.dirname(__FILE__) + '/../commons_member_biographies') require File.expand_path(File.dirname(__FILE__) + '/../cache_writer') require File.expand_path(File.dirname(__FILE__) + '/../constituency_upmystreet_links') require File.expand_path(File.dirname(__FILE__) + '/../boundary_changes') namespace :fymp do include FindYourMP::DataLoader include FindYourMP::CacheWriter include FindYourMP::BoundaryChanges desc "Create new_constituencies file for boundary changes" task :create_new_constituencies_file => :environment do create_new_constituencies_file end desc "Populate data for constituencies in DB" task :constituencies => :environment do load_constituencies end desc "Populate data for members in DB" task :members => :environment do file = ENV['file'] load_members file end desc "Create cache of all postcode pages" task :make_cache => :environment do make_cache end desc "Parse data file for postcode and constituency ID *only*" task :parse_postcodes do source_file = ENV['source'] if source_file parse_postcodes source_file else - puts 'USAGE: rake fymp:parse source=data/NSPDF_MAY_2009_UK_1M_FP.txt' + puts 'USAGE: rake fymp:parse_postcodes source=data/NSPDF_MAY_2009_UK_1M_FP.txt' + end + end + + desc "Parse data file for postcode and constituency ID *only*" + task :parse_new_postcodes do + old_file = ENV['oldfile'] + new_file = ENV['newfile'] + output_file = ENV['output'] + if old_file && new_file + parse_new_postcodes old_file, new_file, output_file + else + puts 'USAGE: rake fymp:parse_new_postcodes oldfile=data/postcodes.txt newfile=data/pcd_pcon_aug_2009_uk_lu/pcd_pcon_aug_2009_uk_lu.txt output=data/new_postcodes.txt' end end desc "Update postcodes from data files for postcode and constituency ID *only*" task :diff_postcodes => :environment do old_file = ENV['old'] new_file = ENV['new'] if old_file && new_file diff_postcodes old_file, new_file else puts 'USAGE: rake fymp:diff_postcodes old=data/NSPDF_FEB_2009_UK_1M.txt new=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end desc "Only analyze potential postcode update and log db discrepancies" task :analyze_postcode_update => :environment do analyze_postcode_update end desc "Update postcodes from data files for postcode and constituency ID *only*" task :update_postcodes => :environment do puts 'USAGE: rake fymp:update_postcodes' update_postcodes end desc "Populate data for postcode and constituency ID in DB" task :populate => :environment do load_postcodes end desc "Populate the postcode districts table" task :load_postcode_districts => :environment do load_postcode_districts end desc "Populate the manually added postcodes" task :load_manual_postcodes => :environment do load_manual_postcodes end desc "Populate the upmystreet lookup table" task :load_upmystreet_lookup => :environment do load_upmystreetcodes end end
robertbrook/findyourmp
c353e737e3151de1d0ceccfd9d9aff86b1cd5655
added rake task for producing list of new constituencies from the boundary changes file
diff --git a/lib/boundary_changes.rb b/lib/boundary_changes.rb new file mode 100644 index 0000000..e845dcb --- /dev/null +++ b/lib/boundary_changes.rb @@ -0,0 +1,56 @@ +require File.expand_path(File.dirname(__FILE__) + '/timer') + +module FindYourMP; end +module FindYourMP::BoundaryChanges + + include FindYourMP::Timer + + DATA_DIR = File.expand_path(File.dirname(__FILE__) + '/../data') + + BOUNDARY_FILE = "#{DATA_DIR}/new_boundary_data.txt" + + def create_new_constituencies_file + tab = "\t" + new_constituencies = [] + new_line = "\n" + + constituencies_file = "#{DATA_DIR}/new_constituencies.txt" + + start_timing + + if File.exist?(constituencies_file) + cmd = "mv #{constituencies_file} #{constituencies_file}.#{Time.now.to_i.to_s}" + puts cmd + `#{cmd}` + end + + constituencies = {} + IO.foreach(BOUNDARY_FILE) do |line| + ons_id = line[24..26] + unless ons_id == ' ' + unless constituencies.has_key?("#{ons_id}") + if line.length > 27 + constituency_name = line[27..line.length] + unless constituency_name.strip == "" + constituencies.merge!({"#{ons_id}" => "#{constituency_name.strip}"}) + end + end + end + end + end + + keys = constituencies.keys.sort + + line = [] + keys.each do |key| + new_constituencies << key << tab << constituencies[key] << new_line + end + log_duration + + start_timing + File.open(constituencies_file,'w') do |file| + file.write(new_constituencies.join('')) + end + log_duration + end +end \ No newline at end of file diff --git a/lib/tasks/parse.rake b/lib/tasks/parse.rake index bdf915e..ce7ddc8 100644 --- a/lib/tasks/parse.rake +++ b/lib/tasks/parse.rake @@ -1,78 +1,87 @@ require File.expand_path(File.dirname(__FILE__) + '/../data_loader') require File.expand_path(File.dirname(__FILE__) + '/../commons_member_biographies') require File.expand_path(File.dirname(__FILE__) + '/../cache_writer') require File.expand_path(File.dirname(__FILE__) + '/../constituency_upmystreet_links') +require File.expand_path(File.dirname(__FILE__) + '/../boundary_changes') namespace :fymp do include FindYourMP::DataLoader include FindYourMP::CacheWriter + include FindYourMP::BoundaryChanges + + desc "Create new_constituencies file for boundary changes" + task :create_new_constituencies_file => :environment do + create_new_constituencies_file + end + + desc "Populate data for constituencies in DB" task :constituencies => :environment do load_constituencies end desc "Populate data for members in DB" task :members => :environment do file = ENV['file'] load_members file end desc "Create cache of all postcode pages" task :make_cache => :environment do make_cache end desc "Parse data file for postcode and constituency ID *only*" task :parse_postcodes do source_file = ENV['source'] if source_file parse_postcodes source_file else puts 'USAGE: rake fymp:parse source=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end desc "Update postcodes from data files for postcode and constituency ID *only*" task :diff_postcodes => :environment do old_file = ENV['old'] new_file = ENV['new'] if old_file && new_file diff_postcodes old_file, new_file else puts 'USAGE: rake fymp:diff_postcodes old=data/NSPDF_FEB_2009_UK_1M.txt new=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end desc "Only analyze potential postcode update and log db discrepancies" task :analyze_postcode_update => :environment do analyze_postcode_update end desc "Update postcodes from data files for postcode and constituency ID *only*" task :update_postcodes => :environment do puts 'USAGE: rake fymp:update_postcodes' update_postcodes end desc "Populate data for postcode and constituency ID in DB" task :populate => :environment do load_postcodes end desc "Populate the postcode districts table" task :load_postcode_districts => :environment do load_postcode_districts end desc "Populate the manually added postcodes" task :load_manual_postcodes => :environment do load_manual_postcodes end desc "Populate the upmystreet lookup table" task :load_upmystreet_lookup => :environment do load_upmystreetcodes end end
robertbrook/findyourmp
8618e161f40886996afd084a3b55affd12356e50
diff_data task checks input files exist
diff --git a/lib/data_loader.rb b/lib/data_loader.rb index 309e621..f9bea11 100644 --- a/lib/data_loader.rb +++ b/lib/data_loader.rb @@ -1,348 +1,356 @@ require File.expand_path(File.dirname(__FILE__) + '/timer') module FindYourMP; end module FindYourMP::DataLoader include FindYourMP::Timer DATA_DIR = File.expand_path(File.dirname(__FILE__) + '/../data') MEMBER_FILE = "#{DATA_DIR}/FYMP_all.txt" CONSTITUENCY_FILE = "#{DATA_DIR}/constituencies.txt" POSTCODE_FILE = "#{DATA_DIR}/postcodes.txt" def diff_postcodes old_file, new_file + unless File.exist?(old_file) + raise "#{old_file} not found" + end + + unless File.exist?(new_file) + raise "#{new_file} not found" + end + old_postcodes = "#{DATA_DIR}/old_postcodes.txt" new_postcodes = "#{DATA_DIR}/new_postcodes.txt" parse_postcodes old_file, old_postcodes parse_postcodes new_file, new_postcodes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if File.exist?(diff_file) cmd = "mv #{diff_file} #{diff_file}.#{Time.now.to_i.to_s}" puts cmd `#{cmd}` end cmd = "diff #{old_postcodes} #{new_postcodes} > #{diff_file}" puts cmd `#{cmd}` end def determine_postcode_changes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if file_not_found(diff_file) puts "Generate or upload #{diff_file}" return end to_delete = {} to_create = {} to_update = {} IO.foreach(diff_file) do |line| parts = line.strip.split(' ') indicator = parts[0] if indicator[/(<|>)/] ons_id = parts.pop postcode = parts.join(' ').sub(indicator, '').strip if indicator == '<' to_delete[postcode] = ons_id elsif indicator == '>' to_create[postcode] = ons_id end end end to_create.keys.each do |postcode| if to_delete.delete(postcode) ons_id = to_create.delete(postcode) to_update[postcode] = ons_id end end puts 'to_delete ' + to_delete.size.to_s + ' e.g. ' + to_delete.to_a.first.inspect puts 'to_update ' + to_update.size.to_s + ' e.g. ' + to_update.to_a.first.inspect puts 'to_create ' + to_create.size.to_s + ' e.g. ' + to_create.to_a.first.inspect puts 'checking we have constituencies... ' (to_delete.values + to_update.values + to_create.values).flatten.uniq.each do |ons_id| unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) raise "unexpected constituency id #{ons_id}" unless constituency end end puts 'all constituencies found' return [to_delete, to_update, to_create] end def update_postcodes to_delete, to_update, to_create = determine_postcode_changes # puts "Update database? y/n" # answer = STDIN.gets # if answer.strip == 'y' do_postcode_update to_delete, to_update, to_create # else # puts 'exiting without database update' # end end def ignore_ons_id?(ons_id) ons_id == '800' || ons_id == '900' end def analyze_postcode_update to_delete, to_update, to_create = determine_postcode_changes already_deleted = [] to_delete.each do |postcode, ons_id| already_deleted << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO DELETE, BUT ALREADY DELETED: #{already_deleted.size}" missing_updates = [] to_update.each do |postcode, ons_id| missing_updates << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO UPDATE, BUT MISSING FROM DB: #{missing_updates.size}" already_there = [] to_create.each do |postcode, ons_id| already_there << [postcode, ons_id] if Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO CREATE, BUT ALREADY IN DB: #{already_there.size}" end def do_postcode_update to_delete, to_update, to_create puts 'do_postcode_update...' total = (to_delete.size + to_update.size + to_create.size).to_f count = 0 include ActionView::Helpers::DateHelper start_timing to_delete.each do |postcode, ons_id| if post_code = Postcode.find_by_code(postcode.sub(' ','')) if ManualPostcode.find_by_code(postcode.sub(' ','')) puts " (ignoring manually added postcode - #{postcode})" else post_code.destroy count = count.next log_duration count / total end else warn "cannot delete postcode, as it was not in database: #{postcode}" end end to_update.each do |postcode, ons_id| post_code = Postcode.find_by_code(postcode.sub(' ','')) if post_code unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) if constituency.nil? raise "cannot update postcode, as constituency was not in database: #{postcode} #{ons_id}" end end if BlacklistedPostcode.find_by_code postcode.sub(' ','') puts " (deleting blacklisted postcode - #{postcode})" post_code.destroy else post_code.ons_id = ons_id.strip.to_i if constituency post_code.constituency_id = constituency.id else post_code.constituency_id = nil end post_code.save end count = count.next log_duration count / total else raise "cannot update postcode, as it was not in database: #{postcode} #{ons_id}" end end to_create.each do |postcode, ons_id| begin if Postcode.exists?(:code => postcode.sub(' ','')) warn 'exists ' + postcode elsif BlacklistedPostcode.find_by_code postcode.sub(' ','') puts " (ignoring blacklisted postcode - #{postcode})" else Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id.strip.to_i end rescue Exception => e raise e end count = count.next log_duration count / total end log_duration end def load_members member_file member_file = MEMBER_FILE unless member_file return if file_not_found(member_file) lines = [] IO.foreach(member_file) do |line| line.strip! lines << line unless(line.blank? || line[/Constituency/]) end lines.each do |line| begin parts = line.split("\t") constituency_name = parts[0].strip member_name = parts[1].strip if is_vacant?(member_name) log "Constituency is vacant: #{constituency_name}" else existing, updated_constituency = Constituency.load_tsv_line(line) if existing && updated_constituency existing.attributes = updated_constituency.attributes existing.save! elsif updated_constituency log "Cannot find constituency for member for line: #{line}" else # nothing to update end end rescue Exception => e log "Cannot set member_name on constituency for: #{line} | #{e.to_s}" end end end def load_constituencies return if file_not_found(CONSTITUENCY_FILE) Constituency.delete_all Slug.delete_all IO.foreach(CONSTITUENCY_FILE) do |line| constituency_id = line[0..2] constituency_name = line[3..(line.length-1)].strip Constituency.create :name=>constituency_name, :ons_id=>constituency_id end end def parse_postcodes source_file, output_file=POSTCODE_FILE return if file_not_found(source_file) start_timing blank_date = ' ' blank_code = ' ' new_line = "\n" space = ' ' post_codes = [] IO.foreach(source_file) do |line| termination_date = line[29..34] if termination_date == blank_date consistuency_code = line[69..71] unless consistuency_code == blank_code post_code = line[0..6] post_codes << post_code << space << consistuency_code post_codes << new_line end end end log_duration start_timing File.open(output_file,'w') do |file| file.write(post_codes.join('')) end log_duration end def load_postcodes group_size=1000 return if file_not_found(POSTCODE_FILE) index = 0 groups = 0 puts 'saving data to db' Postcode.delete_all columns = [:code, :constituency_id] total = `cat #{POSTCODE_FILE} | wc -l` total = total.strip.to_f include ActionView::Helpers::DateHelper post_codes = [] start_timing IO.foreach(POSTCODE_FILE) do |line| code = line[0..6].tr(' ','') constituency_id = line[8..10] post_codes << [code, constituency_id] index = index.next if (index % group_size) == 0 load_codes(post_codes) groups = groups.next percentage_complete = (group_size * groups) / total log_duration percentage_complete post_codes = [] end end # complete remaining load_codes(post_codes) log_duration 1.0 end def load_postcode_districts PostcodeDistrict.delete_all sql = "SELECT SUBSTRING(code, 1, LENGTH(code)-3) " + "AS district, constituency_id " + "FROM postcodes " + "GROUP BY district, constituency_id;" districts = PostcodeDistrict.find_by_sql(sql) districts.each do |district| PostcodeDistrict.create!(district.attributes) end end def load_manual_postcodes manual_codes = ManualPostcode.all manual_codes.each do |manual_code| Postcode.create :code => manual_code.code, :constituency_id => manual_code.constituency_id, :ons_id => manual_code.ons_id end end private def load_codes(post_codes) post_codes.each do |codes| if BlacklistedPostcode.find_by_code codes[0] puts " (ignoring blacklisted postcode - #{codes[0]})" else Postcode.create :code => codes[0], :ons_id => codes[1] end end end def is_vacant?(name) name == 'Vacant' end def log msg $stderr.puts msg end def file_not_found file_name if File.exist?(file_name) false else log "Data file not found: #{file_name}" true end end end
robertbrook/findyourmp
0957fbd1ca4ee27c279c1e803f47cf39f83e4a38
added Google Analytics code
diff --git a/app/views/layouts/application.rhtml b/app/views/layouts/application.rhtml index a248739..d53f4fc 100644 --- a/app/views/layouts/application.rhtml +++ b/app/views/layouts/application.rhtml @@ -1,236 +1,245 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head profile="http://gmpg.org/xfn/11"> <% if RAILS_ENV != 'test' %> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>UK Parliament - <%= @title ? "#{@title} (Find Your MP)" : "Search (Find Your MP)" %></title> <% if @meta_description %><meta name="description" content="<%= @meta_description %>" /><% end %> <meta name="keywords" content="UK Parliament, Find your MP, Find my MP, Member of Parliament" /> <% if @nofollow %><meta name="robots" content="NOINDEX, NOFOLLOW" /><% end %> <style type="text/css" media="screen, projection"> @import url("/stylesheets/fymp.css"); @import url("/stylesheets/homepage.css"); @import url("/stylesheets/grid.css"); @import url("/stylesheets/main.css"); </style> <link rel="stylesheet" type="text/css" href="/stylesheets/print.css" media="print" /> <% if @show_postcode_autodiscovery_links %> <%= auto_discovery_link_tag(:xml, @url_for_this + ".xml") %> <%= auto_discovery_link_tag(:json, @url_for_this + ".json") %> <%= auto_discovery_link_tag(:js, @url_for_this + ".js") %> <%= auto_discovery_link_tag(:text, @url_for_this + ".text") %> <%= auto_discovery_link_tag(:csv, @url_for_this + ".csv") %> <%= auto_discovery_link_tag(:yaml, @url_for_this + ".yaml") %> <% end %> <% if @javascript %> <%= javascript_include_tag @javascript %> <% end %> <% end %> <script language="JavaScript1.1" type="text/javascript"> <!-- function displayDate() { var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'); var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat'); today = new Date(); formattedDate = DAY_NAMES[today.getDay()] + ' ' + today.getDate() + ' ' + MONTH_NAMES[today.getMonth()] + ' ' + today.getFullYear(); return formattedDate; } --> </script> </head> <body> <div id="outer_container"> <div id="inner_container"> <% if RAILS_ENV != 'test' %> <span class="hidden"><a href="#maincontent">Skip to main content</a></span> <div id="top_nav"> <div id="top_nav_content"> <ul> <li class="first"><a href="http://www.parliament.uk/site_information/accessibility.cfm">Accessibility</a></li> <li><a href="http://www.parliament.uk/index/">A-Z Index</a></li> <li><a href="http://www.parliament.uk/glossary/glossary.cfm">Glossary</a></li> <li><a href="http://www.parliament.uk/site_information/help.cfm">Help</a></li> <li><a href="http://www.parliament.uk/site_information/contact_us.cfm">Contact Us</a></li> </ul> </div> </div> <div id="banner"> <div id="banner_top"> <div id="banner_img"> <a href="http://www.parliament.uk/"><img src="/images/parliament-uk.gif" width="300" height="55" alt="United Kingdom Parliament" /></a> </div> <div class="banner_divider">&nbsp;</div> <div id="banner_time"> <div id="big_ben"><object type="application/x-shockwave-flash" data="/images/bigben.swf" width="50" height="50" id="bigben"></object></div> <div id="time_text"><span><script language="Javascript 1.1" type="text/javascript">document.write(displayDate());</script></span></div> </div> <div class="banner_divider">&nbsp;</div> <form action="http://www.publications.parliament.uk/cgi-bin/search.pl" method="post"> <div id="banner_search"> <h2 class="hidden">Search</h2> <label for="search" class="hidden">Search</label> <input type="text" name="QUERY00" id="search" class="searchBox" /> <input type="submit" class="searchSubmit" value="Search" name="CMD=search.run" /> <input type="hidden" name="STYPE" value="SIMPLE" /> <input type="hidden" name="DB" value="semukparl" /> <input type="hidden" name="SHOWCONCEPT" value="1" /> <input type="hidden" name="ORGANISE_CODED" value="R:date" /> <input type="hidden" name="ENDDATE" value="TODAY" /> <input type="hidden" name="DAYSMINUS" value="730" /> </div> </form> </div> <div id="main_nav"> <ul> <li class="first"><a href="http://www.parliament.uk/">Home</a></li> <li><a href="http://www.parliament.uk/visiting">Visiting</a></li> <li><a href="http://www.parliament.uk/about/">About</a></li> <li><a href="http://www.parliament.uk/business/">Parliamentary Business</a></li> <li class="selected"><a href="http://www.parliament.uk/mpslordsandoffices/">MPs, Lords and Offices</a></li> <li><a href="http://www.parliament.uk/getinvolved/">Get Involved</a></li> <li><a href="http://www.parliament.uk/topics/topical-issues.htm">Topical Issues</a></li> <li><a href="http://www.parliament.uk/education/">Education</a></li> </ul> </div> <div id="secondary_nav"> <ul> <li class="selected"><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords.cfm">MPs and Lords</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/government_and_opposition.cfm">Government &amp; Opposition</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/offices.cfm">Parliamentary Offices</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/finances.cfm">Members' Allowances</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/standards.cfm">Standards</a></li> </ul> </div> </div> <div id="breadcrumb"> You are here: <a href="http://www.parliament.uk/">Parliament Home</a> &gt; <a href="http://www.parliament.uk/mpslordsandoffices/">MPs and Lords</a> &gt; <%= @crumbtrail ? "<a href=\"/\">Find your MP</a> &gt; #{@crumbtrail}" : "Find your MP" %> </div> <% end %> <div id="page_content"> <% if RAILS_ENV != 'test' %> <div class="column_wrapper_right"> <div id="leftnav"> <ul id="sidebarleft"> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/alms.cfm">Alphabetical list of MPs</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/alcm.cfm">MPs by constituency</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/clomps.cfm">MPs by county and unitary authority</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/party.cfm">MPs by party</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/gender.cfm">MPs by gender</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/stateparties.cfm">Current state of the parties</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/selmem.cfm">Commons Select Committee membership</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/alphabetical_list_of_members.cfm">Lords: alphabetical list of Members</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/analysis_by_composition.cfm">Lords by party and type of peerage</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/conservative_members.cfm">Lords by party - Conservative</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/labour_members.cfm">Lords by party - Labour</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/liberal_democrat_members.cfm">Lords by party - Liberal Democrat</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/crossbench_members.cfm">Lords by party - Crossbench</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/other_members.cfm">Lords by party - other</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/house_of_lords_bishops.cfm">Lords Bishops</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/deceased_members.cfm">Lords who have died since 1 January 2009</a></li> <li><a href="http://www.parliament.uk/mpslordsandoffices/mps_and_lords/new_members.cfm">New Members in the Lords</a></li> </ul> </div> <div class="spacer">&nbsp;</div> </div> <% end %> <div class="spacer9">&nbsp;</div> <div class="<%= is_admin? ? "column-620" : "column-460" %>"> <h1><a href="/">Find your MP</a></h1> <h2><a name="maincontent" id="maincontent"></a><%= @title ? "#{@title}" : "Search" %></h2> <% if flash[:notice] %> <div class="text <%= flash[:notice][/Successful/] ? 'info' : 'flash' %>"> <%= flash[:notice] %> </div> <% end %> <div><%= yield %></div> </div> <div class="spacer9">&nbsp;</div> <% if !is_admin? && RAILS_ENV != 'test' && @title != 'API' %> <div class="column_wrapper_left"> <div class="spacer">&nbsp;</div> <div class="column-300"> <div class="column_content"> <h3 class="section_head">Help and contacts</h3> <div class="column_content"> <ul class="greybullet text tight"> <li><a href="http://www.parliament.uk/directories/hcio/findyourmp_help.cfm">Help using Find your MP</a></li> <li><a href="http://www.parliament.uk/directories/hcio.cfm">House of Commons Information Office</a></li> </ul> </div> <div class="hspacer">&nbsp;</div> <h3 class="section_head">About Parliament</h3> <div class="column_content"> <ul class="greybullet text tight"> <li><a href="http://www.parliament.uk/about/how/members/mps.cfm">What MPs do</a></li> <li><a href="http://www.parliament.uk/about/how/members/mps_contact.cfm">Contacting your MP</a></li> <li><a href="http://www.parliament.uk/about/how/members/mps_contact/when.cfm">When to contact your MP</a></li> <li><a href="http://www.parliament.uk/about/how/members/mps_contact/what.cfm">What your MP can do for you</a></li> <li><a href="http://www.parliament.uk/about/languages/yourmp.cfm">You and your MP (multiple languages)</a></li> </ul> </div> <div class="hspacer">&nbsp;</div> <h3 class="section_head">Follow Parliament on</h3> <div class="column_content"> <ul class="greybullet text tight"> <li><a href="http://www.flickr.com/photos/25334641@N08">Flickr photostream</a></li> <li><a href="http://lordsoftheblog.wordpress.com">Lords of the blog</a></li> <li><a href="http://www.parliament.uk/podcasts/">Podcasts</a></li> <li><a href="http://parliamentlabs.wordpress.com">Parliament Labs blog</a></li> <li><a href="http://twitter.com/ukparliament">Twitter</a></li> <li><a href="http://youtube.com/UKParliament">Parliament&#8217;s YouTube channel</a></li> </ul> </div> <div class="hspacer">&nbsp;</div> </div> </div> </div> <% end %> </div> <div id="footer_nav"> <p>Source: NSPD 2008, National Statistics Crown copyright material is reproduced with the permission of the Controller of HMSO and Queen’s Printer for Scotland.</p> <ul> <li class="first"><a href="http://www.parliament.uk/index/">A-Z Index</a></li> <li><a href="http://www.parliament.uk/site_information/accessibility.cfm">Accessibility</a></li> <li><a href="http://www.parliament.uk/site_information/careers/jobs.cfm">Jobs</a></li> <li><a href="http://www.parliament.uk/site_information/contact_us.cfm">Contact Us</a></li> <li><a href="http://www.parliament.uk/parliamentary_publications_and_archives/foi_introduction.cfm">Freedom of Information</a></li> <li><a href="http://www.parliament.uk/site_information/glossary.cfm">Glossary</a></li> <li><a href="http://www.parliament.uk/site_information/help.cfm">Help</a></li> <li><a href="http://www.parliament.uk/site_information/site_information.cfm">Using this website</a></li> <!-- <%= link_to 'API', api_path %> --> <% if is_admin? %> <li><%= link_to "Logout", user_session_path, :method => :delete %></li> <li><%= link_to 'Admin home', admin_path %></li> <% elsif RAILS_ENV == 'test' %> <li><%= link_to "Log In", new_user_session_path %></li> <% end %> </ul> </div> <div class="hspacer">&nbsp;</div> </div> </div> <% if RAILS_ENV == 'production' %> + <script type="text/javascript"> + var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); + document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); + </script> + <script type="text/javascript"> + try{ + var pageTracker = _gat._getTracker("UA-2953405-1"); + pageTracker._trackPageview(); + } catch(err) {}</script> <script language="JavaScript1.1" type="text/javascript"> <!-- var gDomain="www.stats.tso.co.uk"; var gDcsId="dcs8a1rrculeroaqmbjq87oq1_4s7l"; var gFpcDom=".parliament.uk"; var gFpc="WT_FPC"; var gConvert=true; if((typeof(gConvert)!="undefined")&&gConvert&&(document.cookie.indexOf(gFpc+"=")==-1)&&(document.cookie.indexOf("WTLOPTOUT=")==-1)){ document.write("<scr"+"ipt type='text/javascript' SRC='"+"http"+(window.location.protocol.indexOf('https:')==0?'s':'')+"://"+gDomain+"/"+gDcsId+"/wtid.js"+"'><\/scr"+"ipt>"); } --> </script> <script language="JavaScript1.1" src="/javascripts/webtrends.js" type="text/javascript"></script> <% end %> </body> </html>
robertbrook/findyourmp
e00577eb551a895e453acba8c38b28ff64783bfe
attempting to fix Vista/IE display bug that causes the text in the Telephone field to overlap the Letter field on the constituency page
diff --git a/public/stylesheets/fymp.css b/public/stylesheets/fymp.css index bf3f05f..a45a726 100644 --- a/public/stylesheets/fymp.css +++ b/public/stylesheets/fymp.css @@ -1,107 +1,107 @@ #secondary_breadcrumb { float: left; width: 460px; clear: both; font-size: 0.7em; padding-bottom: 10px; border: 0; margin: 0 0 10px 0; } .column_solid_top { border-top: 1px solid #cfcfcf; float: left; width: 100%; } .text code { font-size: 1.3em; } .info { color: green; } .flash { color: red; } .warn { color: red; } a.warn { text-decoration: underline; } a.warn:visited { color: red; } .hidden_member { color: grey; font-style: italic; } .form_field { margin: 1em 0; } .fieldWithErrors input, .fieldWithErrors textarea { margin: 0; border: solid 1px #cc0000; background-color: #ffcccc; } .formError { color: red; margin-left: 10em; } .errorExplanation { width: 460px; } label { font-size:0.8em; width: 12em; float: left; text-align: right; margin-right: 0.5em; display: block; } label.checkbox_label { float: none; display: inline; } .row_item { padding-top: 0.7em; clear: both; - height: 25px; + min-height: 25px; } .row_label { float: left; width: 125px; } .row_value { float: left; width:330px; } .padded_subheading { padding-top: 1em; padding-bottom: 1em; border-bottom: none; } #mp_search { padding-top: 1em; padding-bottom: 0.1em; } #mp_search .padded_subheading { padding-bottom: 0.1em; }
robertbrook/findyourmp
7e27d732b584a4da23ea5825a10ddbd90c7b72e1
fixed failing features
diff --git a/features/search_api.feature b/features/search_api.feature index 0211e01..9589b4a 100644 --- a/features/search_api.feature +++ b/features/search_api.feature @@ -1,96 +1,89 @@ Feature: Search API In order to search using the API as a constituent I want to get data via the search API Scenario: Call search API with valid postcode, requesting XML Given I call the search API searching for "AB101AA" and requesting "xml" Then I should see xml "<results>" Then I should see xml "<constituencies>" Then I should see xml " <constituency>" Then I should see xml " <constituency-name>Aberdeen North</constituency-name>" Then I should see xml " <member-name>Frank Doran</member-name>" Then I should see xml " <member-party></member-party>" Then I should see xml " <member-biography-url></member-biography-url>" Then I should see xml " <member-website></member-website>" Then I should see xml " <uri>http://www.example.com/constituencies/aberdeen-north.xml</uri>" Scenario: Call search API with valid postcode, requesting plain text Given I call the search API searching for "AB101AA" and requesting "text" - # Then I should see "postcode: AB10 1AA" And I should see "constituency_name: Aberdeen North" And I should see "member_name: Frank Doran" - # And I should see "/postcodes/AB101AA.txt" Scenario: Call search API with valid postcode, requesting JSON Given I call the search API searching for "AB101AA" and requesting "json" - # Then I should see json {"postcode": {"code": "AB10 1AA", "constituency_name": "Aberdeen North", "member_name": "Frank Doran", "uri": - Then I should see json {"results": { "constituencies": {"constituency": {"constituency_name": "Aberdeen North", "member_name": "Frank Doran", "member_party": "", "member_biography_url": "", "member_website": "", "uri": "http://localhost:3000/constituencies/aberdeen-north.json" } }, "members": {} }} - # And I should see "/postcodes/AB101AA.json" + Then I should see json {"results": { "constituencies": {"constituency": {"constituency_name": "Aberdeen North", "member_name": "Frank Doran", "member_party": "", "member_biography_url": "", "member_website": "", "uri": "http://www.example.com/constituencies/aberdeen-north.json" } }, "members": {} }} Scenario: Call search API with valid postcode, requesting CSV Given I call the search API searching for "AB101AA" and requesting "csv" - # Then I should see "postcode,constituency_name,member_name,uri" - # And I should see csv "AB10 1AA","Aberdeen North","Frank Doran" Then I should see "constituency_name,member_name,member_party,member_biography_url,member_website" - And I should see csv "Aberdeen North","Frank Doran","","","","http://localhost:3000/constituencies/aberdeen-north.csv" - # And I should see "/postcodes/AB101AA.csv" + And I should see csv "Aberdeen North","Frank Doran","","","","http://www.example.com/constituencies/aberdeen-north.csv" Scenario: Call search API with valid constituency name, requesting XML Given I call the search API searching for "Aberdeen South" and requesting "xml" Then I should see xml "<constituency>" And I should see xml "<constituency-name>Aberdeen South</constituency-name>" And I should see xml "<member-name>Miss Anne Begg</member-name>" And I should see xml "<member-party></member-party>" And I should see xml "<member-biography-url></member-biography-url>" And I should see xml "<member-website></member-website>" And I should see xml "/constituencies/aberdeen-south.xml</uri>" Scenario: Call search API with valid constituency name, requesting JSON Given I call the search API searching for "Aberdeen South" and requesting "json" Then I should see json {"constituency": { And I should see json "constituency_name": "Aberdeen South" And I should see json "member_name": "Miss Anne Begg" And I should see json "member_party": "" And I should see json "member_biography_url": "" And I should see json "member_website": "" And I should see json "uri": And I should see json /constituencies/aberdeen-south.json Scenario: Call search API with valid constituency name (but no MP), requesting XML Given I call the search API searching for "Glenrothes" and requesting "xml" Then I should see xml "<constituency>" And I should see xml "<constituency-name>Glenrothes</constituency-name>" And I should see xml "<member-name>No sitting member</member-name>" And I should see xml "<member-party></member-party>" And I should see xml "<member-biography-url></member-biography-url>" And I should see xml "<member-website></member-website>" And I should see xml "/constituencies/glenrothes.xml</uri>" Scenario: Call search API with partial member name which will return more than 1 result line, requesting XML Given I call the search API searching for "Frank" and requesting "xml" Then I should see xml "<results>" And I should see xml "<constituency-name>Aberdeen North</constituency-name>" And I should see xml "<member-name>Frank Doran</member-name>" And I should see xml "<constituency-name>Motherwell and Wishaw</constituency-name>" And I should see xml "<member-name>Mr Frank Roy</member-name>" And I should see xml "/constituencies/motherwell-and-wishaw.xml</uri>" And I should see xml "/constituencies/aberdeen-north.xml</uri>" Scenario: Call search API with an invalid search term, requesting XML Given I call the search API searching for "invalid" and requesting "xml" Then I should see xml "<constituencies></constituencies>" Scenario: Call search API to return a single record where the constituency name contains a "&" character, requesting XML Given I call the search API searching for "Newry" and requesting "xml" Then I should see xml "<constituency>" And I should see xml "<constituency-name>Newry &amp; Armagh</constituency-name>" Scenario: Call search API with postcode district, requesting XML Given I call the search API searching for "BT35" and requesting "xml" Then I should see xml "<results>" And I should see xml "<constituency>" And I should see xml "<constituency-name>Upper Bann</constituency-name>" And I should see xml "<constituency-name>Newry &amp; Armagh</constituency-name>" And I should see xml "/constituencies/upper-bann.xml</uri>" And I should see xml "/constituencies/newry-armagh.xml</uri>" diff --git a/features/step_definitions/search_api_steps.rb b/features/step_definitions/search_api_steps.rb index 3efeed9..2f17155 100644 --- a/features/step_definitions/search_api_steps.rb +++ b/features/step_definitions/search_api_steps.rb @@ -1,3 +1,3 @@ Given /^I call the search API searching for "(.+)" and requesting "(.+)"$/ do |search_term, format| - visit URI.escape("/api/search?q=#{search_term}&f=#{format}") + visit URI.escape("/api/search/?q=#{search_term}&f=#{format}") end \ No newline at end of file
robertbrook/findyourmp
f0a4633ebed209fe257c1b8183eebdc095427bf3
fixing bug with manual postcode logic
diff --git a/app/models/manual_postcode.rb b/app/models/manual_postcode.rb index aebd4b5..a910978 100644 --- a/app/models/manual_postcode.rb +++ b/app/models/manual_postcode.rb @@ -1,39 +1,40 @@ class ManualPostcode < ActiveRecord::Base validates_uniqueness_of :code validates_presence_of :ons_id belongs_to :constituency delegate :name, :to => :constituency class << self def add_manual_postcode code, constituency_id, ons_id + code.gsub!(' ', "") postcode = Postcode.find_by_code code unless postcode unless ManualPostcode.find_by_code code manual_postcode = ManualPostcode.create :code => code, :constituency_id => constituency_id, :ons_id => ons_id if manual_postcode postcode = Postcode.create :code => code, :constituency_id => constituency_id, :ons_id => ons_id unless postcode manual_postcode.delete return false end else return false end else Postcode.create :code => code, :constituency_id => constituency_id, :ons_id => ons_id end end true end end def remove - postcode = Postcode.find_by_code + postcode = Postcode.find_by_code code if postcode postcode.delete end self.delete end end diff --git a/app/views/manual_postcodes/new.haml b/app/views/manual_postcodes/new.haml index 8f33d35..f1916df 100644 --- a/app/views/manual_postcodes/new.haml +++ b/app/views/manual_postcodes/new.haml @@ -1,29 +1,31 @@ -@title = 'Manually added postcodes' - @crumbtrail = link_to_admin_home -unless @constituencies - form_tag('/admin/manual_postcodes/new', :method => :post) do = text_field 'manual_postcodes', 'code' = submit_tag 'Search' %br %div.text -if request.post? -if @constituencies %p Please choose a constituency for the postcode <code> = flash[:code] </code> from the dropdown: -form_for :manual_postcodes, :url => '/admin/manual_postcodes/new', :method => :post do |f| - = f.select('constituency', @constituencies.collect {|constituency| [constituency.name, constituency.id]}) + - options = @constituencies.collect {|constituency| [constituency.name, constituency.id]} + - options = options.sort_by{ |x| x[0] } + = f.select('constituency', options) = f.submit 'Create manual postcode' -else Sorry this postcode already exists in the database, please try again %p.text = link_to 'Return to list', manual_postcodes_path %p.text %br = link_to 'Admin home', admin_path \ No newline at end of file diff --git a/spec/controllers/admin_controller_spec.rb b/spec/controllers/admin_controller_spec.rb index 87a8415..a4f385f 100644 --- a/spec/controllers/admin_controller_spec.rb +++ b/spec/controllers/admin_controller_spec.rb @@ -1,132 +1,132 @@ require File.dirname(__FILE__) + '/../spec_helper' describe AdminController do describe "when finding route for action" do it 'should display index' do params_from(:get, "/admin").should == {:controller => "admin", :action => "index"} end end describe 'when not logged in' do it 'should redirect to login page' do get :index response.should redirect_to(new_user_session_url) get :shutdown response.should redirect_to(new_user_session_url) get :mailserver_status response.should redirect_to(new_user_session_url) end end describe 'when logged in' do before do current_user = mock_model User current_user.stub!(:admin?).and_return(false) controller.stub!(:current_user).and_return(current_user) end describe 'when asked for the index' do it 'should not redirect' do get :index response.should_not redirect_to(new_user_session_url) end end describe 'when asked to shutdown' do it 'should redirect to the admin page' do get :shutdown response.should redirect_to(admin_url) end end describe 'when asked for mailserver status' do it 'should redirect to the admin page' do get :mailserver_status response.should redirect_to(admin_url) end end end describe 'when logged in as admin' do before do current_user = mock_model User current_user.stub!(:admin?).and_return(true) controller.stub!(:current_user).and_return(current_user) end describe 'when asked for the index' do it 'should not redirect' do get :index response.should_not redirect_to(new_user_session_url) end it 'should assign values to the view' do Message.stub!(:sent_message_count).and_return(20) Message.stub!(:waiting_to_be_sent_count).and_return(2) get :index assigns[:sent_message_count].should == 20 assigns[:waiting_to_be_sent_count].should == 2 end end describe 'when asked for sent' do it 'should assign values to the view' do Message.stub!(:sent_by_month_count).and_return(20) get :sent assigns[:sent_by_month_count].should == 20 end end describe 'when asked for waiting_to_be_sent' do it 'should assign values to the view' do Message.stub!(:waiting_to_be_sent_by_month_count).and_return(2) get :waiting_to_be_sent assigns[:waiting_to_be_sent_by_month_count].should == 2 end end describe 'when asked for sent' do it 'should assign values to the view' do Message.stub!(:memory_stats).and_return("value") get :stats assigns[:memory_stats].should == "value" end end describe 'when asked for sent_by_month' do it 'should assign values to the view' do Message.stub!(:sent_by_constituency).and_return(88) get :sent_by_month, :yyyy_mm => '2008_01' assigns[:sent_by_constituency].should == 88 end end - describe 'when asked to shutdown' do - it 'should not redirect' do - get :shutdown - response.should_not redirect_to(admin_url) - end - end + #describe 'when asked to shutdown' do + # it 'should not redirect' do + # get :shutdown + # response.should_not redirect_to(admin_url) + # end + #end describe 'when asked for mail server status' do it 'should assign values to the view' do get :mailserver_status assigns[:feed].should_not == "" assigns[:ping_test].should be_nil get :mailserver_status, :commit => 'Ping server' assigns[:ping_test][0].should include("PING mail.messagingengine.com") end end end end
robertbrook/findyourmp
68a897be05a5db2c7d4cdf2afcf2b7cb0033d1a7
(re-)adding Blacklisted and Manual postcode logic to data update tasks
diff --git a/lib/data_loader.rb b/lib/data_loader.rb index 63162f2..309e621 100644 --- a/lib/data_loader.rb +++ b/lib/data_loader.rb @@ -1,344 +1,348 @@ require File.expand_path(File.dirname(__FILE__) + '/timer') module FindYourMP; end module FindYourMP::DataLoader include FindYourMP::Timer DATA_DIR = File.expand_path(File.dirname(__FILE__) + '/../data') MEMBER_FILE = "#{DATA_DIR}/FYMP_all.txt" CONSTITUENCY_FILE = "#{DATA_DIR}/constituencies.txt" POSTCODE_FILE = "#{DATA_DIR}/postcodes.txt" def diff_postcodes old_file, new_file old_postcodes = "#{DATA_DIR}/old_postcodes.txt" new_postcodes = "#{DATA_DIR}/new_postcodes.txt" parse_postcodes old_file, old_postcodes parse_postcodes new_file, new_postcodes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if File.exist?(diff_file) cmd = "mv #{diff_file} #{diff_file}.#{Time.now.to_i.to_s}" puts cmd `#{cmd}` end cmd = "diff #{old_postcodes} #{new_postcodes} > #{diff_file}" puts cmd `#{cmd}` end def determine_postcode_changes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if file_not_found(diff_file) puts "Generate or upload #{diff_file}" return end to_delete = {} to_create = {} to_update = {} IO.foreach(diff_file) do |line| parts = line.strip.split(' ') indicator = parts[0] if indicator[/(<|>)/] ons_id = parts.pop postcode = parts.join(' ').sub(indicator, '').strip if indicator == '<' to_delete[postcode] = ons_id elsif indicator == '>' to_create[postcode] = ons_id end end end to_create.keys.each do |postcode| if to_delete.delete(postcode) ons_id = to_create.delete(postcode) to_update[postcode] = ons_id end end puts 'to_delete ' + to_delete.size.to_s + ' e.g. ' + to_delete.to_a.first.inspect puts 'to_update ' + to_update.size.to_s + ' e.g. ' + to_update.to_a.first.inspect puts 'to_create ' + to_create.size.to_s + ' e.g. ' + to_create.to_a.first.inspect puts 'checking we have constituencies... ' (to_delete.values + to_update.values + to_create.values).flatten.uniq.each do |ons_id| unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) raise "unexpected constituency id #{ons_id}" unless constituency end end puts 'all constituencies found' return [to_delete, to_update, to_create] end def update_postcodes to_delete, to_update, to_create = determine_postcode_changes # puts "Update database? y/n" # answer = STDIN.gets # if answer.strip == 'y' do_postcode_update to_delete, to_update, to_create # else # puts 'exiting without database update' # end end def ignore_ons_id?(ons_id) ons_id == '800' || ons_id == '900' end def analyze_postcode_update to_delete, to_update, to_create = determine_postcode_changes already_deleted = [] to_delete.each do |postcode, ons_id| already_deleted << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO DELETE, BUT ALREADY DELETED: #{already_deleted.size}" missing_updates = [] to_update.each do |postcode, ons_id| missing_updates << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO UPDATE, BUT MISSING FROM DB: #{missing_updates.size}" already_there = [] to_create.each do |postcode, ons_id| already_there << [postcode, ons_id] if Postcode.exists?(:code => postcode.sub(' ','')) end puts "TO CREATE, BUT ALREADY IN DB: #{already_there.size}" end def do_postcode_update to_delete, to_update, to_create puts 'do_postcode_update...' total = (to_delete.size + to_update.size + to_create.size).to_f count = 0 include ActionView::Helpers::DateHelper start_timing to_delete.each do |postcode, ons_id| if post_code = Postcode.find_by_code(postcode.sub(' ','')) - post_code.destroy - count = count.next - log_duration count / total + if ManualPostcode.find_by_code(postcode.sub(' ','')) + puts " (ignoring manually added postcode - #{postcode})" + else + post_code.destroy + count = count.next + log_duration count / total + end else warn "cannot delete postcode, as it was not in database: #{postcode}" end end to_update.each do |postcode, ons_id| post_code = Postcode.find_by_code(postcode.sub(' ','')) if post_code unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) if constituency.nil? raise "cannot update postcode, as constituency was not in database: #{postcode} #{ons_id}" end end - # if BlacklistedPostcode.find_by_code postcode.sub(' ','') - # puts " (deleting blacklisted postcode - #{postcode})" - # post_code.destroy - # else + if BlacklistedPostcode.find_by_code postcode.sub(' ','') + puts " (deleting blacklisted postcode - #{postcode})" + post_code.destroy + else post_code.ons_id = ons_id.strip.to_i if constituency post_code.constituency_id = constituency.id else post_code.constituency_id = nil end post_code.save - # end + end count = count.next log_duration count / total else raise "cannot update postcode, as it was not in database: #{postcode} #{ons_id}" end end to_create.each do |postcode, ons_id| begin if Postcode.exists?(:code => postcode.sub(' ','')) warn 'exists ' + postcode - # elsif BlacklistedPostcode.find_by_code postcode.sub(' ','') - # puts " (ignoring blacklisted postcode - #{postcode})" + elsif BlacklistedPostcode.find_by_code postcode.sub(' ','') + puts " (ignoring blacklisted postcode - #{postcode})" else Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id.strip.to_i end rescue Exception => e raise e end count = count.next log_duration count / total end log_duration end def load_members member_file member_file = MEMBER_FILE unless member_file return if file_not_found(member_file) lines = [] IO.foreach(member_file) do |line| line.strip! lines << line unless(line.blank? || line[/Constituency/]) end lines.each do |line| begin parts = line.split("\t") constituency_name = parts[0].strip member_name = parts[1].strip if is_vacant?(member_name) log "Constituency is vacant: #{constituency_name}" else existing, updated_constituency = Constituency.load_tsv_line(line) if existing && updated_constituency existing.attributes = updated_constituency.attributes existing.save! elsif updated_constituency log "Cannot find constituency for member for line: #{line}" else # nothing to update end end rescue Exception => e log "Cannot set member_name on constituency for: #{line} | #{e.to_s}" end end end def load_constituencies return if file_not_found(CONSTITUENCY_FILE) Constituency.delete_all Slug.delete_all IO.foreach(CONSTITUENCY_FILE) do |line| constituency_id = line[0..2] constituency_name = line[3..(line.length-1)].strip Constituency.create :name=>constituency_name, :ons_id=>constituency_id end end def parse_postcodes source_file, output_file=POSTCODE_FILE return if file_not_found(source_file) start_timing blank_date = ' ' blank_code = ' ' new_line = "\n" space = ' ' post_codes = [] IO.foreach(source_file) do |line| termination_date = line[29..34] if termination_date == blank_date consistuency_code = line[69..71] unless consistuency_code == blank_code post_code = line[0..6] post_codes << post_code << space << consistuency_code post_codes << new_line end end end log_duration start_timing File.open(output_file,'w') do |file| file.write(post_codes.join('')) end log_duration end def load_postcodes group_size=1000 return if file_not_found(POSTCODE_FILE) index = 0 groups = 0 puts 'saving data to db' Postcode.delete_all columns = [:code, :constituency_id] total = `cat #{POSTCODE_FILE} | wc -l` total = total.strip.to_f include ActionView::Helpers::DateHelper post_codes = [] start_timing IO.foreach(POSTCODE_FILE) do |line| code = line[0..6].tr(' ','') constituency_id = line[8..10] post_codes << [code, constituency_id] index = index.next if (index % group_size) == 0 load_codes(post_codes) groups = groups.next percentage_complete = (group_size * groups) / total log_duration percentage_complete post_codes = [] end end # complete remaining load_codes(post_codes) log_duration 1.0 end def load_postcode_districts PostcodeDistrict.delete_all sql = "SELECT SUBSTRING(code, 1, LENGTH(code)-3) " + "AS district, constituency_id " + "FROM postcodes " + "GROUP BY district, constituency_id;" districts = PostcodeDistrict.find_by_sql(sql) districts.each do |district| PostcodeDistrict.create!(district.attributes) end end def load_manual_postcodes manual_codes = ManualPostcode.all manual_codes.each do |manual_code| Postcode.create :code => manual_code.code, :constituency_id => manual_code.constituency_id, :ons_id => manual_code.ons_id end end private def load_codes(post_codes) post_codes.each do |codes| if BlacklistedPostcode.find_by_code codes[0] puts " (ignoring blacklisted postcode - #{codes[0]})" else Postcode.create :code => codes[0], :ons_id => codes[1] end end end def is_vacant?(name) name == 'Vacant' end def log msg $stderr.puts msg end def file_not_found file_name if File.exist?(file_name) false else log "Data file not found: #{file_name}" true end end end
robertbrook/findyourmp
05c2f6c0ff89ff427899963e6eaf995e1cc76f20
removing emergency shutdown view code
diff --git a/app/views/admin/index.haml b/app/views/admin/index.haml index 8eed09a..71d4211 100644 --- a/app/views/admin/index.haml +++ b/app/views/admin/index.haml @@ -1,61 +1,54 @@ - @crumbtrail = 'Admin' - @title = 'Admin' %h3.padded_subheading Messages %p.text = link_to("Messages sent", url_for(:controller=>'admin',:action=>'sent') ) + ':' = number_with_delimiter(@sent_message_count) %p.text - if @waiting_to_be_sent_count > 0 = link_to "Messages <strong>waiting on the server</strong> to be sent: #{number_with_delimiter(@waiting_to_be_sent_count)}", url_for(:controller=>'admin',:action=>'waiting_to_be_sent') - else There are no messages waiting on the server to be sent. -if @current_user.admin? %p.text = link_to 'Check mail server status', url_for(:controller=>'admin',:action=>'mailserver_status') %h3.padded_subheading Members database %p.text = link_to 'Edit Members database information', edit_constituency_list_path | = link_to 'Edit constituencies', constituencies_path - if @current_user.admin? %h3.padded_subheading Postcode database %p.text = link_to 'Manage blacklist', blacklisted_postcodes_path | = link_to 'Manage non-ONS postcodes', manual_postcodes_path %h3.padded_subheading Users %p.text = 'You are logged in as <strong>' + @current_user.login + '</strong>' | = link_to 'Edit your account settings', edit_user_path(@current_user) - if @current_user.admin? %p.text= 'Your account has administrator rights.' %p.text = link_to 'Add new user', new_user_path | = link_to 'Edit users', users_path %h3.padded_subheading Memory use on server %p.text = link_to "Memory statistics", url_for(:controller=>'admin',:action=>'stats') - -- if @current_user.admin? - - %h3.padded_subheading Emergency shutdown - - %p.text - = link_to 'Shutdown site', shutdown_url diff --git a/app/views/admin/shutdown.haml b/app/views/admin/shutdown.haml deleted file mode 100644 index 201f5a4..0000000 --- a/app/views/admin/shutdown.haml +++ /dev/null @@ -1,22 +0,0 @@ -- @crumbtrail = link_to_admin_home -- @title = 'Emergency shutdown' - -%p.text - %span.warn If you continue, the whole site including this admin section will become unavailable - -%p.text - To restart the server, you will need to contact: - <br /><br /> - Server Contact <br /> - contact@contact.us - -%p.text - If you still wish to shut the site down, please click the button below - -- form_tag(shutdown_url, :method => :post) do - = submit_tag 'Shutdown site' - -%p.text - = '&nbsp;' -%p.text - = link_to 'Admin home', admin_url \ No newline at end of file
robertbrook/findyourmp
2973dd4b25da43cf4c3ed76dd77e0004aba77892
when creating postcode diff, move old diff file out the way; added analyze_postcode_update rake and cap task
diff --git a/config/deploy.rb b/config/deploy.rb index f756076..0f6a1ff 100644 --- a/config/deploy.rb +++ b/config/deploy.rb @@ -1,371 +1,384 @@ load File.expand_path(File.dirname(__FILE__) + '/virtualserver/deploy_secrets.rb') default_run_options[:pty] = true set :repository, "git://github.com/robertbrook/findyourmp.git" set :scm, :git ssh_options[:forward_agent] = true set :branch, "master" set :deploy_via, :remote_cache set :git_enable_submodules, 1 role :app, domain role :web, domain role :db, domain, :primary => true set :test_deploy, true set :master_data_file, 'NSPDC_AUG_2008_UK_100M.txt' namespace :deploy do set :user, deployuser set :password, deploypassword desc "Set sitemap cron job" task :set_sitemap_cron_job, :roles => :app do freq_in_minutes = ENV['freq_in_minutes'] unless freq_in_minutes puts puts 'must supply freq_in_minutes when setting cron job' puts 'USAGE: cap deploy:set_sitemap_cron_job freq_in_minutes=59' puts else cmd = "*/#{freq_in_minutes} * * * * cd #{deploy_to}/current; rake fymp:make_sitemap RAILS_ENV=production" set_cron_job cmd, 'make_sitemap' end end desc "Set delete stored messages cron job" task :set_delete_message_contents_cron_job, :roles => :app do weeks_to_keep = ENV['weeks_to_keep'] unless weeks_to_keep puts puts 'must supply weeks_to_keep when setting cron job' puts 'USAGE: cap deploy:set_delete_message_contents_cron_job weeks_to_keep=6' puts else cmd = "35 4 * * * cd #{deploy_to}/current; rake fymp:delete_stored_message_contents weeks_to_keep=#{weeks_to_keep} RAILS_ENV=production" set_cron_job cmd, 'delete_stored_message_contents' end end desc "Set delete stored messages cron job" task :set_delete_messages_cron_job, :roles => :app do months_to_keep = ENV['months_to_keep'] unless months_to_keep puts puts 'must supply months_to_keep when setting cron job' puts 'USAGE: cap deploy:set_delete_messages_cron_job months_to_keep=6' puts else cmd = "05 4 * * * cd #{deploy_to}/current; rake fymp:delete_stored_messages months_to_keep=#{months_to_keep} RAILS_ENV=production" set_cron_job cmd, 'delete_stored_messages' end end desc "Set ar_sendmail cron job" task :set_ar_sendmail_cron_job, :roles => :app do batch_size = ENV['batch_size'] freq_in_minutes = ENV['freq_in_mins'] unless batch_size && freq_in_minutes puts puts 'must supply batch_size and freq_in_minutes when setting cron job' puts 'USAGE: cap deploy:set_ar_sendmail_cron_job batch_size=100 freq_in_mins=5' puts else cmd = "*/#{freq_in_minutes} * * * * cd #{deploy_to}/current; rake fymp:run_ar_sendmail batch_size=#{batch_size} deploy_dir=#{deploy_to}/current environment=production" set_cron_job cmd, 'ar_sendmail' end end desc "Set db backup cron job" task :set_db_backup_cron_job, :roles => :app do cmd = "02 3 * * * #{deploy_to}/current; rake fymp:backup_db_s3 path=db/backup RAILS_ENV='production'" set_cron_job cmd, 'backup_database_to_S3' end desc "Set db backup cleanup cron job" task :set_db_backup_cleanup_cron_job, :roles => :app do cmd = "42 3 * * * cd #{deploy_to}/current; rake fymp:cleanup_db_backup files_to_keep=42 RAILS_ENV='production'" set_cron_job cmd, 'S3_backup_cleanup' end def set_cron_job cmd, identifier tmpname = "/tmp/appname-crontab.#{Time.now.strftime('%s')}" run "(crontab -l || echo '') | grep -v '#{identifier}' > #{tmpname}" run %Q|echo "#{cmd}" >> #{tmpname}| run "crontab #{tmpname}" run "rm #{tmpname}" end desc "Upload deployed database.yml" task :upload_deployed_database_yml, :roles => :app do data = File.read("config/virtualserver/deployed_database.yml") put data, "#{release_path}/config/database.yml", :mode => 0664 end desc "Upload deployed mailer.yml" task :upload_deployed_mailer_yml, :roles => :app do data = File.read("config/virtualserver/deployed_mailer.yml") put data, "#{release_path}/config/mailer.yml", :mode => 0664 end desc "Upload S3 data files" task :put_s3_data, :roles => :app do data = File.read("config/virtualserver/deployed_s3.yml") put data, "#{release_path}/config/s3.yml", :mode => 0664 data = File.read("config/virtualserver/fymp-public.pem") put data, "#{release_path}/config/fymp-public.pem", :mode => 0664 end task :link_to_data, :roles => :app do data_dir = "#{deploy_to}/shared/cached-copy/data" run "if [ -d #{data_dir} ]; then ln -s #{data_dir} #{release_path}/data ; else echo cap deploy put_data first ; fi" end desc 'put data to server' task :put_data, :roles => :app do data_dir = "#{deploy_to}/shared/cached-copy/data" if overwrite run "if [ -d #{data_dir} ]; then echo #{data_dir} exists ; else mkdir #{data_dir} ; fi" run "rm #{data_dir}/FYMP_all.txt" put_data data_dir, 'FYMP_all.txt' run "rm #{data_dir}/constituencies.txt" put_data data_dir, 'constituencies.txt' if test_deploy run "rm #{data_dir}/postcodes.txt" put_data data_dir, 'postcodes.txt' else run "rm #{data_dir}/#{master_data_file}" put_data data_dir, "#{master_data_file}" end end log_dir = "#{deploy_to}/shared/log" run "if [ -d #{log_dir} ]; then echo #{log_dir} exists ; else mkdir #{log_dir} ; fi" run "if [ -d #{deploy_to}/shared/system ]; then echo exists ; else mkdir #{deploy_to}/shared/system ; fi" rc_rake_file = "#{release_path}/vendor/plugins/resource_controller/tasks/gem.rake" run "if [ -f #{rc_rake_file} ]; then mv #{rc_rake_file} #{rc_rake_file}.bak ; else echo not found ; fi" end def put_data data_dir, file data_file = "#{data_dir}/#{file}" run "if [ -f #{data_file} ]; then echo exists ; else echo not there ; fi" do |channel, stream, message| if message.strip == 'not there' puts "sending #{file}" data = File.read("data/#{file.gsub('\\','')}") put data, "#{data_file}", :mode => 0664 else puts "#{file} #{message}" end end end def prompt_for_value(var) puts "" puts "*************************************" answer = "" message = "Do you want to overwrite the data?\n\nIf yes, type: YES, OVERWRITE!!\n(To continue without overwriting, just hit return)\n" answer = Capistrano::CLI.ui.ask(message) if answer == "YES, OVERWRITE!!" set var, true else set var, false end end def check_correct_ip puts "" puts "*************************************" answer = "n" servers = roles[:app].servers.uniq!.join(", ") message = "You are about to deploy to: #{servers} do you want to continue? (y/N)\n" answer = Capistrano::CLI.ui.ask(message) answer = "n" if answer == "" unless answer.downcase == 'y' # answer.first.downcase == "y" raise "Deploy aborted by user" end end desc "Restarting apache and clearing the cache" task :restart, :roles => :app do sudo "/usr/sbin/apache2ctl restart" run "cd #{current_path}; rake fymp:cache:expire_pages RAILS_ENV='production'" end desc "Perform rake tasks" task :rake_tasks, :roles => :app, :except => { :no_release => true } do run "cd #{current_path}; rake db:migrate RAILS_ENV='production'" if overwrite run "cd #{current_path}; rake fymp:constituencies RAILS_ENV='production'" run "cd #{current_path}; rake fymp:members RAILS_ENV='production'" unless test_deploy postcode_source = "" message = "Which postcodes data file?\n\ne.g. data/NSPDF_MAY_2009_UK_1M_FP.txt\n" postcode_source = Capistrano::CLI.ui.ask(message) if File.exist?(postcode_source) run "cd #{current_path}; rake fymp:parse_postcodes source=#{postcode_source} RAILS_ENV='production'" else raise "cannot find postcodes file: #{postcode_source}" end end run "cd #{current_path}; rake fymp:populate RAILS_ENV='production'" end run "cd #{current_path}; rake fymp:load_manual_postcodes RAILS_ENV='production'" run "cd #{current_path}; rake fymp:load_postcode_districts RAILS_ENV='production'" end task :check_folder_setup, :roles => :app do if is_first_run? set :overwrite, true else prompt_for_value(:overwrite) end puts 'checking folders...' run "if [ -d #{deploy_to} ]; then echo exists ; else echo not there ; fi" do |channel, stream, message| if message.strip == 'not there' folders = deploy_to.split("/") folderpath = "" folders.each do |folder| if folder != "" folderpath << "/" << folder run "if [ -d #{folderpath} ]; then echo exists ; else echo not there ; fi" do |channel, stream, message| if message.strip == 'not there' sudo "mkdir #{folderpath}" end end end end sudo "chown #{user} #{folderpath}" run "mkdir #{folderpath}/releases" end end puts 'checks complete!' end task :check_server, :roles => :app do check_correct_ip run "git --help" do |channel, stream, message| if message =~ /No such file or directory/ raise "You need to install git before proceeding" end end end task :check_site_setup, :roles => :app do if is_first_run? site_setup else rake_tasks end end task :site_setup, :roles => :app do puts 'entering first time only setup...' sudo "touch /etc/apache2/sites-available/#{application}" sudo "chown #{user} /etc/apache2/sites-available/#{application}" source = File.read("config/findyourmp.apache.example") data = "" source.each { |line| line.gsub!("[RELEASE-PATH]", deploy_to) data << line } put data, "/etc/apache2/sites-available/#{application}", :mode => 0664 sudo "sudo ln -s -f /etc/apache2/sites-available/#{application} /etc/apache2/sites-enabled/000-default" run "sudo mysql -uroot -p", :pty => true do |ch, stream, data| # puts data if data =~ /Enter password:/ ch.send_data(sql_server_password + "\n") else ch.send_data("create database #{application}_production CHARACTER SET utf8 COLLATE utf8_unicode_ci; \n") ch.send_data("create database #{application}_development CHARACTER SET utf8 COLLATE utf8_unicode_ci; \n") ch.send_data("create user '#{sql_backup_user}'@'localhost' identified by '#{sql_backup_password}'; \n") ch.send_data("grant SELECT, LOCK TABLES on #{application}_production.* to '#{sql_backup_user}'@'localhost'; \n") ch.send_data("grant SHOW DATABASES, RELOAD on *.* to '#{sql_backup_user}'@'localhost'; \n") ch.send_data("FLUSH PRIVILEGES; \n") ch.send_data("exit \n") end end sudo "gem sources -a http://gems.github.com" sudo "gem install hpricot" sudo "gem install morph" sudo "gem install unicode" sudo "gem install treetop" sudo "gem install term-ansicolor" sudo "gem install aws-s3 --version '0.5.1'" sudo "gem install adzap-ar_mailer --version '2.1.5'" sudo "cp /var/lib/gems/1.8/bin/ar_sendmail /usr/local/bin/ar_sendmail" rake_tasks sudo "/usr/sbin/apache2ctl restart" puts 'first time only setup complete!' end [:start, :stop].each do |t| desc "#{t} task is not used with mod_rails" task t, :roles => :app do ; end end def is_first_run? run "if [ -f /etc/apache2/sites-available/#{application} ]; then echo exists ; else echo not there ; fi" do |channel, stream, message| if message.strip == 'not there' return true else return false end end end - desc "Perform rake tasks" + desc "Update postcodes" task :update_postcodes, :roles => :app do file = "data/diff_postcodes.txt" if File.exist?(file) data = File.read(file) put data, "#{current_path}/data/diff_postcodes.txt", :mode => 0664 run "cd #{current_path}; rake fymp:update_postcodes RAILS_ENV='production'" else puts 'USAGE EXAMPLE:' puts 'rake fymp:diff_postcodes old=data/NSPDF_FEB_2009_UK_1M.txt new=data/NSPDF_MAY_2009_UK_1M_FP.txt' puts 'cap deploy:update_postcodes' end end + desc "Analyze postcodes" + task :analyze_postcode_update, :roles => :app do + file = "data/diff_postcodes.txt" + if File.exist?(file) + data = File.read(file) + put data, "#{current_path}/data/diff_postcodes.txt", :mode => 0664 + run "cd #{current_path}; rake fymp:analyze_postcode_update RAILS_ENV='production'" + else + puts 'USAGE EXAMPLE:' + puts 'rake fymp:diff_postcodes old=data/NSPDF_FEB_2009_UK_1M.txt new=data/NSPDF_MAY_2009_UK_1M_FP.txt' + puts 'cap deploy:analyze_postcode_update' + end + end end before 'deploy:update_code', 'deploy:check_server', 'deploy:check_folder_setup' after 'deploy:update_code', 'deploy:upload_deployed_database_yml', 'deploy:upload_deployed_mailer_yml', 'deploy:put_s3_data', 'deploy:put_data', 'deploy:link_to_data' after 'deploy:symlink', 'deploy:check_site_setup' namespace :fymp do namespace :cache do set :remote_rake_cmd, "/usr/local/bin/rake" desc "Expire page cache" task :expire_pages, :roles => :app do run("export RAILS_ENV=production; cd #{deploy_to}/current; #{remote_rake_cmd} fymp:cache:expire_pages") end end end diff --git a/lib/data_loader.rb b/lib/data_loader.rb index 953017d..63162f2 100644 --- a/lib/data_loader.rb +++ b/lib/data_loader.rb @@ -1,296 +1,344 @@ require File.expand_path(File.dirname(__FILE__) + '/timer') module FindYourMP; end module FindYourMP::DataLoader include FindYourMP::Timer DATA_DIR = File.expand_path(File.dirname(__FILE__) + '/../data') MEMBER_FILE = "#{DATA_DIR}/FYMP_all.txt" CONSTITUENCY_FILE = "#{DATA_DIR}/constituencies.txt" POSTCODE_FILE = "#{DATA_DIR}/postcodes.txt" def diff_postcodes old_file, new_file old_postcodes = "#{DATA_DIR}/old_postcodes.txt" new_postcodes = "#{DATA_DIR}/new_postcodes.txt" parse_postcodes old_file, old_postcodes parse_postcodes new_file, new_postcodes diff_file = "#{DATA_DIR}/diff_postcodes.txt" + if File.exist?(diff_file) + cmd = "mv #{diff_file} #{diff_file}.#{Time.now.to_i.to_s}" + puts cmd + `#{cmd}` + end + cmd = "diff #{old_postcodes} #{new_postcodes} > #{diff_file}" puts cmd - `#{cmd}` unless File.exist?(diff_file) + `#{cmd}` end - def update_postcodes + def determine_postcode_changes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if file_not_found(diff_file) puts "Generate or upload #{diff_file}" return end to_delete = {} to_create = {} to_update = {} IO.foreach(diff_file) do |line| parts = line.strip.split(' ') indicator = parts[0] if indicator[/(<|>)/] ons_id = parts.pop postcode = parts.join(' ').sub(indicator, '').strip if indicator == '<' to_delete[postcode] = ons_id elsif indicator == '>' to_create[postcode] = ons_id end end end to_create.keys.each do |postcode| if to_delete.delete(postcode) ons_id = to_create.delete(postcode) to_update[postcode] = ons_id end end puts 'to_delete ' + to_delete.size.to_s + ' e.g. ' + to_delete.to_a.first.inspect puts 'to_update ' + to_update.size.to_s + ' e.g. ' + to_update.to_a.first.inspect puts 'to_create ' + to_create.size.to_s + ' e.g. ' + to_create.to_a.first.inspect puts 'checking we have constituencies... ' (to_delete.values + to_update.values + to_create.values).flatten.uniq.each do |ons_id| unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) raise "unexpected constituency id #{ons_id}" unless constituency end end puts 'all constituencies found' + return [to_delete, to_update, to_create] + end + + def update_postcodes + to_delete, to_update, to_create = determine_postcode_changes # puts "Update database? y/n" # answer = STDIN.gets # if answer.strip == 'y' do_postcode_update to_delete, to_update, to_create # else # puts 'exiting without database update' # end end def ignore_ons_id?(ons_id) ons_id == '800' || ons_id == '900' end + def analyze_postcode_update + to_delete, to_update, to_create = determine_postcode_changes + + already_deleted = [] + to_delete.each do |postcode, ons_id| + already_deleted << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) + end + puts "TO DELETE, BUT ALREADY DELETED: #{already_deleted.size}" + + missing_updates = [] + to_update.each do |postcode, ons_id| + missing_updates << [postcode, ons_id] unless Postcode.exists?(:code => postcode.sub(' ','')) + end + puts "TO UPDATE, BUT MISSING FROM DB: #{missing_updates.size}" + + already_there = [] + to_create.each do |postcode, ons_id| + already_there << [postcode, ons_id] if Postcode.exists?(:code => postcode.sub(' ','')) + end + puts "TO CREATE, BUT ALREADY IN DB: #{already_there.size}" + end + def do_postcode_update to_delete, to_update, to_create puts 'do_postcode_update...' total = (to_delete.size + to_update.size + to_create.size).to_f count = 0 include ActionView::Helpers::DateHelper start_timing to_delete.each do |postcode, ons_id| if post_code = Postcode.find_by_code(postcode.sub(' ','')) post_code.destroy count = count.next log_duration count / total else - raise "cannot delete postcode, as it was not in database: #{postcode}" + warn "cannot delete postcode, as it was not in database: #{postcode}" end end to_update.each do |postcode, ons_id| - if (post_code = Postcode.find_by_code(postcode.sub(' ',''))) && (ignore_ons_id?(ons_id) || constituency = Constituency.find_by_ons_id(ons_id)) - post_code.ons_id = ons_id.strip.to_i - if constituency - post_code.constituency_id = constituency.id - else - post_code.constituency_id = nil + post_code = Postcode.find_by_code(postcode.sub(' ','')) + + if post_code + unless ignore_ons_id?(ons_id) + constituency = Constituency.find_by_ons_id(ons_id) + if constituency.nil? + raise "cannot update postcode, as constituency was not in database: #{postcode} #{ons_id}" + end end - post_code.save + + # if BlacklistedPostcode.find_by_code postcode.sub(' ','') + # puts " (deleting blacklisted postcode - #{postcode})" + # post_code.destroy + # else + post_code.ons_id = ons_id.strip.to_i + if constituency + post_code.constituency_id = constituency.id + else + post_code.constituency_id = nil + end + post_code.save + # end + count = count.next log_duration count / total else - raise "cannot delete postcode, as it was not in database: #{postcode} #{ons_id}" + raise "cannot update postcode, as it was not in database: #{postcode} #{ons_id}" end end to_create.each do |postcode, ons_id| begin if Postcode.exists?(:code => postcode.sub(' ','')) - raise 'exists ' + postcode - elsif BlacklistedPostcode.find_by_code postcode.sub(' ','') - puts " (ignoring blacklisted postcode - #{postcode})" + warn 'exists ' + postcode + # elsif BlacklistedPostcode.find_by_code postcode.sub(' ','') + # puts " (ignoring blacklisted postcode - #{postcode})" else Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id.strip.to_i end rescue Exception => e raise e end count = count.next log_duration count / total end log_duration end def load_members member_file member_file = MEMBER_FILE unless member_file return if file_not_found(member_file) lines = [] IO.foreach(member_file) do |line| line.strip! lines << line unless(line.blank? || line[/Constituency/]) end lines.each do |line| begin parts = line.split("\t") constituency_name = parts[0].strip member_name = parts[1].strip if is_vacant?(member_name) log "Constituency is vacant: #{constituency_name}" else existing, updated_constituency = Constituency.load_tsv_line(line) if existing && updated_constituency existing.attributes = updated_constituency.attributes existing.save! elsif updated_constituency log "Cannot find constituency for member for line: #{line}" else # nothing to update end end rescue Exception => e log "Cannot set member_name on constituency for: #{line} | #{e.to_s}" end end end def load_constituencies return if file_not_found(CONSTITUENCY_FILE) Constituency.delete_all Slug.delete_all IO.foreach(CONSTITUENCY_FILE) do |line| constituency_id = line[0..2] constituency_name = line[3..(line.length-1)].strip Constituency.create :name=>constituency_name, :ons_id=>constituency_id end end def parse_postcodes source_file, output_file=POSTCODE_FILE return if file_not_found(source_file) start_timing blank_date = ' ' blank_code = ' ' new_line = "\n" space = ' ' post_codes = [] IO.foreach(source_file) do |line| termination_date = line[29..34] if termination_date == blank_date consistuency_code = line[69..71] unless consistuency_code == blank_code post_code = line[0..6] post_codes << post_code << space << consistuency_code post_codes << new_line end end end log_duration start_timing File.open(output_file,'w') do |file| file.write(post_codes.join('')) end log_duration end def load_postcodes group_size=1000 return if file_not_found(POSTCODE_FILE) index = 0 groups = 0 puts 'saving data to db' Postcode.delete_all columns = [:code, :constituency_id] total = `cat #{POSTCODE_FILE} | wc -l` total = total.strip.to_f include ActionView::Helpers::DateHelper post_codes = [] start_timing IO.foreach(POSTCODE_FILE) do |line| code = line[0..6].tr(' ','') constituency_id = line[8..10] post_codes << [code, constituency_id] index = index.next if (index % group_size) == 0 load_codes(post_codes) groups = groups.next percentage_complete = (group_size * groups) / total log_duration percentage_complete post_codes = [] end end # complete remaining load_codes(post_codes) log_duration 1.0 end def load_postcode_districts PostcodeDistrict.delete_all sql = "SELECT SUBSTRING(code, 1, LENGTH(code)-3) " + "AS district, constituency_id " + "FROM postcodes " + "GROUP BY district, constituency_id;" districts = PostcodeDistrict.find_by_sql(sql) districts.each do |district| PostcodeDistrict.create!(district.attributes) end end - + def load_manual_postcodes manual_codes = ManualPostcode.all manual_codes.each do |manual_code| Postcode.create :code => manual_code.code, :constituency_id => manual_code.constituency_id, :ons_id => manual_code.ons_id end end private def load_codes(post_codes) post_codes.each do |codes| if BlacklistedPostcode.find_by_code codes[0] puts " (ignoring blacklisted postcode - #{codes[0]})" else Postcode.create :code => codes[0], :ons_id => codes[1] end end end def is_vacant?(name) name == 'Vacant' end def log msg $stderr.puts msg end def file_not_found file_name if File.exist?(file_name) false else log "Data file not found: #{file_name}" true end end end diff --git a/lib/tasks/parse.rake b/lib/tasks/parse.rake index 5b22cab..bdf915e 100644 --- a/lib/tasks/parse.rake +++ b/lib/tasks/parse.rake @@ -1,73 +1,78 @@ require File.expand_path(File.dirname(__FILE__) + '/../data_loader') require File.expand_path(File.dirname(__FILE__) + '/../commons_member_biographies') require File.expand_path(File.dirname(__FILE__) + '/../cache_writer') require File.expand_path(File.dirname(__FILE__) + '/../constituency_upmystreet_links') namespace :fymp do include FindYourMP::DataLoader include FindYourMP::CacheWriter desc "Populate data for constituencies in DB" task :constituencies => :environment do load_constituencies end desc "Populate data for members in DB" task :members => :environment do file = ENV['file'] load_members file end desc "Create cache of all postcode pages" task :make_cache => :environment do make_cache end desc "Parse data file for postcode and constituency ID *only*" task :parse_postcodes do source_file = ENV['source'] if source_file parse_postcodes source_file else puts 'USAGE: rake fymp:parse source=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end - + desc "Update postcodes from data files for postcode and constituency ID *only*" task :diff_postcodes => :environment do old_file = ENV['old'] new_file = ENV['new'] if old_file && new_file diff_postcodes old_file, new_file else puts 'USAGE: rake fymp:diff_postcodes old=data/NSPDF_FEB_2009_UK_1M.txt new=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end + desc "Only analyze potential postcode update and log db discrepancies" + task :analyze_postcode_update => :environment do + analyze_postcode_update + end + desc "Update postcodes from data files for postcode and constituency ID *only*" task :update_postcodes => :environment do puts 'USAGE: rake fymp:update_postcodes' update_postcodes end desc "Populate data for postcode and constituency ID in DB" task :populate => :environment do load_postcodes end desc "Populate the postcode districts table" task :load_postcode_districts => :environment do load_postcode_districts end desc "Populate the manually added postcodes" task :load_manual_postcodes => :environment do load_manual_postcodes end desc "Populate the upmystreet lookup table" task :load_upmystreet_lookup => :environment do load_upmystreetcodes end end
robertbrook/findyourmp
3bf80e49d8f1c76ac21f12654ffb14d5c546826b
tidier uri value when host is on port 80
diff --git a/app/models/constituency.rb b/app/models/constituency.rb index 2937166..8ed63a8 100755 --- a/app/models/constituency.rb +++ b/app/models/constituency.rb @@ -1,202 +1,206 @@ class Constituency < ActiveRecord::Base include ActionController::UrlWriter has_friendly_id :name, :use_slug => true, :strip_diacritics => true has_many :postcodes has_many :postcode_districts has_many :messages validate :valid_email? class << self def all_constituencies all.select{|c| c.name != 'Example'} end def remove_quotes text text.strip[/^"?([^"]+)"?$/,1] end def load_tsv_line line parts = line.split("\t") constituency_name = remove_quotes(parts[0]) member_name = remove_quotes(parts[1]) member_party = remove_quotes(parts[2]) member_bio_url = remove_quotes(parts[3]) member_contact = remove_quotes(parts[4]) member_website = remove_quotes(parts[5]) member_contact = "" unless member_contact existing = Constituency.find_by_constituency_name(constituency_name) new_constituency = nil if existing non_matching = (existing.member_name != member_name || existing.member_party != member_party || existing.member_biography_url != member_bio_url) non_matching = non_matching || ( member_contact[/http:\/\//] ? (existing.member_requested_contact_url.to_s.strip != member_contact.to_s.strip) : (existing.member_email.to_s.strip != member_contact.to_s.strip) ) if non_matching new_constituency = Constituency.new(existing.attributes) new_constituency.member_name = member_name new_constituency.member_party = member_party new_constituency.member_biography_url = member_bio_url if member_contact[/http:\/\//] new_constituency.member_requested_contact_url = member_contact else new_constituency.member_email = member_contact.chomp('.') end new_constituency.member_website = member_website end [existing, new_constituency] else [nil, nil] end end def find_all_constituency_and_member_matches term term = term.squeeze(' ').gsub('"','') constituencies = Constituency.find_all_name_or_member_name_matches(term) members = constituencies.clone if term[/[A-Z][a-z].*/] constituencies = constituencies.select { |c| c.name.include? term } members = members.select { |c| c.member_name.include? term } else constituencies = constituencies.select { |c| c.name.downcase.include? term.downcase } members = members.select { |c| c.member_name? && c.member_name.downcase.include?(term.downcase) } end constituencies = constituencies.sort_by(&:name) members = members.sort_by(&:member_name) return [constituencies, members] end def find_all_name_or_member_name_matches term term = term.squeeze(' ').gsub('"','') matches_name_or_member_name = %Q|name like "%#{term}%" or | + %Q|(member_name like "%#{term}%" and member_visible = 1)| constituencies = find(:all, :conditions => matches_name_or_member_name) constituencies.delete_if{|c| c.name == 'Example'} if case_sensitive(term) constituencies.delete_if do |c| !c.name.include?(term) && !c.member_name.include?(term) end end constituencies end def case_sensitive term term.gsub('"','')[/^([A-Z][a-z]+[ ]+)*([A-Z][a-z]+)$/] ? true : false end def find_by_constituency_name name name.gsub!('St ', 'St. ') name.gsub!(' - ','-') if name[/^(.+), City of$/] name = "City of #{$1}" end constituency = find_by_name(name) unless constituency name.gsub!('&', 'and') if name == "Regent's Park and Kensington North" name = "Regent's Park and North Kensington" end if name[/^(.+), The$/] name = "The #{$1}" end name.tr!('-', ' ') name.gsub!('ô','o') name.gsub!('and#244;', 'o') constituency = find_by_name(name) end unless constituency puts "" puts "not found: #{name}" end constituency end end def show_message_form? member_name? && member_email? && !member_requested_contact_url? end def code if ons_id.nil? '' elsif ons_id < 10 "00#{ons_id}" elsif ons_id < 100 "0#{ons_id}" else ons_id.to_s end end def no_sitting_member? (!member_name?) || (!member_visible) end def to_tsv_line %Q|"#{name}"\t"#{member_name}"\t"#{member_party}"\t"#{member_biography_url}"\t"#{member_email}"\t"#{member_website}"| end def to_json host, port if no_sitting_member? %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "No sitting member", "member_party": "", "member_biography_url": "", "member_website": "", "uri": "#{object_url(host, port, "json")}" } }| else %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "#{member_name}", "member_party": "#{member_party}", "member_biography_url": "#{member_biography_url}", "member_website": "#{member_website}", "uri": "#{object_url(host, port, "json")}" } }| end end def to_text host, port, format="txt" if no_sitting_member? %Q|constituency_name: #{name}\nmember_name: No sitting member\nmember_party: \nmember_biography_url: \nmember_website: \nuri: #{object_url(host, port, format)}| else %Q|constituency_name: #{name}\nmember_name: #{member_name}\nmember_party: #{member_party}\nmember_biography_url: #{member_biography_url}\nmember_website: #{member_website}\nuri: #{object_url(host, port, format)}| end end def to_csv host, port headers = 'constituency_name,member_name,member_party,member_biography_url,member_website,uri' values = to_csv_value(host, port) "#{headers}\n#{values}\n" end def to_csv_value host, port if no_sitting_member? %Q|"#{name}","No sitting member","","","","#{object_url(host, port, format, "csv")}"| else %Q|"#{name}","#{member_name}","#{member_party}","#{member_biography_url}","#{member_website}","#{object_url(host, port, "csv")}"| end end def to_output_yaml host, port "---\n#{to_text(host, port, "yaml")}" end def member_attribute_changed? attribute, constituency send(attribute).to_s.strip != constituency.send(attribute).to_s.strip end private def valid_email? unless member_email.blank? begin self.member_email = MessageMailer.parse_email(member_email).address rescue errors.add_to_base("Member email must be a valid email") end end end def object_url host, port, format=nil - url_for :host=> host, :port=> port, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false + if port.to_s == "80" + url_for :host=> host, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false + else + url_for :host=> host, :port=> port, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false + end end end diff --git a/app/models/postcode.rb b/app/models/postcode.rb index 82ebade..f2f913d 100644 --- a/app/models/postcode.rb +++ b/app/models/postcode.rb @@ -1,101 +1,105 @@ class Postcode < ActiveRecord::Base include ActionController::UrlWriter before_validation_on_create :populate_constituency_id validates_uniqueness_of :code validates_presence_of :ons_id belongs_to :constituency delegate :member_name, :to => :constituency class << self def find_postcode_by_code search_term return nil unless search_term code = String.new search_term code.strip! code.upcase! code.tr!(' ','') find_by_code(code, :include => :constituency) end end def in_constituency? constituency self.constituency_id == constituency.id end def constituency_name if constituency constituency.name else raise "constituency not found for constituency_id: #{constituency_id}, postcode: #{code}" end end def code_prefix code[0..-4] end def code_with_space suffix = code[-3,3] "#{code_prefix} #{suffix}" end def to_json host, port member = member_name ? %Q|, "member_name": "#{member_name.strip}"| : '' %Q|{"postcode": {"code": "#{code_with_space}", "constituency_name": "#{constituency_name}"#{member}, "uri": "#{object_url(host, port, "json")}"} }| end def to_text host, port, format="txt" member = member_name ? %Q|\nmember_name: #{member_name.strip}| : '' %Q|postcode: #{code_with_space}\nconstituency_name: #{constituency_name}#{member}\nuri: #{object_url(host, port, format)}\n| end def to_csv host, port headers = 'postcode,constituency_name' values = %Q|"#{code_with_space}","#{constituency_name}"| if member_name headers += ',member_name' values += %Q|,"#{member_name.strip}"| end headers += ",uri" values += %Q|,"#{object_url(host, port, "csv")}"| "#{headers}\n#{values}\n" end def to_output_yaml host, port "---\n#{to_text(host, port, "yaml")}" end def blacklist blacklisted = BlacklistedPostcode.find_by_code(code) unless blacklisted blacklisted = BlacklistedPostcode.create :code => code, :constituency_id => constituency_id ,:ons_id => ons_id if blacklisted self.delete else return false end else self.delete end true end private def populate_constituency_id if ons_id if constituency = Constituency.find_by_ons_id(ons_id) self.constituency_id = constituency.id # else # errors.add('constituency_id', "Can't find a constituency corresponding to ONS ID: #{ons_id}") end end end def object_url host, port, format=nil - url_for :host=> host, :port=> port, :controller=>"postcodes", :action=>"show", :postcode => code, :format => format, :only_path => false + if port.to_s == "80" + url_for :host=> host, :controller=>"postcodes", :action=>"show", :postcode => code, :format => format, :only_path => false + else + url_for :host=> host, :port=> port, :controller=>"postcodes", :action=>"show", :postcode => code, :format => format, :only_path => false + end end end
robertbrook/findyourmp
c32befaf6999d26686cd88df0516971c43a32dc3
fixed bug where non-html and xml views returned the hostname and port values in the uri field
diff --git a/app/controllers/api_controller.rb b/app/controllers/api_controller.rb index f9dc03e..ee7e336 100644 --- a/app/controllers/api_controller.rb +++ b/app/controllers/api_controller.rb @@ -1,214 +1,219 @@ class ApiController < ApplicationController def index @host = request.host unless request.port == 80 @host += ':' + request.port.to_s end end def search params[:search_term] = params[:q] unless params[:q].blank? search_term = params[:search_term] params[:format] = params[:f] unless params[:f].blank? search_format = params[:format] if search_term postcode_districts = PostcodeDistrict.find_all_by_district(search_term) unless postcode_districts.empty? show_postcode_districts(postcode_districts, search_format) else postcode = Postcode.find_postcode_by_code(search_term) if postcode show_postcode(postcode, search_term, search_format) else stripped_term = search_term.strip.squeeze(' ').gsub('"','') if stripped_term.size > 2 constituencies = Constituency.find_all_name_or_member_name_matches(stripped_term) if constituencies.empty? flash[:not_found] = "not_found" flash[:last_search_term] = search_term show_error(search_format) elsif constituencies.size == 1 show_constituencies([constituencies.first], stripped_term, search_format) else show_constituencies(constituencies, stripped_term, search_format) end else flash[:not_found] = "Sorry: we need more than two letters to search" flash[:last_search_term] = search_term show_error(search_format) end end end else flash[:not_found] = "Sorry: the API did not recognise this parameter" show_error(search_format) end end def postcodes code = params[:code] district = params[:district] params[:format] = params[:f] unless params[:f].blank? search_format = params[:format] if district postcode_districts = PostcodeDistrict.find_all_by_district(district) unless postcode_districts.empty? show_postcode_districts(postcode_districts, search_format) else flash[:not_found] = "Sorry: we couldn't find a postcode when we searched for #{district}. Please go back and check the postcode you entered, and ensure you have entered a complete postcode. If you are an expatriate, in an overseas territory, a Crown dependency or in the Armed Forces without a postcode, this service cannot be used to find your MP." show_error(search_format) end elsif code postcode = Postcode.find_postcode_by_code(code) if postcode show_postcode(postcode, code, search_format) else flash[:not_found] = "Sorry: we couldn't find a postcode when we searched for #{code}. Please go back and check the postcode you entered, and ensure you have entered a complete postcode. If you are an expatriate, in an overseas territory, a Crown dependency or in the Armed Forces without a postcode, this service cannot be used to find your MP." show_error(search_format) end else flash[:not_found] = "Sorry: the API did not recognise this parameter" show_error(search_format) end end def constituencies member_name = params[:member] constituency_name = params[:constituency] ons_id = params[:ons_id] params[:format] = params[:f] unless params[:f].blank? search_format = params[:format] if ons_id ons_id = ons_id.strip.gsub('"','') constituency = Constituency.find_by_ons_id(ons_id) if constituency show_constituency(constituency, search_format) else flash[:not_found] = "Sorry: we couldn't find a constituency with an ONS id of #{ons_id}" show_error(search_format) end elsif member_name member_name = member_name.strip.gsub('"','') constituency = Constituency.find_by_member_name(member_name) if constituency show_constituency(constituency, search_format) else flash[:not_found] = "Sorry: we couldn't find a constituency with a member name of #{member_name}" show_error(search_format) end elsif constituency_name constituency_name = constituency_name.strip.gsub('"','') constituency = Constituency.find_by_name(constituency_name) if constituency show_constituency(constituency, search_format) else flash[:not_found] = "Sorry: we couldn't find a constituency with a constituency name of #{constituency_name}" show_error(search_format) end else flash[:not_found] = "Sorry: the API did not recognise this parameter" show_error(search_format) end end private def show_postcode postcode, search_term, format + host = request.host + port = request.port + show_constituencies([postcode.constituency], nil, format) # @postcode = postcode # @constituency = postcode.constituency # respond_to do |format| # format.html { render :template => '/postcodes/show', :postcode => postcode } # format.xml { render :template => '/postcodes/show', :postcode => postcode, :layout => false } - # format.json { render :json => postcode.to_json } - # format.js { render :json => postcode.to_json } - # format.text { render :text => postcode.to_text } - # format.csv { render :text => postcode.to_csv } - # format.yaml { render :text => postcode.to_output_yaml } + # format.json { render :json => postcode.to_json(host, port) } + # format.js { render :json => postcode.to_json(host, port) } + # format.text { render :text => postcode.to_text(host, port) } + # format.csv { render :text => postcode.to_csv(host, port) } + # format.yaml { render :text => postcode.to_output_yaml(host, port) } # end end def show_postcode_districts postcode_districts, format @search_term = params[:q] respond_to do |format| @postcode_districts = postcode_districts @constituencies = postcode_districts.collect { |postcode| postcode.constituency } format.html { render :template => '/postcodes/show' } format.xml { render :template => '/constituencies/show', :layout => false } format.json { render :json => results_to_json(@constituencies, []) } format.js { render :json => results_to_json(@constituencies, []) } format.text { render :text => results_to_text(@constituencies, []) } format.csv { render :text => results_to_csv(@constituencies, []) } format.yaml { render :text => results_to_yaml(@constituencies, []) } end end def show_constituency constituency, format @constituency = constituency + host = request.host + port = request.port respond_to do |format| format.html { render :template => '/constituencies/show' } format.xml { render :template => '/constituencies/show.xml.haml', :layout => false } - format.json { render :json => constituency.to_json } - format.js { render :json => constituency.to_json } - format.text { render :text => constituency.to_text } - format.csv { render :text => constituency.to_csv } - format.yaml { render :text => constituency.to_output_yaml } + format.json { render :json => constituency.to_json(host, port) } + format.js { render :json => constituency.to_json(host, port) } + format.text { render :text => constituency.to_text(host, port) } + format.csv { render :text => constituency.to_csv(host, port) } + format.yaml { render :text => constituency.to_output_yaml(host, port) } end end def show_constituencies constituencies, search_term, format @constituencies = constituencies if search_term @members = constituencies.clone if search_term[/[A-Z][a-z].*/] @constituencies.delete_if { |c| !(c.name.include? search_term) } @members.delete_if { |c| c.member_name.blank? || !(c.member_name.include? search_term) } else @constituencies.delete_if { |c| !(c.name.downcase.include? search_term.downcase) } @members.delete_if { |c| c.member_name.blank? || !(c.member_name.downcase.include? search_term.downcase) } end else @members = [] end respond_to do |format| format.html { render :template => '/constituencies/show' } format.xml { render :template => '/constituencies/show.xml.haml', :layout => false } format.json { render :json => results_to_json(@constituencies, @members, params[:callback]) } format.js { render :json => results_to_json(@constituencies, @members, params[:callback]) } format.text { render :text => results_to_text(@constituencies, @members) } format.csv { render :text => results_to_csv(@constituencies, @members) } format.yaml { render :text => results_to_yaml(@constituencies, @members) } end end def show_error format @error_message = flash[:not_found] flash[:not_found] = nil unless format == 'html' respond_to do |format| format.html { render :template => '/api/index'} format.xml { render :template => '/constituencies/show.xml.haml', :layout => false } format.json { render :json => results_to_json([], []) } format.js { render :json => results_to_json([], []) } format.text { render :text => results_to_text([], []) } format.csv { render :text => results_to_csv([], []) } format.yaml { render :text => results_to_yaml([], []) } end end end \ No newline at end of file diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 79da0c7..569d25c 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,152 +1,161 @@ # Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base filter_parameter_logging :password, :password_confirmation, :message, :constituency_list helper_method :current_user_session, :is_admin? def render_not_found message='Page not found.' @title = "Page cannot be found (404 error)" @crumbtrail = "Error: page cannot be found" render :template => 'public/404.html', :status => 404 end private def render_unauthorized render :text => 'Unauthorized', :status => 401 end def respond_unauthorized_if_not_admin render_unauthorized unless is_admin? end def redirect_to_root_if_not_admin redirect_to '/', :status => 303 unless is_admin? end def is_admin? current_user ? true : false end def current_user_session return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find end def current_user return @current_user if defined?(@current_user) @current_user = current_user_session && current_user_session.user end def require_user unless current_user store_location flash[:notice] = "You must be logged in to access this page" redirect_to new_user_session_url return false end end def require_admin_user require_user unless current_user.admin? redirect_to admin_path return false end end def require_no_user if current_user store_location redirect_to admin_path return false end end def store_location session[:return_to] = request.request_uri end def redirect_back_or_default(default) redirect_to(session[:return_to] || default) session[:return_to] = nil end def results_to_json constituencies, members, callback=nil + host = request.host + port = request.port + constituencies_json = "" constituencies.each do |constituency| constituencies_json += ", " unless constituencies_json == "" - constituencies_json += constituency.to_json[1..-2] + constituencies_json += constituency.to_json(host, port)[1..-2] end members_json = "" members.each do |member| members_json += ", " unless members_json == "" - members_json += member.to_json[1..-2] + members_json += member.to_json(host, port)[1..-2] end constituencies_results = %Q|"constituencies": {#{constituencies_json}}| members_results = %Q|"members": {#{members_json}}| json = %Q|{"results": { #{constituencies_results}, #{members_results} }} | if callback %Q|#{callback}(#{json})| else json end end def results_to_text constituencies, members + host = request.host + port = request.port + results = "" constituencies.each do |constituency| results += "\n\n" - results += " - " + constituency.to_text.gsub("\n", "\n\ ") + results += " - " + constituency.to_text(host, port).gsub("\n", "\n\ ") end members.each do |member| results += "\n\n" - results += " - " + member.to_text.gsub("\n", "\n ") + results += " - " + member.to_text(host, port).gsub("\n", "\n ") end "constituencies:" + results end def results_to_yaml constituencies, members "---\n#{results_to_text(constituencies, members)}" end def results_to_csv constituencies, members - headers = 'constituency_name,member_name,member_party,member_biography_url,member_website' + host = request.host + port = request.port + + headers = 'constituency_name,member_name,member_party,member_biography_url,member_website, uri' values = "" constituencies.each do |constituency| - values += constituency.to_csv_value + "\n" + values += constituency.to_csv_value(host, port) + "\n" end members.each do |constituency| - values += constituency.to_csv_value + "\n" + values += constituency.to_csv_value(host, port) + "\n" end "#{headers}\n#{values}\n" end def message_to_json root, message %Q|{"#{root}": "#{message}"}| end def message_to_text root, message %Q|#{root}: #{message}\n| end def message_to_csv root, message, root_header, message_header headers = %Q|"#{root_header}","#{message_header}"| values = %Q|"#{root}","#{message}"| "#{headers}\n#{values}\n" end def message_to_yaml root, message "---\n#{message_to_text(root, message)}" end end diff --git a/app/models/constituency.rb b/app/models/constituency.rb index bf91dc4..2937166 100755 --- a/app/models/constituency.rb +++ b/app/models/constituency.rb @@ -1,202 +1,202 @@ class Constituency < ActiveRecord::Base include ActionController::UrlWriter has_friendly_id :name, :use_slug => true, :strip_diacritics => true has_many :postcodes has_many :postcode_districts has_many :messages validate :valid_email? class << self def all_constituencies all.select{|c| c.name != 'Example'} end def remove_quotes text text.strip[/^"?([^"]+)"?$/,1] end def load_tsv_line line parts = line.split("\t") constituency_name = remove_quotes(parts[0]) member_name = remove_quotes(parts[1]) member_party = remove_quotes(parts[2]) member_bio_url = remove_quotes(parts[3]) member_contact = remove_quotes(parts[4]) member_website = remove_quotes(parts[5]) member_contact = "" unless member_contact existing = Constituency.find_by_constituency_name(constituency_name) new_constituency = nil if existing non_matching = (existing.member_name != member_name || existing.member_party != member_party || existing.member_biography_url != member_bio_url) non_matching = non_matching || ( member_contact[/http:\/\//] ? (existing.member_requested_contact_url.to_s.strip != member_contact.to_s.strip) : (existing.member_email.to_s.strip != member_contact.to_s.strip) ) if non_matching new_constituency = Constituency.new(existing.attributes) new_constituency.member_name = member_name new_constituency.member_party = member_party new_constituency.member_biography_url = member_bio_url if member_contact[/http:\/\//] new_constituency.member_requested_contact_url = member_contact else new_constituency.member_email = member_contact.chomp('.') end new_constituency.member_website = member_website end [existing, new_constituency] else [nil, nil] end end def find_all_constituency_and_member_matches term term = term.squeeze(' ').gsub('"','') constituencies = Constituency.find_all_name_or_member_name_matches(term) members = constituencies.clone if term[/[A-Z][a-z].*/] constituencies = constituencies.select { |c| c.name.include? term } members = members.select { |c| c.member_name.include? term } else constituencies = constituencies.select { |c| c.name.downcase.include? term.downcase } members = members.select { |c| c.member_name? && c.member_name.downcase.include?(term.downcase) } end constituencies = constituencies.sort_by(&:name) members = members.sort_by(&:member_name) return [constituencies, members] end def find_all_name_or_member_name_matches term term = term.squeeze(' ').gsub('"','') matches_name_or_member_name = %Q|name like "%#{term}%" or | + %Q|(member_name like "%#{term}%" and member_visible = 1)| constituencies = find(:all, :conditions => matches_name_or_member_name) constituencies.delete_if{|c| c.name == 'Example'} if case_sensitive(term) constituencies.delete_if do |c| !c.name.include?(term) && !c.member_name.include?(term) end end constituencies end def case_sensitive term term.gsub('"','')[/^([A-Z][a-z]+[ ]+)*([A-Z][a-z]+)$/] ? true : false end def find_by_constituency_name name name.gsub!('St ', 'St. ') name.gsub!(' - ','-') if name[/^(.+), City of$/] name = "City of #{$1}" end constituency = find_by_name(name) unless constituency name.gsub!('&', 'and') if name == "Regent's Park and Kensington North" name = "Regent's Park and North Kensington" end if name[/^(.+), The$/] name = "The #{$1}" end name.tr!('-', ' ') name.gsub!('ô','o') name.gsub!('and#244;', 'o') constituency = find_by_name(name) end unless constituency puts "" puts "not found: #{name}" end constituency end end def show_message_form? member_name? && member_email? && !member_requested_contact_url? end def code if ons_id.nil? '' elsif ons_id < 10 "00#{ons_id}" elsif ons_id < 100 "0#{ons_id}" else ons_id.to_s end end def no_sitting_member? (!member_name?) || (!member_visible) end def to_tsv_line %Q|"#{name}"\t"#{member_name}"\t"#{member_party}"\t"#{member_biography_url}"\t"#{member_email}"\t"#{member_website}"| end - def to_json + def to_json host, port if no_sitting_member? - %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "No sitting member", "member_party": "", "member_biography_url": "", "member_website": "", "uri": "#{object_url("json")}" } }| + %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "No sitting member", "member_party": "", "member_biography_url": "", "member_website": "", "uri": "#{object_url(host, port, "json")}" } }| else - %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "#{member_name}", "member_party": "#{member_party}", "member_biography_url": "#{member_biography_url}", "member_website": "#{member_website}", "uri": "#{object_url("json")}" } }| + %Q|{"constituency": {"constituency_name": "#{name}", "member_name": "#{member_name}", "member_party": "#{member_party}", "member_biography_url": "#{member_biography_url}", "member_website": "#{member_website}", "uri": "#{object_url(host, port, "json")}" } }| end end - def to_text(format="txt") + def to_text host, port, format="txt" if no_sitting_member? - %Q|constituency_name: #{name}\nmember_name: No sitting member\nmember_party: \nmember_biography_url: \nmember_website: \nuri: #{object_url(format)}| + %Q|constituency_name: #{name}\nmember_name: No sitting member\nmember_party: \nmember_biography_url: \nmember_website: \nuri: #{object_url(host, port, format)}| else - %Q|constituency_name: #{name}\nmember_name: #{member_name}\nmember_party: #{member_party}\nmember_biography_url: #{member_biography_url}\nmember_website: #{member_website}\nuri: #{object_url(format)}| + %Q|constituency_name: #{name}\nmember_name: #{member_name}\nmember_party: #{member_party}\nmember_biography_url: #{member_biography_url}\nmember_website: #{member_website}\nuri: #{object_url(host, port, format)}| end end - def to_csv + def to_csv host, port headers = 'constituency_name,member_name,member_party,member_biography_url,member_website,uri' - values = to_csv_value + values = to_csv_value(host, port) "#{headers}\n#{values}\n" end - def to_csv_value + def to_csv_value host, port if no_sitting_member? - %Q|"#{name}","No sitting member","","","","#{object_url("csv")}"| + %Q|"#{name}","No sitting member","","","","#{object_url(host, port, format, "csv")}"| else - %Q|"#{name}","#{member_name}","#{member_party}","#{member_biography_url}","#{member_website}","#{object_url("csv")}"| + %Q|"#{name}","#{member_name}","#{member_party}","#{member_biography_url}","#{member_website}","#{object_url(host, port, "csv")}"| end end - def to_output_yaml - "---\n#{to_text("yaml")}" + def to_output_yaml host, port + "---\n#{to_text(host, port, "yaml")}" end def member_attribute_changed? attribute, constituency send(attribute).to_s.strip != constituency.send(attribute).to_s.strip end private def valid_email? unless member_email.blank? begin self.member_email = MessageMailer.parse_email(member_email).address rescue errors.add_to_base("Member email must be a valid email") end end end - def object_url format=nil - url_for :host=>'localhost', :port=>'3000', :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false + def object_url host, port, format=nil + url_for :host=> host, :port=> port, :controller=>"constituencies", :action=>"show", :id => friendly_id, :format => format, :only_path => false end end diff --git a/app/models/postcode.rb b/app/models/postcode.rb index 5170b21..82ebade 100644 --- a/app/models/postcode.rb +++ b/app/models/postcode.rb @@ -1,101 +1,101 @@ class Postcode < ActiveRecord::Base include ActionController::UrlWriter before_validation_on_create :populate_constituency_id validates_uniqueness_of :code validates_presence_of :ons_id belongs_to :constituency delegate :member_name, :to => :constituency class << self def find_postcode_by_code search_term return nil unless search_term code = String.new search_term code.strip! code.upcase! code.tr!(' ','') find_by_code(code, :include => :constituency) end end def in_constituency? constituency self.constituency_id == constituency.id end def constituency_name if constituency constituency.name else raise "constituency not found for constituency_id: #{constituency_id}, postcode: #{code}" end end def code_prefix code[0..-4] end def code_with_space suffix = code[-3,3] "#{code_prefix} #{suffix}" end - def to_json + def to_json host, port member = member_name ? %Q|, "member_name": "#{member_name.strip}"| : '' - %Q|{"postcode": {"code": "#{code_with_space}", "constituency_name": "#{constituency_name}"#{member}, "uri": "#{object_url("json")}"} }| + %Q|{"postcode": {"code": "#{code_with_space}", "constituency_name": "#{constituency_name}"#{member}, "uri": "#{object_url(host, port, "json")}"} }| end - def to_text(format="txt") + def to_text host, port, format="txt" member = member_name ? %Q|\nmember_name: #{member_name.strip}| : '' - %Q|postcode: #{code_with_space}\nconstituency_name: #{constituency_name}#{member}\nuri: #{object_url(format)}\n| + %Q|postcode: #{code_with_space}\nconstituency_name: #{constituency_name}#{member}\nuri: #{object_url(host, port, format)}\n| end - def to_csv + def to_csv host, port headers = 'postcode,constituency_name' values = %Q|"#{code_with_space}","#{constituency_name}"| if member_name headers += ',member_name' values += %Q|,"#{member_name.strip}"| end headers += ",uri" - values += %Q|,"#{object_url("csv")}"| + values += %Q|,"#{object_url(host, port, "csv")}"| "#{headers}\n#{values}\n" end - def to_output_yaml - "---\n#{to_text("yaml")}" + def to_output_yaml host, port + "---\n#{to_text(host, port, "yaml")}" end def blacklist blacklisted = BlacklistedPostcode.find_by_code(code) unless blacklisted blacklisted = BlacklistedPostcode.create :code => code, :constituency_id => constituency_id ,:ons_id => ons_id if blacklisted self.delete else return false end else self.delete end true end private def populate_constituency_id if ons_id if constituency = Constituency.find_by_ons_id(ons_id) self.constituency_id = constituency.id # else # errors.add('constituency_id', "Can't find a constituency corresponding to ONS ID: #{ons_id}") end end end - def object_url format=nil - url_for :host=>'localhost', :port=>'3000', :controller=>"postcodes", :action=>"show", :postcode => code, :format => format, :only_path => false + def object_url host, port, format=nil + url_for :host=> host, :port=> port, :controller=>"postcodes", :action=>"show", :postcode => code, :format => format, :only_path => false end end diff --git a/spec/models/constituency_spec.rb b/spec/models/constituency_spec.rb index 5b897a2..88e34fd 100644 --- a/spec/models/constituency_spec.rb +++ b/spec/models/constituency_spec.rb @@ -1,369 +1,369 @@ require File.dirname(__FILE__) + '/../spec_helper' describe Constituency do assert_model_has_many :postcodes assert_model_has_many :messages before do @constituency = Constituency.new @constituency2 = Constituency.new end describe 'when asked for find_all_constituency_and_member_matches' do before do @constituency.name = 'Bethnal Green and Bow' @constituency2.name = 'Aldershot Bow' @constituency.member_name = '' @constituency2.member_name = '' end it 'should sort constituencies by name' do constituencies = [@constituency,@constituency2] Constituency.should_receive(:find_all_name_or_member_name_matches).with('Bow').and_return constituencies constituencies, members = Constituency.find_all_constituency_and_member_matches('Bow') constituencies.should == [@constituency2, @constituency] end it 'should match case of constituency name' do @constituency2.name = 'Aldershotbow' constituencies = [@constituency,@constituency2] Constituency.should_receive(:find_all_name_or_member_name_matches).with('Bow').and_return constituencies constituencies, members = Constituency.find_all_constituency_and_member_matches('Bow') constituencies.should == [@constituency] end it 'should ignore case of search term if not capitalized' do @constituency2.name = 'Aldershotbow' constituencies = [@constituency,@constituency2] Constituency.should_receive(:find_all_name_or_member_name_matches).with('bow').and_return constituencies constituencies, members = Constituency.find_all_constituency_and_member_matches('bow') constituencies.should == [@constituency2,@constituency] end it 'should match case of member name if capitalized' do @constituency.member_name = 'Ian' @constituency2.member_name = 'Sian' constituencies = [@constituency,@constituency2] Constituency.should_receive(:find_all_name_or_member_name_matches).with('Ian').and_return constituencies constituencies, members = Constituency.find_all_constituency_and_member_matches('Ian') members.should == [@constituency] end it 'should not match a hidden member name' do @constituency.member_name = 'Ian' @constituency2.member_name = 'Sian' @constituency.member_visible = false Constituency.should_receive(:find_all_name_or_member_name_matches).with('ian').and_return [@constituency2] constituencies, members = Constituency.find_all_constituency_and_member_matches('ian') members.should == [@constituency2] end end describe 'when asked if member name has changed' do it 'should return true if it has' do @constituency.member_name = 'old' @constituency2.member_name = 'new' @constituency.member_attribute_changed?(:member_name, @constituency2).should be_true end it 'should return false if it hasn\'t' do @constituency.member_name = 'old' @constituency2.member_name = 'old' @constituency.member_attribute_changed?(:member_name, @constituency2).should be_false end end describe 'when asked if member party has changed' do it 'should return true if it has' do @constituency.member_party = 'old' @constituency2.member_party = 'new' @constituency.member_attribute_changed?(:member_party, @constituency2).should be_true end it 'should return false if it hasn\'t' do @constituency.member_party = 'old' @constituency2.member_party = 'old' @constituency.member_attribute_changed?(:member_party, @constituency2).should be_false end end describe 'when asked for find_all_name_or_member_name_matches' do def should_find_all term cleaned_term = term.squeeze(' ').gsub('"','') conditions = %Q|name like "%#{cleaned_term}%" or (member_name like "%#{cleaned_term}%" and member_visible = 1)| @name_match_lc = mock(Constituency, :name => 'Lanark and Hamilton East', :member_name=>'member') @member_match_lc = mock(Constituency, :member_name => 'Ms Emily Thornberry', :name=>'place') @name_match = mock(Constituency, :name => 'Milton Keynes South West', :member_name=>'another member') @member_match = mock(Constituency, :member_name => 'Anne Milton', :name=>'another place') @all_matches = [@name_match_lc, @member_match_lc, @name_match, @member_match] Constituency.should_receive(:find).with(:all, :conditions => conditions).and_return @all_matches end describe 'and search term is lowercase, e.g. "mil"' do it 'should return all matches ignoring case' do term = 'mil' Constituency.case_sensitive(term).should be_false should_find_all term Constituency.find_all_name_or_member_name_matches(term).should == @all_matches end end describe 'and search term is capitalized, e.g. Mil' do it 'should return all matches, case-sensitive' do term = 'Mil' Constituency.case_sensitive(term).should be_true should_find_all term Constituency.find_all_name_or_member_name_matches(term).should == [@name_match, @member_match] end end describe 'and search term is in brackets, e.g. "Mil"' do it 'should return all matches, case-sensitive' do term = '"Mil"' Constituency.case_sensitive(term).should be_true should_find_all term Constituency.find_all_name_or_member_name_matches(term).should == [@name_match, @member_match] end end describe 'and search term is mixedcase, e.g. "MiL"' do it 'should return all matches ignoring case' do term = 'MiL' Constituency.case_sensitive(term).should be_false should_find_all term Constituency.find_all_name_or_member_name_matches(term).should == @all_matches end end end describe 'when asked for find_by_constituency_name' do before do @match_name = mock(Constituency, :name => 'Aberdeen South', :member_name => 'Miss Anne Begg') @match_st = mock(Constituency, :name => 'St. Ives') @match_city = mock(Constituency, :name => 'City of York') @match_north = mock(Constituency, :name => "Regent's Park and North Kensington") @match_the = mock(Constituency, :name => "The Wrekin") end describe 'and search term is valid' do it 'should return a valid constituency' do term = 'Aberdeen South' Constituency.should_receive(:find_by_name).with(term).and_return @match_name Constituency.find_by_constituency_name(term).should == @match_name end end describe 'and search term is St Ives' do it 'should search for St. Ives' do term = 'St Ives' expected = 'St. Ives' Constituency.should_receive(:find_by_name).with(expected).and_return @match_st Constituency.find_by_constituency_name(term).name.should == expected end end describe 'and search term is York, City of' do it 'should return City of York' do term = 'York, City of' expected = 'City of York' Constituency.should_receive(:find_by_name).with(expected).and_return @match_city Constituency.find_by_constituency_name(term).name.should == expected end end describe "and search term is Regent's Park & Kensington North" do it "should return Regent's Park and North Kensington" do term = "Regent's Park & Kensington North" expected = "Regent's Park and North Kensington" Constituency.should_receive(:find_by_name).with(term).and_return nil Constituency.should_receive(:find_by_name).with(expected).and_return @match_north Constituency.find_by_constituency_name(term).name.should == expected end end describe "and search term is Wrekin, The" do it "should return The Wrekin" do term = "Wrekin, The" expected = "The Wrekin" Constituency.should_receive(:find_by_name).with(term).and_return nil Constituency.should_receive(:find_by_name).with(expected).and_return @match_the Constituency.find_by_constituency_name(term).name.should == expected end end end describe 'when asked to load tsv line' do def tsv_line email %Q|"Islington West"\t"Duncan McCloud"\t"Plaid Cymru"\t"http://biographies.parliament.uk/parliament/default.asp?id=25505"\t"#{email}"\t"http://www.m.co.uk/"| end def check_update_constituency contact, contact_type Constituency.should_receive(:find_by_constituency_name).with('Islington West').and_return @constituency @new_constituency = Constituency.new Constituency.should_receive(:new).with(@constituency.attributes).and_return @new_constituency @new_constituency.should_receive(:member_name=).with('Duncan McCloud') @new_constituency.should_receive(:member_party=).with('Plaid Cymru') @new_constituency.should_receive(:member_biography_url=).with('http://biographies.parliament.uk/parliament/default.asp?id=25505') @new_constituency.should_receive(:member_website=).with('http://www.m.co.uk/') @new_constituency.should_receive(contact_type).with(contact.chomp('.')) line = tsv_line(contact) loaded = Constituency.load_tsv_line(line) loaded.should == [@constituency, @new_constituency] loaded[1] end describe 'and constituency exists and tsv line contains broken email/contact url' do it 'should update constituency' do new_constituency = check_update_constituency 'broken.contact.details', :member_email= end end describe 'and constituency exists and tsv line contains email' do it 'should update constituency' do check_update_constituency 'example@email.address.', :member_email= end end describe 'and constituency exists and tsv line contains contact url' do it 'should update constituency' do check_update_constituency 'http://example.contactform.com', :member_requested_contact_url= end it 'should update constituency when contact url ends in html file' do check_update_constituency 'http://www.armp.org.uk/contact.html', :member_requested_contact_url= end end describe 'and constituency doesn\'t already exist' do it 'should create new constituency?' do Constituency.load_tsv_line tsv_line('example@email.address') end end end describe 'when asked for formatted version' do before do @constituency.stub!(:no_sitting_member?).and_return false @constituency.stub!(:friendly_id).and_return "islington-west" @constituency.name = "Islington West" @constituency.id = 999 @constituency.ons_id = 999 @constituency.member_name = "Duncan McCloud" @constituency.member_email = "duncan@mccloud.clan" @constituency.member_party = "Plaid Cymru" @constituency.member_biography_url = "http://biographies.parliament.uk/parliament/default.asp?id=25476" @constituency.member_website = "http://mccloud.uk" end describe 'as tab separated value line' do it 'should return tsv line' do @constituency.to_tsv_line.should == %Q|"Islington West"\t"Duncan McCloud"\t"Plaid Cymru"\t"http://biographies.parliament.uk/parliament/default.asp?id=25476"\t"duncan@mccloud.clan"\t"http://mccloud.uk"| end end describe 'in json' do it 'should create json correctly' do - @constituency.to_json.should == %Q|{"constituency": {"constituency_name": "Islington West", "member_name": "Duncan McCloud", "member_party": "Plaid Cymru", "member_biography_url": "http://biographies.parliament.uk/parliament/default.asp?id=25476", "member_website": "http://mccloud.uk", "uri": "http://localhost:3000/constituencies/islington-west.json" } }| + @constituency.to_json('localhost', '3000').should == %Q|{"constituency": {"constituency_name": "Islington West", "member_name": "Duncan McCloud", "member_party": "Plaid Cymru", "member_biography_url": "http://biographies.parliament.uk/parliament/default.asp?id=25476", "member_website": "http://mccloud.uk", "uri": "http://localhost:3000/constituencies/islington-west.json" } }| end end describe 'in text' do it 'should create text correctly' do - @constituency.to_text.should == %Q|constituency_name: Islington West\nmember_name: Duncan McCloud\nmember_party: Plaid Cymru\nmember_biography_url: http://biographies.parliament.uk/parliament/default.asp?id=25476\nmember_website: http://mccloud.uk\nuri: http://localhost:3000/constituencies/islington-west.txt| + @constituency.to_text('localhost', '3000').should == %Q|constituency_name: Islington West\nmember_name: Duncan McCloud\nmember_party: Plaid Cymru\nmember_biography_url: http://biographies.parliament.uk/parliament/default.asp?id=25476\nmember_website: http://mccloud.uk\nuri: http://localhost:3000/constituencies/islington-west.txt| end end describe 'in csv' do it 'should create csv correctly' do - @constituency.to_csv.should == %Q|constituency_name,member_name,member_party,member_biography_url,member_website,uri\n"Islington West","Duncan McCloud","Plaid Cymru","http://biographies.parliament.uk/parliament/default.asp?id=25476","http://mccloud.uk","http://localhost:3000/constituencies/islington-west.csv"\n| + @constituency.to_csv('localhost', '3000').should == %Q|constituency_name,member_name,member_party,member_biography_url,member_website,uri\n"Islington West","Duncan McCloud","Plaid Cymru","http://biographies.parliament.uk/parliament/default.asp?id=25476","http://mccloud.uk","http://localhost:3000/constituencies/islington-west.csv"\n| end end describe 'in yaml' do it 'should create yaml correctly' do - @constituency.to_output_yaml.should == %Q|---\nconstituency_name: Islington West\nmember_name: Duncan McCloud\nmember_party: Plaid Cymru\nmember_biography_url: http://biographies.parliament.uk/parliament/default.asp?id=25476\nmember_website: http://mccloud.uk\nuri: http://localhost:3000/constituencies/islington-west.yaml| + @constituency.to_output_yaml('localhost', '3000').should == %Q|---\nconstituency_name: Islington West\nmember_name: Duncan McCloud\nmember_party: Plaid Cymru\nmember_biography_url: http://biographies.parliament.uk/parliament/default.asp?id=25476\nmember_website: http://mccloud.uk\nuri: http://localhost:3000/constituencies/islington-west.yaml| end end end describe 'with invalid member_email' do it 'should not be valid' do @constituency.member_email = 'bad_email' @constituency.valid?.should be_false end end describe 'with valid member_email' do before do @constituency.member_email = 'ds@example.u.p.co.uk' end it 'should be valid' do @constituency.valid?.should be_true end describe 'and with member_name' do before do @constituency.member_name = 'name' end it 'should have show_message_form? return true' do @constituency.show_message_form?.should be_true end describe 'and with member requested contact url' do before do @constituency.member_requested_contact_url = 'http://here.co.uk/' end it 'should have show_message_form? return false' do @constituency.show_message_form?.should be_false end end end describe 'and without member_name' do it 'should have show_message_form? return true' do @constituency.show_message_form?.should be_false end end end describe 'with member' do before do @member_name = 'Tiberius Kirk' @constituency.member_name = @member_name @constituency.member_visible = true end describe 'when asked for member name' do it 'should return member\'s name' do @constituency.member_name.should == @member_name end it 'should have no_sitting_member? return false' do @constituency.no_sitting_member?.should be_false end end end describe 'vacant' do describe 'when asked for member name' do it 'should return nil' do @constituency.member_name.should be_nil end it 'should have no_sitting_member? return true' do @constituency.no_sitting_member?.should be_true end end end describe 'id is 1' do before do; @constituency.stub!(:ons_id).and_return 1; end describe 'when asked for code' do it 'should return 001' do @constituency.code.should == '001' end end end describe 'id is 10' do before do; @constituency.stub!(:ons_id).and_return 10; end describe 'when asked for code' do it 'should return 010' do @constituency.code.should == '010' end end end describe 'id is 100' do before do; @constituency.stub!(:ons_id).and_return 100; end describe 'when asked for code' do it 'should return 100' do @constituency.code.should == '100' end end end end diff --git a/spec/models/postcode_spec.rb b/spec/models/postcode_spec.rb index 1f94a55..6c140c5 100644 --- a/spec/models/postcode_spec.rb +++ b/spec/models/postcode_spec.rb @@ -1,153 +1,153 @@ require File.dirname(__FILE__) + '/../spec_helper' describe Postcode do assert_model_belongs_to :constituency before do @postcode = Postcode.new @constituency_name = 'Islington South' @member_name = 'Edmund Husserl' @constituency = mock_model(Constituency, :id => 123, :ons_id =>801, :name => @constituency_name, :member_name => @member_name) @other_constituency = mock_model(Constituency, :id => 124) @postcode.stub!(:constituency).and_return @constituency @postcode.stub!(:constituency_id).and_return @constituency.id @postcode.stub!(:ons_id).and_return @constituency.ons_id end describe 'when asked to blacklist a postcode' do before do @code = 'N12SD' @postcode.stub!(:code).and_return @code @blacklisted = mock_model(BlacklistedPostcode) end describe 'and the postcode has not already been blacklisted' do before do BlacklistedPostcode.should_receive(:find_by_code).with(@code).and_return nil end it 'should create an entry in the blacklisted_postcodes table and delete the postcodes entry' do BlacklistedPostcode.should_receive(:create).and_return true @blacklisted.stub!(:save).and_return true @postcode.should_receive(:delete).and_return true @postcode.blacklist.should be_true end it 'should not delete the postcode if there is a problem creating the blacklist entry' do BlacklistedPostcode.should_receive(:create).and_return false @postcode.should_not_receive(:delete) @postcode.blacklist end end describe 'and the postcode has already been blacklisted' do it 'should delete the postcodes entry' do @blacklisted.stub!(:create).and_return true BlacklistedPostcode.should_receive(:find_by_code).with(@code).and_return @blacklisted @postcode.should_receive(:delete).and_return true @postcode.blacklist.should be_true end end end describe 'when asked if in constituency' do it 'should return true if in given constituency' do @postcode.in_constituency?(@constituency).should be_true end it 'should return false if not in given constituency' do @postcode.in_constituency?(@other_constituency).should be_false end end describe 'when asked to find postcode by code' do it 'should return match including its constituency and member' do code = 'N12SD' Postcode.should_receive(:find_by_code).with(code, :include => :constituency).and_return @postcode Postcode.find_postcode_by_code(code).should == @postcode end it 'should return nil if given nil code' do Postcode.find_postcode_by_code(nil).should be_nil end end describe 'when asked for formatted version' do before do @postcode.stub!(:code).and_return 'N12SD' end describe 'in json' do it 'should create json correctly' do - @postcode.to_json.should == %Q|{"postcode": {"code": "N1 2SD", "constituency_name": "Islington South", "member_name": "Edmund Husserl", "uri": "http://localhost:3000/postcodes/N12SD.json"} }| + @postcode.to_json('localhost', '3000').should == %Q|{"postcode": {"code": "N1 2SD", "constituency_name": "Islington South", "member_name": "Edmund Husserl", "uri": "http://localhost:3000/postcodes/N12SD.json"} }| end end describe 'in text' do it 'should create text correctly' do - @postcode.to_text.should == %Q|postcode: N1 2SD\nconstituency_name: Islington South\nmember_name: Edmund Husserl\nuri: http://localhost:3000/postcodes/N12SD.txt\n| + @postcode.to_text('localhost', '3000').should == %Q|postcode: N1 2SD\nconstituency_name: Islington South\nmember_name: Edmund Husserl\nuri: http://localhost:3000/postcodes/N12SD.txt\n| end end describe 'in csv' do it 'should create csv correctly' do - @postcode.to_csv.should == %Q|postcode,constituency_name,member_name,uri\n"N1 2SD","Islington South","Edmund Husserl","http://localhost:3000/postcodes/N12SD.csv"\n| + @postcode.to_csv('localhost', '3000').should == %Q|postcode,constituency_name,member_name,uri\n"N1 2SD","Islington South","Edmund Husserl","http://localhost:3000/postcodes/N12SD.csv"\n| end end describe 'in yaml' do it 'should create yaml correctly' do - @postcode.to_output_yaml.should == %Q|---\npostcode: N1 2SD\nconstituency_name: Islington South\nmember_name: Edmund Husserl\nuri: http://localhost:3000/postcodes/N12SD.yaml\n| + @postcode.to_output_yaml('localhost', '3000').should == %Q|---\npostcode: N1 2SD\nconstituency_name: Islington South\nmember_name: Edmund Husserl\nuri: http://localhost:3000/postcodes/N12SD.yaml\n| end end end describe 'when asked for postcode' do describe 'with 5 digit postcode' do it 'should return postcode with space in right place' do @postcode.stub!(:code).and_return 'N12SD' @postcode.code_with_space.should == 'N1 2SD' end end describe 'with 6 digit postcode' do it 'should return postcode with space in right place' do @postcode.stub!(:code).and_return 'SW12SD' @postcode.code_with_space.should == 'SW1 2SD' end end describe 'with 7 digit postcode' do it 'should return postcode with space in right place' do @postcode.stub!(:code).and_return 'WD257BG' @postcode.code_with_space.should == 'WD25 7BG' end end end describe 'with constituency' do describe 'when asked for constituency name' do it 'should return constituency name' do @postcode.constituency_name.should == @constituency_name end end describe 'and member is in constituency' do describe 'when asked for member name' do it 'should return member name' do @postcode.member_name.should == @member_name end end end describe 'and constituency is vacant' do before do @constituency.stub!(:member_name).and_return nil end describe 'when asked for member name' do it 'should return nil' do @postcode.member_name.should be_nil end end end end end
robertbrook/findyourmp
2a7140dc9df0609c7a31c9f15c4e6438fcd9f37e
added manual postcode management function to admin screen
diff --git a/app/controllers/manual_postcodes_controller.rb b/app/controllers/manual_postcodes_controller.rb new file mode 100644 index 0000000..e3f5d6f --- /dev/null +++ b/app/controllers/manual_postcodes_controller.rb @@ -0,0 +1,43 @@ +class ManualPostcodesController < ApplicationController + + before_filter :require_admin_user + + def index + @manual_list = ManualPostcode.all + end + + def new + if request.post? + if params[:commit] == 'Create manual postcode' + code = flash[:code] + flash[:code] = nil + constituency_id = params[:manual_postcodes][:constituency] + constituency = Constituency.find_by_id constituency_id + postcode = ManualPostcode.add_manual_postcode code, constituency_id, constituency.ons_id + + redirect_to :manual_postcodes + else + if params[:manual_postcodes] + code = params[:manual_postcodes][:code] + unless code.nil? + flash[:code] = code + postcode = Postcode.find_by_code code + unless postcode + @constituencies = Constituency.all_constituencies + end + end + end + end + end + end + + def remove + code = params[:code] + manual_code = ManualPostcode.find_by_code code + unless manual_code.nil? + manual_code.remove + end + + redirect_to :manual_postcodes + end +end \ No newline at end of file diff --git a/app/models/manual_postcode.rb b/app/models/manual_postcode.rb index 40ebdf7..aebd4b5 100644 --- a/app/models/manual_postcode.rb +++ b/app/models/manual_postcode.rb @@ -1,36 +1,39 @@ class ManualPostcode < ActiveRecord::Base - validates_uniqueness_of :code validates_presence_of :ons_id + belongs_to :constituency + + delegate :name, :to => :constituency + class << self def add_manual_postcode code, constituency_id, ons_id postcode = Postcode.find_by_code code unless postcode unless ManualPostcode.find_by_code code manual_postcode = ManualPostcode.create :code => code, :constituency_id => constituency_id, :ons_id => ons_id if manual_postcode postcode = Postcode.create :code => code, :constituency_id => constituency_id, :ons_id => ons_id unless postcode manual_postcode.delete return false end else return false end else Postcode.create :code => code, :constituency_id => constituency_id, :ons_id => ons_id end end true end end def remove postcode = Postcode.find_by_code if postcode postcode.delete end self.delete end end diff --git a/app/views/admin/index.haml b/app/views/admin/index.haml index 3168af0..8eed09a 100644 --- a/app/views/admin/index.haml +++ b/app/views/admin/index.haml @@ -1,59 +1,61 @@ - @crumbtrail = 'Admin' - @title = 'Admin' %h3.padded_subheading Messages %p.text = link_to("Messages sent", url_for(:controller=>'admin',:action=>'sent') ) + ':' = number_with_delimiter(@sent_message_count) %p.text - if @waiting_to_be_sent_count > 0 = link_to "Messages <strong>waiting on the server</strong> to be sent: #{number_with_delimiter(@waiting_to_be_sent_count)}", url_for(:controller=>'admin',:action=>'waiting_to_be_sent') - else There are no messages waiting on the server to be sent. -if @current_user.admin? %p.text = link_to 'Check mail server status', url_for(:controller=>'admin',:action=>'mailserver_status') %h3.padded_subheading Members database %p.text = link_to 'Edit Members database information', edit_constituency_list_path | = link_to 'Edit constituencies', constituencies_path - if @current_user.admin? %h3.padded_subheading Postcode database %p.text = link_to 'Manage blacklist', blacklisted_postcodes_path + | + = link_to 'Manage non-ONS postcodes', manual_postcodes_path %h3.padded_subheading Users %p.text = 'You are logged in as <strong>' + @current_user.login + '</strong>' | = link_to 'Edit your account settings', edit_user_path(@current_user) - if @current_user.admin? %p.text= 'Your account has administrator rights.' %p.text = link_to 'Add new user', new_user_path | = link_to 'Edit users', users_path %h3.padded_subheading Memory use on server %p.text = link_to "Memory statistics", url_for(:controller=>'admin',:action=>'stats') - if @current_user.admin? %h3.padded_subheading Emergency shutdown %p.text = link_to 'Shutdown site', shutdown_url diff --git a/app/views/manual_postcodes/index.haml b/app/views/manual_postcodes/index.haml new file mode 100644 index 0000000..b989b8d --- /dev/null +++ b/app/views/manual_postcodes/index.haml @@ -0,0 +1,21 @@ +-@title = 'Manually added postcodes' +- @crumbtrail = link_to_admin_home + +%div.column_content + - unless @manual_list.size == 0 + %table.text + -@manual_list.each do |postcode| + %tr + %td= postcode.code + %td= postcode.name + %td= link_to('remove', "/admin/manual_postcodes/remove/#{postcode.code}") + - else + %div.text The list is currently empty + %br + +%div.text + = link_to('Add to list', '/admin/manual_postcodes/new') + +%p.text + %br + = link_to 'Admin home', admin_path \ No newline at end of file diff --git a/app/views/manual_postcodes/new.haml b/app/views/manual_postcodes/new.haml new file mode 100644 index 0000000..8f33d35 --- /dev/null +++ b/app/views/manual_postcodes/new.haml @@ -0,0 +1,29 @@ +-@title = 'Manually added postcodes' +- @crumbtrail = link_to_admin_home + +-unless @constituencies + - form_tag('/admin/manual_postcodes/new', :method => :post) do + = text_field 'manual_postcodes', 'code' + = submit_tag 'Search' + %br + +%div.text + -if request.post? + -if @constituencies + %p + Please choose a constituency for the postcode <code> + = flash[:code] + </code> from the dropdown: + + -form_for :manual_postcodes, :url => '/admin/manual_postcodes/new', :method => :post do |f| + = f.select('constituency', @constituencies.collect {|constituency| [constituency.name, constituency.id]}) + = f.submit 'Create manual postcode' + -else + Sorry this postcode already exists in the database, please try again + +%p.text + = link_to 'Return to list', manual_postcodes_path + +%p.text + %br + = link_to 'Admin home', admin_path \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 1015523..07a876a 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,56 +1,58 @@ ActionController::Routing::Routes.draw do |map| map.resources :constituencies do |constituency| constituency.resources :messages, :only => [:new, :create, :index] end map.connect '/constituencies/:constituency_id/messages/new', :conditions => { :method => :post }, :controller => 'messages', :action => 'new' map.resource :account, :controller => "users" map.resources :users map.resource :user_session map.resource :constituency_list map.resources :password_resets map.root :controller => "postcodes" map.connect '/postcodes/:postcode.:format', :controller => "postcodes", :action => 'show' map.connect '/postcodes/:postcode', :controller => "postcodes", :action => 'show' map.connect '/search/:q.:format', :controller => "search", :action => 'show' map.connect '/search/:q', :controller => "search", :action => 'show' map.search '/search', :controller => "search", :action => 'index' map.connect '/constituencies/hide_members', :conditions => { :method => :post }, :controller => "constituencies", :action => 'hide_members' map.connect '/constituencies/unhide_members', :conditions => { :method => :post }, :controller => "constituencies", :action => 'unhide_members' map.admin '/admin', :controller => 'admin', :action => 'index' map.connect '/admin/sent', :controller => 'admin', :action => 'sent' map.connect '/admin/sent/:yyyy_mm', :controller => 'admin', :action => 'sent_by_month' map.connect '/admin/waiting_to_be_sent', :controller => 'admin', :action => 'waiting_to_be_sent' map.connect '/admin/stats', :controller => 'admin', :action => 'stats' map.shutdown '/admin/shutdown', :controller => 'admin', :action => 'shutdown' map.mailserver_status '/admin/mailserver_status', :controller => 'admin', :action => 'mailserver_status' map.blacklisted_postcodes '/admin/blacklist', :controller => 'blacklisted_postcodes', :action => 'index' map.connect '/admin/blacklist/restore/:code', :controller => 'blacklisted_postcodes', :action => 'restore' map.connect '/admin/blacklist/new', :controller => 'blacklisted_postcodes', :action => 'new' + + map.manual_postcodes '/admin/manual_postcodes', :controller => 'manual_postcodes', :action => 'index' + map.connect '/admin/manual_postcodes/remove/:code', :controller => 'manual_postcodes', :action => 'remove' + map.connect '/admin/manual_postcodes/new', :controller => 'manual_postcodes', :action => 'new' map.api '/api', :controller => 'api', :action => 'index' map.connect 'api/search', :controller => 'api', :action => 'search' map.connect 'api/postcodes', :controller => 'api', :action => 'postcodes' map.connect 'api/constituencies', :controller => 'api', :action => 'constituencies' - - map.manual_postcodes '/manual_postcodes', :controller => 'manual_postcodes', :action => 'index' map.connect '/commons/constituency/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/member/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/postcode/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/constituency/cons/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/member/cons/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/email/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/l/', :controller => 'postcodes', :action => 'redir' map.connect '/commons/', :controller => 'postcodes', :action => 'redir' map.connect '*bad_route', :controller => 'application', :action => 'render_not_found' end diff --git a/spec/controllers/manual_postcodes_controller_spec.rb b/spec/controllers/manual_postcodes_controller_spec.rb new file mode 100644 index 0000000..c47f148 --- /dev/null +++ b/spec/controllers/manual_postcodes_controller_spec.rb @@ -0,0 +1,83 @@ +require File.dirname(__FILE__) + '/../spec_helper' + +describe ManualPostcodesController do + before do + current_user = mock_model User + current_user.stub!(:admin?).and_return(true) + controller.stub!(:current_user).and_return(current_user) + end + + describe "when finding route for action" do + it 'should display index' do + params_from(:get, "/admin/manual_postcodes").should == {:controller => "manual_postcodes", :action => "index"} + end + end + + describe "when displaying the index page" do + it 'should assign an array of blacklisted postcodes to the view' do + ManualPostcode.stub!(:all).and_return ["postcode1", "postcode2"] + get :index + + assigns[:manual_list].should == ["postcode1", "postcode2"] + end + end + + describe "when removing a manual postcode" do + before do + @code = 'NS21AB' + @manual_postcode = mock('ManualPostcode', :code => @code, :ons_id => 1, :constituency_id => 1, :name => 'Test') + end + + def do_get code + get :remove, :code => code + end + + it "should invoke remove and redirect to the index page given a valid code" do + ManualPostcode.should_receive(:find_by_code).and_return @manual_postcode + @manual_postcode.should_receive(:remove).and_return true + + do_get @code + + response.should redirect_to('/admin/manual_postcodes') + end + end + + describe "when adding a new postcode to the manual list" do + before do + @code = 'NS21AB' + @blacklisted_postcode = mock('ManualPostcode', :code => @code, :ons_id => 1, :constituency_id => 1, :name => 'Test') + end + + describe "when given a valid postcode" do + it "should assign the code to flash memory" do + Postcode.should_receive(:find_by_code).and_return true + + post :new, :manual_postcodes => { :code => @code } + flash[:code].should == @code + end + + it "should assign a list of constituencies to the view if the postcode does not already exist" do + Postcode.should_receive(:find_by_code).and_return nil + Constituency.should_receive(:all_constituencies).and_return ['constituency1', 'constituency2'] + + post :new, :manual_postcodes => { :code => @code } + assigns[:constituencies].should == ['constituency1', 'constituency2'] + end + end + + describe "when a constituency is chosen" do + it 'should retrieve the code from flash memory and redirect after performing an update' do + flash[:code] = @code + constituency_id = 1 + ons_id = 2 + @constituency = mock('Constituency', :constituency_id => constituency_id, :ons_id => ons_id) + Constituency.should_receive(:find_by_id).with(constituency_id).and_return @constituency + ManualPostcode.should_receive(:add_manual_postcode).with(@code, constituency_id, ons_id).and_return @postcode + + post :new, :manual_postcodes => { :constituency => constituency_id }, :commit => 'Create manual postcode' + flash[:code].should == nil + response.should redirect_to('/admin/manual_postcodes') + end + end + end +end \ No newline at end of file
robertbrook/findyourmp
3f1ec52b69a751ee5d6daa937a8eb92a5020fc9f
added blacklist management function to admin screen
diff --git a/app/controllers/blacklisted_postcodes_controller.rb b/app/controllers/blacklisted_postcodes_controller.rb new file mode 100644 index 0000000..bdd60c3 --- /dev/null +++ b/app/controllers/blacklisted_postcodes_controller.rb @@ -0,0 +1,40 @@ +class BlacklistedPostcodesController < ApplicationController + + before_filter :require_admin_user + + def index + @blacklist = BlacklistedPostcode.all + end + + def restore + code = params[:code] + blacklisted_code = BlacklistedPostcode.find_by_code code + unless blacklisted_code.nil? + blacklisted_code.restore + end + + redirect_to :blacklisted_postcodes + end + + def new + if request.post? + if params[:commit] == 'Confirm' + code = flash[:code] + postcode = Postcode.find_by_code code + flash[:code] = nil + postcode.blacklist unless postcode.nil? + + redirect_to :blacklisted_postcodes + else + if params[:blacklist] + code = params[:blacklist][:code] + unless code.nil? + flash[:code] = code + @postcode = Postcode.find_by_code code + end + end + end + end + end + +end \ No newline at end of file diff --git a/app/models/blacklisted_postcode.rb b/app/models/blacklisted_postcode.rb index 4d4abaa..85fbc02 100644 --- a/app/models/blacklisted_postcode.rb +++ b/app/models/blacklisted_postcode.rb @@ -1,12 +1,16 @@ class BlacklistedPostcode < ActiveRecord::Base validates_uniqueness_of :code validates_presence_of :ons_id + belongs_to :constituency + + delegate :name, :to => :constituency + def restore postcode = Postcode.find_by_code code unless postcode postcode = Postcode.create(:code => code, :constituency_id => constituency_id, :ons_id => ons_id) end self.delete if postcode end end \ No newline at end of file diff --git a/app/models/postcode.rb b/app/models/postcode.rb index fb2f589..5170b21 100644 --- a/app/models/postcode.rb +++ b/app/models/postcode.rb @@ -1,101 +1,101 @@ class Postcode < ActiveRecord::Base include ActionController::UrlWriter before_validation_on_create :populate_constituency_id validates_uniqueness_of :code validates_presence_of :ons_id belongs_to :constituency delegate :member_name, :to => :constituency class << self def find_postcode_by_code search_term return nil unless search_term code = String.new search_term code.strip! code.upcase! code.tr!(' ','') find_by_code(code, :include => :constituency) end end def in_constituency? constituency self.constituency_id == constituency.id end def constituency_name if constituency constituency.name else raise "constituency not found for constituency_id: #{constituency_id}, postcode: #{code}" end end def code_prefix code[0..-4] end def code_with_space suffix = code[-3,3] "#{code_prefix} #{suffix}" end def to_json member = member_name ? %Q|, "member_name": "#{member_name.strip}"| : '' %Q|{"postcode": {"code": "#{code_with_space}", "constituency_name": "#{constituency_name}"#{member}, "uri": "#{object_url("json")}"} }| end def to_text(format="txt") member = member_name ? %Q|\nmember_name: #{member_name.strip}| : '' %Q|postcode: #{code_with_space}\nconstituency_name: #{constituency_name}#{member}\nuri: #{object_url(format)}\n| end def to_csv headers = 'postcode,constituency_name' values = %Q|"#{code_with_space}","#{constituency_name}"| if member_name headers += ',member_name' values += %Q|,"#{member_name.strip}"| end headers += ",uri" values += %Q|,"#{object_url("csv")}"| "#{headers}\n#{values}\n" end def to_output_yaml "---\n#{to_text("yaml")}" end def blacklist blacklisted = BlacklistedPostcode.find_by_code(code) unless blacklisted blacklisted = BlacklistedPostcode.create :code => code, :constituency_id => constituency_id ,:ons_id => ons_id - if BlacklistedPostcode.find_by_code(code) + if blacklisted self.delete else return false end else self.delete end true end private def populate_constituency_id if ons_id if constituency = Constituency.find_by_ons_id(ons_id) self.constituency_id = constituency.id # else # errors.add('constituency_id', "Can't find a constituency corresponding to ONS ID: #{ons_id}") end end end def object_url format=nil url_for :host=>'localhost', :port=>'3000', :controller=>"postcodes", :action=>"show", :postcode => code, :format => format, :only_path => false end end diff --git a/app/views/admin/index.haml b/app/views/admin/index.haml index cf31fd1..3168af0 100644 --- a/app/views/admin/index.haml +++ b/app/views/admin/index.haml @@ -1,53 +1,59 @@ - @crumbtrail = 'Admin' - @title = 'Admin' %h3.padded_subheading Messages %p.text = link_to("Messages sent", url_for(:controller=>'admin',:action=>'sent') ) + ':' = number_with_delimiter(@sent_message_count) %p.text - if @waiting_to_be_sent_count > 0 = link_to "Messages <strong>waiting on the server</strong> to be sent: #{number_with_delimiter(@waiting_to_be_sent_count)}", url_for(:controller=>'admin',:action=>'waiting_to_be_sent') - else There are no messages waiting on the server to be sent. -if @current_user.admin? %p.text = link_to 'Check mail server status', url_for(:controller=>'admin',:action=>'mailserver_status') %h3.padded_subheading Members database %p.text = link_to 'Edit Members database information', edit_constituency_list_path | = link_to 'Edit constituencies', constituencies_path + +- if @current_user.admin? + %h3.padded_subheading Postcode database + + %p.text + = link_to 'Manage blacklist', blacklisted_postcodes_path %h3.padded_subheading Users %p.text = 'You are logged in as <strong>' + @current_user.login + '</strong>' | = link_to 'Edit your account settings', edit_user_path(@current_user) - if @current_user.admin? %p.text= 'Your account has administrator rights.' %p.text = link_to 'Add new user', new_user_path | = link_to 'Edit users', users_path %h3.padded_subheading Memory use on server %p.text = link_to "Memory statistics", url_for(:controller=>'admin',:action=>'stats') - if @current_user.admin? %h3.padded_subheading Emergency shutdown %p.text = link_to 'Shutdown site', shutdown_url diff --git a/app/views/blacklisted_postcodes/index.haml b/app/views/blacklisted_postcodes/index.haml new file mode 100644 index 0000000..4adb157 --- /dev/null +++ b/app/views/blacklisted_postcodes/index.haml @@ -0,0 +1,21 @@ +-@title = 'Blacklisted postcodes' +- @crumbtrail = link_to_admin_home + +%div.column_content + - unless @blacklist.size == 0 + %table.text + -@blacklist.each do |postcode| + %tr + %td= postcode.code + %td= postcode.name + %td= link_to('restore', "/admin/blacklist/restore/#{postcode.code}") + - else + %div.text The blacklist is currently empty + %br + +%div.text + = link_to('Add to blacklist', '/admin/blacklist/new') + +%p.text + %br + = link_to 'Admin home', admin_path \ No newline at end of file diff --git a/app/views/blacklisted_postcodes/new.haml b/app/views/blacklisted_postcodes/new.haml new file mode 100644 index 0000000..6164e45 --- /dev/null +++ b/app/views/blacklisted_postcodes/new.haml @@ -0,0 +1,25 @@ +-@title = 'Blacklisted postcodes' +- @crumbtrail = link_to_admin_home + +- form_tag('/admin/blacklist/new', :method => :post) do + = text_field 'blacklist', 'code' + = submit_tag 'Search' +%br + +%div.text + -if request.post? + -if @postcode + You are about to blacklist <code> + = @postcode.code + </code>, please click to confirm + -form_tag('/admin/blacklist/new', :method => :post) do + =submit_tag 'Confirm' + -else + Sorry this postcode does not exist, please try again + +%p.text + = link_to 'Return to list', blacklisted_postcodes_path + +%p.text + %br + = link_to 'Admin home', admin_path \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 4b8be9a..1015523 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,50 +1,56 @@ ActionController::Routing::Routes.draw do |map| map.resources :constituencies do |constituency| constituency.resources :messages, :only => [:new, :create, :index] end map.connect '/constituencies/:constituency_id/messages/new', :conditions => { :method => :post }, :controller => 'messages', :action => 'new' map.resource :account, :controller => "users" map.resources :users map.resource :user_session map.resource :constituency_list map.resources :password_resets map.root :controller => "postcodes" map.connect '/postcodes/:postcode.:format', :controller => "postcodes", :action => 'show' map.connect '/postcodes/:postcode', :controller => "postcodes", :action => 'show' map.connect '/search/:q.:format', :controller => "search", :action => 'show' map.connect '/search/:q', :controller => "search", :action => 'show' map.search '/search', :controller => "search", :action => 'index' map.connect '/constituencies/hide_members', :conditions => { :method => :post }, :controller => "constituencies", :action => 'hide_members' map.connect '/constituencies/unhide_members', :conditions => { :method => :post }, :controller => "constituencies", :action => 'unhide_members' map.admin '/admin', :controller => 'admin', :action => 'index' map.connect '/admin/sent', :controller => 'admin', :action => 'sent' map.connect '/admin/sent/:yyyy_mm', :controller => 'admin', :action => 'sent_by_month' map.connect '/admin/waiting_to_be_sent', :controller => 'admin', :action => 'waiting_to_be_sent' map.connect '/admin/stats', :controller => 'admin', :action => 'stats' map.shutdown '/admin/shutdown', :controller => 'admin', :action => 'shutdown' map.mailserver_status '/admin/mailserver_status', :controller => 'admin', :action => 'mailserver_status' + + map.blacklisted_postcodes '/admin/blacklist', :controller => 'blacklisted_postcodes', :action => 'index' + map.connect '/admin/blacklist/restore/:code', :controller => 'blacklisted_postcodes', :action => 'restore' + map.connect '/admin/blacklist/new', :controller => 'blacklisted_postcodes', :action => 'new' map.api '/api', :controller => 'api', :action => 'index' map.connect 'api/search', :controller => 'api', :action => 'search' map.connect 'api/postcodes', :controller => 'api', :action => 'postcodes' map.connect 'api/constituencies', :controller => 'api', :action => 'constituencies' + + map.manual_postcodes '/manual_postcodes', :controller => 'manual_postcodes', :action => 'index' map.connect '/commons/constituency/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/member/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/postcode/search/l/:q.html', :controller => 'search', :action => 'redir' map.connect '/commons/constituency/cons/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/member/cons/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/email/l/:up_my_street_code.html', :controller => 'constituencies', :action => 'redir' map.connect '/commons/l/', :controller => 'postcodes', :action => 'redir' map.connect '/commons/', :controller => 'postcodes', :action => 'redir' map.connect '*bad_route', :controller => 'application', :action => 'render_not_found' end diff --git a/spec/controllers/blacklisted_postcode_controller_spec.rb b/spec/controllers/blacklisted_postcode_controller_spec.rb new file mode 100644 index 0000000..0eb8570 --- /dev/null +++ b/spec/controllers/blacklisted_postcode_controller_spec.rb @@ -0,0 +1,82 @@ +require File.dirname(__FILE__) + '/../spec_helper' + +describe BlacklistedPostcodesController do + before do + current_user = mock_model User + current_user.stub!(:admin?).and_return(true) + controller.stub!(:current_user).and_return(current_user) + end + + describe "when finding route for action" do + it 'should display index' do + params_from(:get, "/admin/blacklist").should == {:controller => "blacklisted_postcodes", :action => "index"} + end + end + + describe "when displaying the index page" do + it 'should assign an array of blacklisted postcodes to the view' do + BlacklistedPostcode.stub!(:all).and_return ["postcode1", "postcode2"] + get :index + + assigns[:blacklist].should == ["postcode1", "postcode2"] + end + end + + describe "when restoring a blacklisted postcode" do + before do + @code = 'NS21AB' + @blacklisted_postcode = mock('BlacklistedPostcode', :code => @code, :ons_id => 1, :constituency_id => 1, :name => 'Test') + end + + def do_get code + get :restore, :code => code + end + + it "should invoke restore and redirect to the index page given a valid code" do + BlacklistedPostcode.should_receive(:find_by_code).and_return @blacklisted_postcode + @blacklisted_postcode.should_receive(:restore).and_return true + + do_get @code + + response.should redirect_to('/admin/blacklist') + end + + it "should redirect to the index page without invoking restore given an invalid code" do + BlacklistedPostcode.should_receive(:find_by_code).and_return nil + @blacklisted_postcode.should_not_receive(:restore) + + do_get 'invalid' + + response.should redirect_to('/admin/blacklist') + end + end + + describe "when adding a new postcode to the blacklist" do + before do + @code = 'NS21AB' + @blacklisted_postcode = mock('BlacklistedPostcode', :code => @code, :ons_id => 1, :constituency_id => 1, :name => 'Test') + end + + describe "when searching for a postcode" do + it "should assign the code to flash memory" do + Postcode.should_receive(:find_by_code) + + post :new, :blacklist => { :code => @code } + flash[:code].should == @code + end + end + + describe "when an update is confirmed" do + it 'should retrieve the code from flash memory and redirect after performing an update' do + flash[:code] = @code + @postcode = mock('Postcode') + Postcode.should_receive(:find_by_code).with(@code).and_return @postcode + @postcode.should_receive(:blacklist) + + post :new, :commit => 'Confirm' + flash[:code].should == nil + response.should redirect_to('/admin/blacklist') + end + end + end +end \ No newline at end of file diff --git a/spec/models/postcode_spec.rb b/spec/models/postcode_spec.rb index 9425668..1f94a55 100644 --- a/spec/models/postcode_spec.rb +++ b/spec/models/postcode_spec.rb @@ -1,153 +1,153 @@ require File.dirname(__FILE__) + '/../spec_helper' describe Postcode do assert_model_belongs_to :constituency before do @postcode = Postcode.new @constituency_name = 'Islington South' @member_name = 'Edmund Husserl' @constituency = mock_model(Constituency, :id => 123, :ons_id =>801, :name => @constituency_name, :member_name => @member_name) @other_constituency = mock_model(Constituency, :id => 124) @postcode.stub!(:constituency).and_return @constituency @postcode.stub!(:constituency_id).and_return @constituency.id @postcode.stub!(:ons_id).and_return @constituency.ons_id end describe 'when asked to blacklist a postcode' do before do @code = 'N12SD' @postcode.stub!(:code).and_return @code @blacklisted = mock_model(BlacklistedPostcode) end describe 'and the postcode has not already been blacklisted' do before do BlacklistedPostcode.should_receive(:find_by_code).with(@code).and_return nil - BlacklistedPostcode.should_receive(:create).and_return @blacklisted end it 'should create an entry in the blacklisted_postcodes table and delete the postcodes entry' do + BlacklistedPostcode.should_receive(:create).and_return true @blacklisted.stub!(:save).and_return true @postcode.should_receive(:delete).and_return true @postcode.blacklist.should be_true end it 'should not delete the postcode if there is a problem creating the blacklist entry' do - @blacklisted.stub!(:create).and_return false + BlacklistedPostcode.should_receive(:create).and_return false @postcode.should_not_receive(:delete) @postcode.blacklist end end describe 'and the postcode has already been blacklisted' do it 'should delete the postcodes entry' do @blacklisted.stub!(:create).and_return true BlacklistedPostcode.should_receive(:find_by_code).with(@code).and_return @blacklisted @postcode.should_receive(:delete).and_return true @postcode.blacklist.should be_true end end end describe 'when asked if in constituency' do it 'should return true if in given constituency' do @postcode.in_constituency?(@constituency).should be_true end it 'should return false if not in given constituency' do @postcode.in_constituency?(@other_constituency).should be_false end end describe 'when asked to find postcode by code' do it 'should return match including its constituency and member' do code = 'N12SD' Postcode.should_receive(:find_by_code).with(code, :include => :constituency).and_return @postcode Postcode.find_postcode_by_code(code).should == @postcode end it 'should return nil if given nil code' do Postcode.find_postcode_by_code(nil).should be_nil end end describe 'when asked for formatted version' do before do @postcode.stub!(:code).and_return 'N12SD' end describe 'in json' do it 'should create json correctly' do @postcode.to_json.should == %Q|{"postcode": {"code": "N1 2SD", "constituency_name": "Islington South", "member_name": "Edmund Husserl", "uri": "http://localhost:3000/postcodes/N12SD.json"} }| end end describe 'in text' do it 'should create text correctly' do @postcode.to_text.should == %Q|postcode: N1 2SD\nconstituency_name: Islington South\nmember_name: Edmund Husserl\nuri: http://localhost:3000/postcodes/N12SD.txt\n| end end describe 'in csv' do it 'should create csv correctly' do @postcode.to_csv.should == %Q|postcode,constituency_name,member_name,uri\n"N1 2SD","Islington South","Edmund Husserl","http://localhost:3000/postcodes/N12SD.csv"\n| end end describe 'in yaml' do it 'should create yaml correctly' do @postcode.to_output_yaml.should == %Q|---\npostcode: N1 2SD\nconstituency_name: Islington South\nmember_name: Edmund Husserl\nuri: http://localhost:3000/postcodes/N12SD.yaml\n| end end end describe 'when asked for postcode' do describe 'with 5 digit postcode' do it 'should return postcode with space in right place' do @postcode.stub!(:code).and_return 'N12SD' @postcode.code_with_space.should == 'N1 2SD' end end describe 'with 6 digit postcode' do it 'should return postcode with space in right place' do @postcode.stub!(:code).and_return 'SW12SD' @postcode.code_with_space.should == 'SW1 2SD' end end describe 'with 7 digit postcode' do it 'should return postcode with space in right place' do @postcode.stub!(:code).and_return 'WD257BG' @postcode.code_with_space.should == 'WD25 7BG' end end end describe 'with constituency' do describe 'when asked for constituency name' do it 'should return constituency name' do @postcode.constituency_name.should == @constituency_name end end describe 'and member is in constituency' do describe 'when asked for member name' do it 'should return member name' do @postcode.member_name.should == @member_name end end end describe 'and constituency is vacant' do before do @constituency.stub!(:member_name).and_return nil end describe 'when asked for member name' do it 'should return nil' do @postcode.member_name.should be_nil end end end end end
robertbrook/findyourmp
6cb97dfbaba4bd138dccaf6809bbad61e783d285
added remove method to ManualPostcode
diff --git a/app/models/manual_postcode.rb b/app/models/manual_postcode.rb index 055a07f..40ebdf7 100644 --- a/app/models/manual_postcode.rb +++ b/app/models/manual_postcode.rb @@ -1,28 +1,36 @@ class ManualPostcode < ActiveRecord::Base validates_uniqueness_of :code validates_presence_of :ons_id class << self def add_manual_postcode code, constituency_id, ons_id postcode = Postcode.find_by_code code unless postcode unless ManualPostcode.find_by_code code manual_postcode = ManualPostcode.create :code => code, :constituency_id => constituency_id, :ons_id => ons_id if manual_postcode postcode = Postcode.create :code => code, :constituency_id => constituency_id, :ons_id => ons_id unless postcode manual_postcode.delete return false end else return false end else Postcode.create :code => code, :constituency_id => constituency_id, :ons_id => ons_id end end true end end + + def remove + postcode = Postcode.find_by_code + if postcode + postcode.delete + end + self.delete + end end diff --git a/spec/models/manual_postcode_spec.rb b/spec/models/manual_postcode_spec.rb index a763548..29eb427 100644 --- a/spec/models/manual_postcode_spec.rb +++ b/spec/models/manual_postcode_spec.rb @@ -1,61 +1,84 @@ require File.dirname(__FILE__) + '/../spec_helper' describe ManualPostcode do + before do + @code = 'BA140AB' + @constituency_id = 506 + @ons_id = 111 + + @postcode = mock_model(Postcode, :code => @code, :constituency_id => @constituency_id, :ons_id => @ons_id) + end describe 'when asked to add a manual postcode' do before do - @code = 'BA140AB' - @constituency_id = 506 - @ons_id = 111 - - @postcode = mock_model(Postcode, :code => @code, :constituency_id => @constituency_id, :ons_id => @ons_id) @manual_postcode = mock_model(ManualPostcode, :code => @code, :constituency_id => @constituency_id, :ons_id => @ons_id) end it 'should create new Postcode and ManualPostcode records if neither pre-exist' do Postcode.should_receive(:find_by_code).once.and_return nil ManualPostcode.should_receive(:find_by_code).once.and_return nil ManualPostcode.should_receive(:create).and_return @manual_postcode Postcode.should_receive(:create).and_return @postcode ManualPostcode.add_manual_postcode(@code, @constituency_id, @ons_id).should == true end it 'should just create a new postcode if the ManualPostcode record already exists' do Postcode.should_receive(:find_by_code).once.and_return nil ManualPostcode.should_receive(:find_by_code).once.and_return @manual_postcode Postcode.should_receive(:create).and_return @postcode ManualPostcode.should_not_receive(:create) ManualPostcode.add_manual_postcode(@code, @constituency_id, @ons_id).should == true end it 'should not perform any updates if the Postcode already exists' do Postcode.should_receive(:find_by_code).once.and_return @postcode ManualPostcode.should_not_receive(:create) Postcode.should_not_receive(:create) ManualPostcode.add_manual_postcode(@code, @constituency_id, @ons_id).should == true end it 'should not update Postcode if a ManualPostcode insert fails' do Postcode.should_receive(:find_by_code).once.and_return nil ManualPostcode.should_receive(:find_by_code).once.and_return nil ManualPostcode.should_receive(:create).with(:code => @code, :constituency_id => @constituency_id, :ons_id => nil) Postcode.should_not_receive(:create) ManualPostcode.add_manual_postcode(@code, @constituency_id, nil).should == false end it 'should remove the new ManualPostcode if inserting new Postcode fails' do Postcode.should_receive(:find_by_code).once.and_return nil ManualPostcode.should_receive(:find_by_code).once.and_return nil ManualPostcode.should_receive(:create).and_return @manual_postcode Postcode.should_receive(:create).and_return nil @manual_postcode.should_receive(:delete) ManualPostcode.add_manual_postcode(@code, @constituency_id, @ons_id).should == false end end + describe 'when asked to remove a manual postcode' do + before do + @manual_postcode = ManualPostcode.new + end + + it 'should delete the Postcode entry if it exists' do + Postcode.should_receive(:find_by_code).and_return @postcode + @postcode.should_receive(:delete) + @manual_postcode.should_receive(:delete) + + @manual_postcode.remove + end + + it 'should still delete the Manual Postcode entry if there is no matching Postcode' do + Postcode.should_receive(:find_by_code).and_return nil + @postcode.should_not_receive(:delete) + @manual_postcode.should_receive(:delete) + + @manual_postcode.remove + end + end end \ No newline at end of file
robertbrook/findyourmp
1477c4d035ad1cc367af079760bd96f5253eb819
added restore method to BlacklistedPostcode
diff --git a/app/models/blacklisted_postcode.rb b/app/models/blacklisted_postcode.rb index 54f3e39..4d4abaa 100644 --- a/app/models/blacklisted_postcode.rb +++ b/app/models/blacklisted_postcode.rb @@ -1,4 +1,12 @@ class BlacklistedPostcode < ActiveRecord::Base validates_uniqueness_of :code validates_presence_of :ons_id -end + + def restore + postcode = Postcode.find_by_code code + unless postcode + postcode = Postcode.create(:code => code, :constituency_id => constituency_id, :ons_id => ons_id) + end + self.delete if postcode + end +end \ No newline at end of file diff --git a/spec/models/blacklisted_postcode_spec.rb b/spec/models/blacklisted_postcode_spec.rb index 7dc414b..b7e082a 100644 --- a/spec/models/blacklisted_postcode_spec.rb +++ b/spec/models/blacklisted_postcode_spec.rb @@ -1,22 +1,55 @@ require File.dirname(__FILE__) + '/../spec_helper' describe BlacklistedPostcode do + before do + @blacklisted_postcode = BlacklistedPostcode.new + end describe 'when asked to find blacklisted postcode by code' do - before do - @postcode = BlacklistedPostcode.new - end - it 'should return a match' do code = 'N12SD' - BlacklistedPostcode.should_receive(:find_by_code).with(code).and_return @postcode - - BlacklistedPostcode.find_by_code(code).should == @postcode + BlacklistedPostcode.should_receive(:find_by_code).with(code).and_return @blacklisted_postcode + BlacklistedPostcode.find_by_code(code).should == @blacklisted_postcode end it 'should return nil if given nil code' do BlacklistedPostcode.find_by_code(nil).should be_nil end end + describe 'when asked to restore a blacklisted postcode' do + before do + @postcode = mock_model(Postcode) + @ons_id = 444 + @constituency_id = 5 + @code = 'N215SD' + @blacklisted_postcode.stub!(:ons_id).and_return @ons_id + @blacklisted_postcode.stub!(:constituency_id).and_return @constituency_id + @blacklisted_postcoed.stub!(:code).and_return @code + end + + it 'should insert a new Postcode entry if none already exists' do + Postcode.should_receive(:find_by_code).and_return nil + Postcode.should_receive(:create).and_return @postcode + @blacklisted_postcode.should_receive(:delete) + + @blacklisted_postcode.restore + end + + it 'should not attempt to create a new Postcode entry if one already exists' do + Postcode.should_receive(:find_by_code).and_return @postcode + Postcode.should_not_receive(:create) + @blacklisted_postcode.should_receive(:delete) + + @blacklisted_postcode.restore + end + + it 'should not delete the BlacklistedPostcode if the creation of a new Postcode fails' do + Postcode.should_receive(:find_by_code).and_return nil + Postcode.should_receive(:create).and_return nil + @blacklisted_postcode.should_not_receive(:delete) + + @blacklisted_postcode.restore + end + end end \ No newline at end of file
robertbrook/findyourmp
81274574ebbed28719c3b19648a75dbd1a0f8b35
moved admin-only mail server status link to the messages section on the Amdin page
diff --git a/app/views/admin/index.haml b/app/views/admin/index.haml index ffb59f9..cf31fd1 100644 --- a/app/views/admin/index.haml +++ b/app/views/admin/index.haml @@ -1,54 +1,53 @@ - @crumbtrail = 'Admin' - @title = 'Admin' %h3.padded_subheading Messages %p.text = link_to("Messages sent", url_for(:controller=>'admin',:action=>'sent') ) + ':' = number_with_delimiter(@sent_message_count) %p.text - if @waiting_to_be_sent_count > 0 = link_to "Messages <strong>waiting on the server</strong> to be sent: #{number_with_delimiter(@waiting_to_be_sent_count)}", url_for(:controller=>'admin',:action=>'waiting_to_be_sent') - else There are no messages waiting on the server to be sent. + + -if @current_user.admin? + %p.text + = link_to 'Check mail server status', url_for(:controller=>'admin',:action=>'mailserver_status') %h3.padded_subheading Members database %p.text = link_to 'Edit Members database information', edit_constituency_list_path | = link_to 'Edit constituencies', constituencies_path %h3.padded_subheading Users %p.text = 'You are logged in as <strong>' + @current_user.login + '</strong>' | = link_to 'Edit your account settings', edit_user_path(@current_user) - if @current_user.admin? %p.text= 'Your account has administrator rights.' %p.text = link_to 'Add new user', new_user_path | = link_to 'Edit users', users_path %h3.padded_subheading Memory use on server %p.text = link_to "Memory statistics", url_for(:controller=>'admin',:action=>'stats') -- if @current_user.admin? - - %h3.padded_subheading Mail server availability - - %p.text - = link_to 'Mail server status', url_for(:controller=>'admin',:action=>'mailserver_status') +- if @current_user.admin? %h3.padded_subheading Emergency shutdown %p.text = link_to 'Shutdown site', shutdown_url
robertbrook/findyourmp
11be2066cc77abaa56f71040af0ddd0692c761fb
added Manual (non-ONS) Postcode functionality
diff --git a/app/models/manual_postcode.rb b/app/models/manual_postcode.rb new file mode 100644 index 0000000..055a07f --- /dev/null +++ b/app/models/manual_postcode.rb @@ -0,0 +1,28 @@ +class ManualPostcode < ActiveRecord::Base + + validates_uniqueness_of :code + validates_presence_of :ons_id + + class << self + def add_manual_postcode code, constituency_id, ons_id + postcode = Postcode.find_by_code code + unless postcode + unless ManualPostcode.find_by_code code + manual_postcode = ManualPostcode.create :code => code, :constituency_id => constituency_id, :ons_id => ons_id + if manual_postcode + postcode = Postcode.create :code => code, :constituency_id => constituency_id, :ons_id => ons_id + unless postcode + manual_postcode.delete + return false + end + else + return false + end + else + Postcode.create :code => code, :constituency_id => constituency_id, :ons_id => ons_id + end + end + true + end + end +end diff --git a/config/deploy.rb b/config/deploy.rb index 4f07854..f756076 100644 --- a/config/deploy.rb +++ b/config/deploy.rb @@ -1,370 +1,371 @@ load File.expand_path(File.dirname(__FILE__) + '/virtualserver/deploy_secrets.rb') default_run_options[:pty] = true set :repository, "git://github.com/robertbrook/findyourmp.git" set :scm, :git ssh_options[:forward_agent] = true set :branch, "master" set :deploy_via, :remote_cache set :git_enable_submodules, 1 role :app, domain role :web, domain role :db, domain, :primary => true set :test_deploy, true set :master_data_file, 'NSPDC_AUG_2008_UK_100M.txt' namespace :deploy do set :user, deployuser set :password, deploypassword desc "Set sitemap cron job" task :set_sitemap_cron_job, :roles => :app do freq_in_minutes = ENV['freq_in_minutes'] unless freq_in_minutes puts puts 'must supply freq_in_minutes when setting cron job' puts 'USAGE: cap deploy:set_sitemap_cron_job freq_in_minutes=59' puts else cmd = "*/#{freq_in_minutes} * * * * cd #{deploy_to}/current; rake fymp:make_sitemap RAILS_ENV=production" set_cron_job cmd, 'make_sitemap' end end desc "Set delete stored messages cron job" task :set_delete_message_contents_cron_job, :roles => :app do weeks_to_keep = ENV['weeks_to_keep'] unless weeks_to_keep puts puts 'must supply weeks_to_keep when setting cron job' puts 'USAGE: cap deploy:set_delete_message_contents_cron_job weeks_to_keep=6' puts else cmd = "35 4 * * * cd #{deploy_to}/current; rake fymp:delete_stored_message_contents weeks_to_keep=#{weeks_to_keep} RAILS_ENV=production" set_cron_job cmd, 'delete_stored_message_contents' end end desc "Set delete stored messages cron job" task :set_delete_messages_cron_job, :roles => :app do months_to_keep = ENV['months_to_keep'] unless months_to_keep puts puts 'must supply months_to_keep when setting cron job' puts 'USAGE: cap deploy:set_delete_messages_cron_job months_to_keep=6' puts else cmd = "05 4 * * * cd #{deploy_to}/current; rake fymp:delete_stored_messages months_to_keep=#{months_to_keep} RAILS_ENV=production" set_cron_job cmd, 'delete_stored_messages' end end desc "Set ar_sendmail cron job" task :set_ar_sendmail_cron_job, :roles => :app do batch_size = ENV['batch_size'] freq_in_minutes = ENV['freq_in_mins'] unless batch_size && freq_in_minutes puts puts 'must supply batch_size and freq_in_minutes when setting cron job' puts 'USAGE: cap deploy:set_ar_sendmail_cron_job batch_size=100 freq_in_mins=5' puts else cmd = "*/#{freq_in_minutes} * * * * cd #{deploy_to}/current; rake fymp:run_ar_sendmail batch_size=#{batch_size} deploy_dir=#{deploy_to}/current environment=production" set_cron_job cmd, 'ar_sendmail' end end desc "Set db backup cron job" task :set_db_backup_cron_job, :roles => :app do cmd = "02 3 * * * #{deploy_to}/current; rake fymp:backup_db_s3 path=db/backup RAILS_ENV='production'" set_cron_job cmd, 'backup_database_to_S3' end desc "Set db backup cleanup cron job" task :set_db_backup_cleanup_cron_job, :roles => :app do cmd = "42 3 * * * cd #{deploy_to}/current; rake fymp:cleanup_db_backup files_to_keep=42 RAILS_ENV='production'" set_cron_job cmd, 'S3_backup_cleanup' end def set_cron_job cmd, identifier tmpname = "/tmp/appname-crontab.#{Time.now.strftime('%s')}" run "(crontab -l || echo '') | grep -v '#{identifier}' > #{tmpname}" run %Q|echo "#{cmd}" >> #{tmpname}| run "crontab #{tmpname}" run "rm #{tmpname}" end desc "Upload deployed database.yml" task :upload_deployed_database_yml, :roles => :app do data = File.read("config/virtualserver/deployed_database.yml") put data, "#{release_path}/config/database.yml", :mode => 0664 end desc "Upload deployed mailer.yml" task :upload_deployed_mailer_yml, :roles => :app do data = File.read("config/virtualserver/deployed_mailer.yml") put data, "#{release_path}/config/mailer.yml", :mode => 0664 end desc "Upload S3 data files" task :put_s3_data, :roles => :app do data = File.read("config/virtualserver/deployed_s3.yml") put data, "#{release_path}/config/s3.yml", :mode => 0664 data = File.read("config/virtualserver/fymp-public.pem") put data, "#{release_path}/config/fymp-public.pem", :mode => 0664 end task :link_to_data, :roles => :app do data_dir = "#{deploy_to}/shared/cached-copy/data" run "if [ -d #{data_dir} ]; then ln -s #{data_dir} #{release_path}/data ; else echo cap deploy put_data first ; fi" end desc 'put data to server' task :put_data, :roles => :app do data_dir = "#{deploy_to}/shared/cached-copy/data" if overwrite run "if [ -d #{data_dir} ]; then echo #{data_dir} exists ; else mkdir #{data_dir} ; fi" run "rm #{data_dir}/FYMP_all.txt" put_data data_dir, 'FYMP_all.txt' run "rm #{data_dir}/constituencies.txt" put_data data_dir, 'constituencies.txt' if test_deploy run "rm #{data_dir}/postcodes.txt" put_data data_dir, 'postcodes.txt' else run "rm #{data_dir}/#{master_data_file}" put_data data_dir, "#{master_data_file}" end end log_dir = "#{deploy_to}/shared/log" run "if [ -d #{log_dir} ]; then echo #{log_dir} exists ; else mkdir #{log_dir} ; fi" run "if [ -d #{deploy_to}/shared/system ]; then echo exists ; else mkdir #{deploy_to}/shared/system ; fi" rc_rake_file = "#{release_path}/vendor/plugins/resource_controller/tasks/gem.rake" run "if [ -f #{rc_rake_file} ]; then mv #{rc_rake_file} #{rc_rake_file}.bak ; else echo not found ; fi" end def put_data data_dir, file data_file = "#{data_dir}/#{file}" run "if [ -f #{data_file} ]; then echo exists ; else echo not there ; fi" do |channel, stream, message| if message.strip == 'not there' puts "sending #{file}" data = File.read("data/#{file.gsub('\\','')}") put data, "#{data_file}", :mode => 0664 else puts "#{file} #{message}" end end end def prompt_for_value(var) puts "" puts "*************************************" answer = "" message = "Do you want to overwrite the data?\n\nIf yes, type: YES, OVERWRITE!!\n(To continue without overwriting, just hit return)\n" answer = Capistrano::CLI.ui.ask(message) if answer == "YES, OVERWRITE!!" set var, true else set var, false end end def check_correct_ip puts "" puts "*************************************" answer = "n" servers = roles[:app].servers.uniq!.join(", ") message = "You are about to deploy to: #{servers} do you want to continue? (y/N)\n" answer = Capistrano::CLI.ui.ask(message) answer = "n" if answer == "" unless answer.downcase == 'y' # answer.first.downcase == "y" raise "Deploy aborted by user" end end desc "Restarting apache and clearing the cache" task :restart, :roles => :app do sudo "/usr/sbin/apache2ctl restart" run "cd #{current_path}; rake fymp:cache:expire_pages RAILS_ENV='production'" end desc "Perform rake tasks" task :rake_tasks, :roles => :app, :except => { :no_release => true } do run "cd #{current_path}; rake db:migrate RAILS_ENV='production'" if overwrite run "cd #{current_path}; rake fymp:constituencies RAILS_ENV='production'" run "cd #{current_path}; rake fymp:members RAILS_ENV='production'" unless test_deploy postcode_source = "" message = "Which postcodes data file?\n\ne.g. data/NSPDF_MAY_2009_UK_1M_FP.txt\n" postcode_source = Capistrano::CLI.ui.ask(message) if File.exist?(postcode_source) run "cd #{current_path}; rake fymp:parse_postcodes source=#{postcode_source} RAILS_ENV='production'" else raise "cannot find postcodes file: #{postcode_source}" end end run "cd #{current_path}; rake fymp:populate RAILS_ENV='production'" end + run "cd #{current_path}; rake fymp:load_manual_postcodes RAILS_ENV='production'" run "cd #{current_path}; rake fymp:load_postcode_districts RAILS_ENV='production'" end task :check_folder_setup, :roles => :app do if is_first_run? set :overwrite, true else prompt_for_value(:overwrite) end puts 'checking folders...' run "if [ -d #{deploy_to} ]; then echo exists ; else echo not there ; fi" do |channel, stream, message| if message.strip == 'not there' folders = deploy_to.split("/") folderpath = "" folders.each do |folder| if folder != "" folderpath << "/" << folder run "if [ -d #{folderpath} ]; then echo exists ; else echo not there ; fi" do |channel, stream, message| if message.strip == 'not there' sudo "mkdir #{folderpath}" end end end end sudo "chown #{user} #{folderpath}" run "mkdir #{folderpath}/releases" end end puts 'checks complete!' end task :check_server, :roles => :app do check_correct_ip run "git --help" do |channel, stream, message| if message =~ /No such file or directory/ raise "You need to install git before proceeding" end end end task :check_site_setup, :roles => :app do if is_first_run? site_setup else rake_tasks end end task :site_setup, :roles => :app do puts 'entering first time only setup...' sudo "touch /etc/apache2/sites-available/#{application}" sudo "chown #{user} /etc/apache2/sites-available/#{application}" source = File.read("config/findyourmp.apache.example") data = "" source.each { |line| line.gsub!("[RELEASE-PATH]", deploy_to) data << line } put data, "/etc/apache2/sites-available/#{application}", :mode => 0664 sudo "sudo ln -s -f /etc/apache2/sites-available/#{application} /etc/apache2/sites-enabled/000-default" run "sudo mysql -uroot -p", :pty => true do |ch, stream, data| # puts data if data =~ /Enter password:/ ch.send_data(sql_server_password + "\n") else ch.send_data("create database #{application}_production CHARACTER SET utf8 COLLATE utf8_unicode_ci; \n") ch.send_data("create database #{application}_development CHARACTER SET utf8 COLLATE utf8_unicode_ci; \n") ch.send_data("create user '#{sql_backup_user}'@'localhost' identified by '#{sql_backup_password}'; \n") ch.send_data("grant SELECT, LOCK TABLES on #{application}_production.* to '#{sql_backup_user}'@'localhost'; \n") ch.send_data("grant SHOW DATABASES, RELOAD on *.* to '#{sql_backup_user}'@'localhost'; \n") ch.send_data("FLUSH PRIVILEGES; \n") ch.send_data("exit \n") end end sudo "gem sources -a http://gems.github.com" sudo "gem install hpricot" sudo "gem install morph" sudo "gem install unicode" sudo "gem install treetop" sudo "gem install term-ansicolor" sudo "gem install aws-s3 --version '0.5.1'" sudo "gem install adzap-ar_mailer --version '2.1.5'" sudo "cp /var/lib/gems/1.8/bin/ar_sendmail /usr/local/bin/ar_sendmail" rake_tasks sudo "/usr/sbin/apache2ctl restart" puts 'first time only setup complete!' end [:start, :stop].each do |t| desc "#{t} task is not used with mod_rails" task t, :roles => :app do ; end end def is_first_run? run "if [ -f /etc/apache2/sites-available/#{application} ]; then echo exists ; else echo not there ; fi" do |channel, stream, message| if message.strip == 'not there' return true else return false end end end desc "Perform rake tasks" task :update_postcodes, :roles => :app do file = "data/diff_postcodes.txt" if File.exist?(file) data = File.read(file) put data, "#{current_path}/data/diff_postcodes.txt", :mode => 0664 run "cd #{current_path}; rake fymp:update_postcodes RAILS_ENV='production'" else puts 'USAGE EXAMPLE:' puts 'rake fymp:diff_postcodes old=data/NSPDF_FEB_2009_UK_1M.txt new=data/NSPDF_MAY_2009_UK_1M_FP.txt' puts 'cap deploy:update_postcodes' end end end before 'deploy:update_code', 'deploy:check_server', 'deploy:check_folder_setup' after 'deploy:update_code', 'deploy:upload_deployed_database_yml', 'deploy:upload_deployed_mailer_yml', 'deploy:put_s3_data', 'deploy:put_data', 'deploy:link_to_data' after 'deploy:symlink', 'deploy:check_site_setup' namespace :fymp do namespace :cache do set :remote_rake_cmd, "/usr/local/bin/rake" desc "Expire page cache" task :expire_pages, :roles => :app do run("export RAILS_ENV=production; cd #{deploy_to}/current; #{remote_rake_cmd} fymp:cache:expire_pages") end end end diff --git a/db/migrate/20090820151314_create_manual_postcodes.rb b/db/migrate/20090820151314_create_manual_postcodes.rb new file mode 100644 index 0000000..a1671ac --- /dev/null +++ b/db/migrate/20090820151314_create_manual_postcodes.rb @@ -0,0 +1,17 @@ +class CreateManualPostcodes < ActiveRecord::Migration + def self.up + create_table :manual_postcodes do |t| + t.string :code, :limit => 7 + t.integer :constituency_id + t.integer :ons_id + + t.timestamps + end + + add_index :manual_postcodes, :code + end + + def self.down + drop_table :manual_postcodes + end +end diff --git a/db/schema.rb b/db/schema.rb index cd274d6..4a8de7f 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,136 +1,146 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090820095620) do +ActiveRecord::Schema.define(:version => 20090820151314) do create_table "blacklisted_postcodes", :force => true do |t| t.string "code", :limit => 7 t.integer "constituency_id" t.integer "ons_id" t.datetime "created_at" t.datetime "updated_at" end add_index "blacklisted_postcodes", ["code"], :name => "index_blacklisted_postcodes_on_code" create_table "constituencies", :force => true do |t| t.string "name" t.string "member_name" t.string "member_party" t.string "member_email" t.string "member_biography_url" t.boolean "member_visible" t.string "member_website" t.string "member_requested_contact_url" t.integer "ons_id" t.datetime "updated_at" end add_index "constituencies", ["ons_id"], :name => "index_constituencies_on_ons_id" create_table "emails", :force => true do |t| t.string "from" t.string "to" t.integer "last_send_attempt", :default => 0 t.text "mail" t.datetime "created_on" end + create_table "manual_postcodes", :force => true do |t| + t.string "code", :limit => 7 + t.integer "constituency_id" + t.integer "ons_id" + t.datetime "created_at" + t.datetime "updated_at" + end + + add_index "manual_postcodes", ["code"], :name => "index_manual_postcodes_on_code" + create_table "message_summaries", :force => true do |t| t.string "constituency_name" t.string "recipient" t.string "recipient_email" t.datetime "created_at" t.datetime "updated_at" t.date "sent_month" t.integer "count" end add_index "message_summaries", ["constituency_name"], :name => "index_message_summaries_on_constituency_name" add_index "message_summaries", ["recipient"], :name => "index_message_summaries_on_recipient" add_index "message_summaries", ["recipient_email"], :name => "index_message_summaries_on_recipient_email" add_index "message_summaries", ["sent_month"], :name => "index_message_summaries_on_sent_month" create_table "messages", :force => true do |t| t.string "constituency_id" t.string "sender_email" t.string "sender" t.string "recipient" t.string "address" t.string "postcode" t.string "subject" t.text "message" t.boolean "sent" t.datetime "created_at" t.datetime "updated_at" t.string "authenticity_token" t.string "recipient_email" t.boolean "sender_is_constituent" t.string "constituency_name" t.string "mailer_error" t.datetime "sent_at" t.string "sender_ip_address" end add_index "messages", ["sent"], :name => "index_messages_on_sent" add_index "messages", ["sent_at"], :name => "index_messages_on_sent_at" create_table "postcode_districts", :force => true do |t| t.string "district", :limit => 4 t.integer "constituency_id" end add_index "postcode_districts", ["district"], :name => "index_postcode_districts_on_district" create_table "postcodes", :force => true do |t| t.string "code", :limit => 7 t.integer "constituency_id" t.integer "ons_id" end add_index "postcodes", ["code"], :name => "index_postcodes_on_code" add_index "postcodes", ["constituency_id"], :name => "index_postcodes_on_constituency_id" add_index "postcodes", ["ons_id"], :name => "index_postcodes_on_ons_id" create_table "slugs", :force => true do |t| t.string "name" t.integer "sluggable_id" t.integer "sequence", :default => 1, :null => false t.string "sluggable_type", :limit => 40 t.string "scope", :limit => 40 t.datetime "created_at" end add_index "slugs", ["name", "sluggable_type", "scope", "sequence"], :name => "index_slugs_on_name_and_sluggable_type_and_scope_and_sequence", :unique => true add_index "slugs", ["sluggable_id"], :name => "index_slugs_on_sluggable_id" create_table "users", :force => true do |t| t.string "login" t.string "crypted_password" t.string "password_salt" t.string "persistence_token" t.integer "login_count" t.datetime "last_request_at" t.datetime "last_login_at" t.datetime "current_login_at" t.string "last_login_ip" t.string "current_login_ip" t.datetime "created_at" t.datetime "updated_at" t.string "perishable_token", :default => "", :null => false t.string "email", :default => "", :null => false t.boolean "admin", :default => false end add_index "users", ["email"], :name => "index_users_on_email" add_index "users", ["perishable_token"], :name => "index_users_on_perishable_token" end diff --git a/lib/data_loader.rb b/lib/data_loader.rb index 055b9f6..953017d 100644 --- a/lib/data_loader.rb +++ b/lib/data_loader.rb @@ -1,289 +1,296 @@ require File.expand_path(File.dirname(__FILE__) + '/timer') module FindYourMP; end module FindYourMP::DataLoader include FindYourMP::Timer DATA_DIR = File.expand_path(File.dirname(__FILE__) + '/../data') MEMBER_FILE = "#{DATA_DIR}/FYMP_all.txt" CONSTITUENCY_FILE = "#{DATA_DIR}/constituencies.txt" POSTCODE_FILE = "#{DATA_DIR}/postcodes.txt" def diff_postcodes old_file, new_file old_postcodes = "#{DATA_DIR}/old_postcodes.txt" new_postcodes = "#{DATA_DIR}/new_postcodes.txt" parse_postcodes old_file, old_postcodes parse_postcodes new_file, new_postcodes diff_file = "#{DATA_DIR}/diff_postcodes.txt" cmd = "diff #{old_postcodes} #{new_postcodes} > #{diff_file}" puts cmd `#{cmd}` unless File.exist?(diff_file) end def update_postcodes diff_file = "#{DATA_DIR}/diff_postcodes.txt" if file_not_found(diff_file) puts "Generate or upload #{diff_file}" return end to_delete = {} to_create = {} to_update = {} IO.foreach(diff_file) do |line| parts = line.strip.split(' ') indicator = parts[0] if indicator[/(<|>)/] ons_id = parts.pop postcode = parts.join(' ').sub(indicator, '').strip if indicator == '<' to_delete[postcode] = ons_id elsif indicator == '>' to_create[postcode] = ons_id end end end to_create.keys.each do |postcode| if to_delete.delete(postcode) ons_id = to_create.delete(postcode) to_update[postcode] = ons_id end end puts 'to_delete ' + to_delete.size.to_s + ' e.g. ' + to_delete.to_a.first.inspect puts 'to_update ' + to_update.size.to_s + ' e.g. ' + to_update.to_a.first.inspect puts 'to_create ' + to_create.size.to_s + ' e.g. ' + to_create.to_a.first.inspect puts 'checking we have constituencies... ' (to_delete.values + to_update.values + to_create.values).flatten.uniq.each do |ons_id| unless ignore_ons_id?(ons_id) constituency = Constituency.find_by_ons_id(ons_id) raise "unexpected constituency id #{ons_id}" unless constituency end end puts 'all constituencies found' # puts "Update database? y/n" # answer = STDIN.gets # if answer.strip == 'y' do_postcode_update to_delete, to_update, to_create # else # puts 'exiting without database update' # end end def ignore_ons_id?(ons_id) ons_id == '800' || ons_id == '900' end def do_postcode_update to_delete, to_update, to_create puts 'do_postcode_update...' total = (to_delete.size + to_update.size + to_create.size).to_f count = 0 include ActionView::Helpers::DateHelper start_timing to_delete.each do |postcode, ons_id| if post_code = Postcode.find_by_code(postcode.sub(' ','')) post_code.destroy count = count.next log_duration count / total else raise "cannot delete postcode, as it was not in database: #{postcode}" end end to_update.each do |postcode, ons_id| if (post_code = Postcode.find_by_code(postcode.sub(' ',''))) && (ignore_ons_id?(ons_id) || constituency = Constituency.find_by_ons_id(ons_id)) post_code.ons_id = ons_id.strip.to_i if constituency post_code.constituency_id = constituency.id else post_code.constituency_id = nil end post_code.save count = count.next log_duration count / total else raise "cannot delete postcode, as it was not in database: #{postcode} #{ons_id}" end end to_create.each do |postcode, ons_id| begin if Postcode.exists?(:code => postcode.sub(' ','')) raise 'exists ' + postcode elsif BlacklistedPostcode.find_by_code postcode.sub(' ','') puts " (ignoring blacklisted postcode - #{postcode})" else Postcode.create! :code => postcode.sub(' ',''), :ons_id => ons_id.strip.to_i end rescue Exception => e raise e end count = count.next log_duration count / total end log_duration end def load_members member_file member_file = MEMBER_FILE unless member_file return if file_not_found(member_file) lines = [] IO.foreach(member_file) do |line| line.strip! lines << line unless(line.blank? || line[/Constituency/]) end lines.each do |line| begin parts = line.split("\t") constituency_name = parts[0].strip member_name = parts[1].strip if is_vacant?(member_name) log "Constituency is vacant: #{constituency_name}" else existing, updated_constituency = Constituency.load_tsv_line(line) if existing && updated_constituency existing.attributes = updated_constituency.attributes existing.save! elsif updated_constituency log "Cannot find constituency for member for line: #{line}" else # nothing to update end end rescue Exception => e log "Cannot set member_name on constituency for: #{line} | #{e.to_s}" end end end def load_constituencies return if file_not_found(CONSTITUENCY_FILE) Constituency.delete_all Slug.delete_all IO.foreach(CONSTITUENCY_FILE) do |line| constituency_id = line[0..2] constituency_name = line[3..(line.length-1)].strip Constituency.create :name=>constituency_name, :ons_id=>constituency_id end end def parse_postcodes source_file, output_file=POSTCODE_FILE return if file_not_found(source_file) start_timing blank_date = ' ' blank_code = ' ' new_line = "\n" space = ' ' post_codes = [] IO.foreach(source_file) do |line| termination_date = line[29..34] if termination_date == blank_date consistuency_code = line[69..71] unless consistuency_code == blank_code post_code = line[0..6] post_codes << post_code << space << consistuency_code post_codes << new_line end end end log_duration start_timing File.open(output_file,'w') do |file| file.write(post_codes.join('')) end log_duration end def load_postcodes group_size=1000 return if file_not_found(POSTCODE_FILE) index = 0 groups = 0 puts 'saving data to db' Postcode.delete_all columns = [:code, :constituency_id] total = `cat #{POSTCODE_FILE} | wc -l` total = total.strip.to_f include ActionView::Helpers::DateHelper post_codes = [] start_timing IO.foreach(POSTCODE_FILE) do |line| code = line[0..6].tr(' ','') constituency_id = line[8..10] post_codes << [code, constituency_id] index = index.next if (index % group_size) == 0 load_codes(post_codes) groups = groups.next percentage_complete = (group_size * groups) / total log_duration percentage_complete post_codes = [] end end # complete remaining load_codes(post_codes) log_duration 1.0 end def load_postcode_districts PostcodeDistrict.delete_all sql = "SELECT SUBSTRING(code, 1, LENGTH(code)-3) " + "AS district, constituency_id " + "FROM postcodes " + "GROUP BY district, constituency_id;" districts = PostcodeDistrict.find_by_sql(sql) districts.each do |district| PostcodeDistrict.create!(district.attributes) end end + + def load_manual_postcodes + manual_codes = ManualPostcode.all + manual_codes.each do |manual_code| + Postcode.create :code => manual_code.code, :constituency_id => manual_code.constituency_id, :ons_id => manual_code.ons_id + end + end private def load_codes(post_codes) post_codes.each do |codes| if BlacklistedPostcode.find_by_code codes[0] puts " (ignoring blacklisted postcode - #{codes[0]})" else Postcode.create :code => codes[0], :ons_id => codes[1] end end end def is_vacant?(name) name == 'Vacant' end def log msg $stderr.puts msg end def file_not_found file_name if File.exist?(file_name) false else log "Data file not found: #{file_name}" true end end end diff --git a/lib/tasks/parse.rake b/lib/tasks/parse.rake index 4ff98e3..5b22cab 100644 --- a/lib/tasks/parse.rake +++ b/lib/tasks/parse.rake @@ -1,68 +1,73 @@ require File.expand_path(File.dirname(__FILE__) + '/../data_loader') require File.expand_path(File.dirname(__FILE__) + '/../commons_member_biographies') require File.expand_path(File.dirname(__FILE__) + '/../cache_writer') require File.expand_path(File.dirname(__FILE__) + '/../constituency_upmystreet_links') namespace :fymp do include FindYourMP::DataLoader include FindYourMP::CacheWriter desc "Populate data for constituencies in DB" task :constituencies => :environment do load_constituencies end desc "Populate data for members in DB" task :members => :environment do file = ENV['file'] load_members file end desc "Create cache of all postcode pages" task :make_cache => :environment do make_cache end desc "Parse data file for postcode and constituency ID *only*" task :parse_postcodes do source_file = ENV['source'] if source_file parse_postcodes source_file else puts 'USAGE: rake fymp:parse source=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end - + desc "Update postcodes from data files for postcode and constituency ID *only*" task :diff_postcodes => :environment do old_file = ENV['old'] new_file = ENV['new'] if old_file && new_file diff_postcodes old_file, new_file else puts 'USAGE: rake fymp:diff_postcodes old=data/NSPDF_FEB_2009_UK_1M.txt new=data/NSPDF_MAY_2009_UK_1M_FP.txt' end end desc "Update postcodes from data files for postcode and constituency ID *only*" task :update_postcodes => :environment do puts 'USAGE: rake fymp:update_postcodes' update_postcodes end desc "Populate data for postcode and constituency ID in DB" task :populate => :environment do load_postcodes end desc "Populate the postcode districts table" task :load_postcode_districts => :environment do load_postcode_districts end + desc "Populate the manually added postcodes" + task :load_manual_postcodes => :environment do + load_manual_postcodes + end + desc "Populate the upmystreet lookup table" task :load_upmystreet_lookup => :environment do load_upmystreetcodes end end diff --git a/spec/models/manual_postcode_spec.rb b/spec/models/manual_postcode_spec.rb new file mode 100644 index 0000000..a763548 --- /dev/null +++ b/spec/models/manual_postcode_spec.rb @@ -0,0 +1,61 @@ +require File.dirname(__FILE__) + '/../spec_helper' + +describe ManualPostcode do + + describe 'when asked to add a manual postcode' do + before do + @code = 'BA140AB' + @constituency_id = 506 + @ons_id = 111 + + @postcode = mock_model(Postcode, :code => @code, :constituency_id => @constituency_id, :ons_id => @ons_id) + @manual_postcode = mock_model(ManualPostcode, :code => @code, :constituency_id => @constituency_id, :ons_id => @ons_id) + end + + it 'should create new Postcode and ManualPostcode records if neither pre-exist' do + Postcode.should_receive(:find_by_code).once.and_return nil + ManualPostcode.should_receive(:find_by_code).once.and_return nil + ManualPostcode.should_receive(:create).and_return @manual_postcode + Postcode.should_receive(:create).and_return @postcode + + ManualPostcode.add_manual_postcode(@code, @constituency_id, @ons_id).should == true + end + + it 'should just create a new postcode if the ManualPostcode record already exists' do + Postcode.should_receive(:find_by_code).once.and_return nil + ManualPostcode.should_receive(:find_by_code).once.and_return @manual_postcode + Postcode.should_receive(:create).and_return @postcode + ManualPostcode.should_not_receive(:create) + + ManualPostcode.add_manual_postcode(@code, @constituency_id, @ons_id).should == true + end + + it 'should not perform any updates if the Postcode already exists' do + Postcode.should_receive(:find_by_code).once.and_return @postcode + ManualPostcode.should_not_receive(:create) + Postcode.should_not_receive(:create) + + ManualPostcode.add_manual_postcode(@code, @constituency_id, @ons_id).should == true + end + + it 'should not update Postcode if a ManualPostcode insert fails' do + Postcode.should_receive(:find_by_code).once.and_return nil + ManualPostcode.should_receive(:find_by_code).once.and_return nil + ManualPostcode.should_receive(:create).with(:code => @code, :constituency_id => @constituency_id, :ons_id => nil) + Postcode.should_not_receive(:create) + + ManualPostcode.add_manual_postcode(@code, @constituency_id, nil).should == false + end + + it 'should remove the new ManualPostcode if inserting new Postcode fails' do + Postcode.should_receive(:find_by_code).once.and_return nil + ManualPostcode.should_receive(:find_by_code).once.and_return nil + ManualPostcode.should_receive(:create).and_return @manual_postcode + Postcode.should_receive(:create).and_return nil + @manual_postcode.should_receive(:delete) + + ManualPostcode.add_manual_postcode(@code, @constituency_id, @ons_id).should == false + end + end + +end \ No newline at end of file
nlehuen/pytst
fc62cc67dd634759b45ecf4f79fef0ac9c683b4a
MIT License
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..75d312c --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (C) 2004-2012 Nicolas Lehuen <nicolas@lehuen.com> + +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. \ No newline at end of file
nlehuen/pytst
e7b42350bc0ae1b74d75ce63f139ba611bc11216
Small change in the algorithm to factor the exit code.
diff --git a/include/tst.h b/include/tst.h index 2b92538..b239b5d 100644 --- a/include/tst.h +++ b/include/tst.h @@ -1,552 +1,552 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __TST__H_INCLUDED__ #define __TST__H_INCLUDED__ const char* const TST_VERSION = "1.18"; #include "debug.h" #include <iostream> #ifdef __PYTHON__BUILD__ #include "Python.h" #define tst_malloc PyMem_Malloc #define tst_realloc PyMem_Realloc #define tst_free PyMem_Free // Add / remove SCANNER functions - // #define SCANNER + #define SCANNER #else #include "stdlib.h" #define tst_malloc malloc #define tst_realloc realloc #define tst_free free - // Pour ajouter/supprimer les fonctions de scanning. + // Add / remove SCANNER functions // #define SCANNER #endif template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst; #include "fundamentals.h" #include "memory_storage.h" #include "iterators.h" template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst { public: friend class lexical_iterator<charT,valueT,storageT,serializerT,stringT>; friend class match_iterator<charT,valueT,storageT,serializerT,stringT>; typedef charT character_type; typedef valueT value_type; typedef storageT storage_type; typedef serializerT serializer_type; tst(); virtual ~tst() { delete storage; } void pack() { storage->pack(root); } valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,const stringT & string) const; valueT close_match(const stringT & string,int maximum_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT prefix_match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT get(const stringT & string) const; valueT get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory); valueT put(const stringT & string,valueT data); void remove(const stringT & string); bool contains(const stringT & string) const; void write(std::ostream &file) const; void read(std::istream &file); lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator() const { stringT key; return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,key,root); } lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; find_node(&current_index,&best_node,string); return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,string.substr(0,string.size()-1),current_index); } match_iterator<charT,valueT,storageT,serializerT,stringT> close_match_iterator(const stringT & string,int distance) const { return match_iterator<charT,valueT,storageT,serializerT,stringT>(this,string,distance,root); } int get_number_of_nodes() const { return storage->size(); } valueT get_default_value() const { return default_value; } #ifdef SCANNER valueT scan(const stringT & string,tst_action<charT,valueT,stringT>* to_perform); valueT scan_with_stop_chars(const stringT & string,const stringT& stop_chars,tst_action<charT,valueT,stringT>* to_perform) const; #endif protected: void set_storage(storageT* new_storage) { delete storage; storage = new_storage; } private: storageT* storage; valueT default_value; int root; void walk_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void close_match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,const size_t position, const int distance, const int remaining_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_joker_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_star_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; int build_node(node_info<charT,valueT>* current_node,const stringT & string,size_t current_position); void remove_node(int* current_index,const stringT & string,const size_t position); int find_char(tst_node<charT,valueT>** current_node, charT c) const; tst_node<charT,valueT>* find_node(int* current_index,int* best_node, const stringT & string) const; void balance_node(node_info<charT,valueT>* bal); void ll(node_info<charT,valueT>* bal); void rr(node_info<charT,valueT>* bal); void lr(node_info<charT,valueT>* bal); void rl(node_info<charT,valueT>* bal); void compute_height_and_balance(node_info<charT,valueT>* current_node_info) const; void write_node(std::ostream& file,serializerT* writer,int index) const; int read_node(std::istream& file,serializerT* reader,int depth); #ifdef SCANNER void compute_backtrack(tst_node<charT,valueT> *current_node,const stringT & string,int si_match_start,int si_match_end); #endif }; template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst<charT,valueT,storageT,serializerT,stringT>::tst() : storage(new storage_type(16)), default_value() { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } /*************************** high-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return current_node->data; } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> bool tst<charT,valueT,storageT,serializerT,stringT>::contains(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return true; } else { return false; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::put(const stringT & string,valueT data) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; return storage->get(node_index)->store(data); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; tst_node<charT,valueT>* current_node=storage->get(node_index); valueT data = current_node->data; if(data==default_value) { data=factory->perform(string,0,current_node->data); current_node->store(data); return data; } else { return data; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove(const stringT & string) { remove_node(&root,string,0); if(root==UNDEFINED_INDEX) { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } } /**************************** low-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst_node<charT,valueT>* tst<charT,valueT,storageT,serializerT,stringT>::find_node(int* current_index,int* best_node,const stringT & string) const { tst_node<charT,valueT>* current_node; int diff; size_t pos=0; while(*current_index!=UNDEFINED_INDEX) { current_node=storage->get(*current_index); if(current_node->c==0) { *current_index=UNDEFINED_INDEX; return 0; } else { diff=string[pos]-(current_node->c); } if(diff==0) { if(current_node->data!=default_value) { *best_node=*current_index; } ++pos; if(pos<string.size()) { *current_index = current_node->next; } else { return current_node; } } else if(diff>0) { *current_index=current_node->right; } else { *current_index=current_node->left; } } return 0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> int tst<charT,valueT,storageT,serializerT,stringT>::build_node(node_info<charT,valueT>* current_node_info,const stringT & string,size_t current_position) { int diff,result; if(current_node_info->node->c==0) { current_node_info->node->c=string[current_position]; #ifdef SCANNER current_node_info->node->position=current_position; #endif diff=0; } else { diff=string[current_position]-(current_node_info->node->c); } current_node_info->height=-1; current_node_info->balance_performed=0; if(diff==0) { ++current_position; compute_height_and_balance(current_node_info); // TODO : est-ce bien necessaire ? if(current_position<string.size()) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->next; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->next = next_node_info.index; return result; } else { return current_node_info->index; } } else if(diff>0) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->right; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->right = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->left==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = next_node_info.height; current_node_info->left_balance = 0; current_node_info->right_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->left; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = next_node_info.height-other_node_info.height; current_node_info->left_balance = other_node_info.balance; current_node_info->right_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } else { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->left; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->left = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->right==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = -next_node_info.height; current_node_info->right_balance = 0; current_node_info->left_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->right; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = other_node_info.height-next_node_info.height; current_node_info->right_balance = other_node_info.balance; current_node_info->left_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove_node(int* current_index,const stringT & string,const size_t current_position) { tst_node<charT,valueT>* current_node = storage->get(*current_index); int diff,*next_index; if(current_node->c==0) { return; } else { diff=string[current_position]-(current_node->c); } if(diff==0) { if(current_position+1<string.size()) { next_index = &(current_node->next); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position+1); } } else { current_node->store(default_value); } } else if(diff>0) { next_index = &(current_node->right); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } else { next_index = &(current_node->left); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } current_node=storage->get(*current_index); if( current_node->data==default_value && current_node->next==UNDEFINED_INDEX && current_node->right==UNDEFINED_INDEX && current_node->left==UNDEFINED_INDEX) { storage->delete_node(*current_index); *current_index=UNDEFINED_INDEX; } else { node_info<charT,valueT> current_node_info; current_node_info.index=*current_index; current_node_info.node=current_node; current_node_info.height=-1; balance_node(&current_node_info); *current_index = current_node_info.index; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::balance_node(node_info<charT,valueT>* bal) { if(bal->height==-1) { compute_height_and_balance(bal); } bal->balance_performed=0; if(bal->balance>1) { if(bal->right_balance>0) { rr(bal); } else { rl(bal); } bal->balance_performed=1; } else if(bal->balance<-1) { if(bal->left_balance<0) { ll(bal); } else { lr(bal); } bal->balance_performed=1; } assert(abs(bal->balance)<2); assert(abs(bal->right_balance)<2); assert(abs(bal->left_balance)<2); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::ll(node_info<charT,valueT>* bal) { int left_index=bal->node->left; tst_node<charT,valueT>* left_node=storage->get(left_index); int left_right_index=left_node->right; bal->node->left=left_right_index; left_node->right=bal->index; bal->index=left_index; bal->node=storage->get(left_index); bal->height=bal->height-1; bal->balance=0; bal->right_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rr(node_info<charT,valueT>* bal) { int right_index=bal->node->right; tst_node<charT,valueT>* right_node=storage->get(right_index); int right_left_index=right_node->left; bal->node->right=right_left_index; right_node->left=bal->index; bal->index=right_index; bal->node=storage->get(right_index); bal->height=bal->height-1; bal->balance=0; bal->left_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::lr(node_info<charT,valueT>* bal) { node_info<charT,valueT> left; left.index = bal->node->left; left.node = storage->get(left.index); rr(&left); bal->node->left=left.index; ll(bal); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rl(node_info<charT,valueT>* bal) { node_info<charT,valueT> right; right.index = bal->node->right; right.node = storage->get(right.index); ll(&right); bal->node->right=right.index; rr(bal); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::compute_height_and_balance(node_info<charT,valueT>* current_node_info) const { int left = current_node_info->node->left; int right = current_node_info->node->right; if(right!=UNDEFINED_INDEX) { node_info<charT,valueT> right_balance; right_balance.index=right; right_balance.node=storage->get(right); compute_height_and_balance(&right_balance); if(left!=UNDEFINED_INDEX) { node_info<charT,valueT> left_balance; left_balance.index=left; left_balance.node=storage->get(left); compute_height_and_balance(&left_balance); @@ -606,868 +606,872 @@ template<typename charT,typename valueT,typename storageT,typename serializerT, void tst<charT,valueT,storageT,serializerT,stringT>::close_match_recurse(tst_node<charT,valueT>* current_node,stringT& current_key,const stringT & string, const size_t position, const int distance, const int remaining_distance,tst_filter<charT,valueT,stringT>* filter, tst_action<charT,valueT,stringT>* to_perform) const { // LEFT int other_index=current_node->left; if (other_index!=UNDEFINED_INDEX) { close_match_recurse(storage->get(other_index),current_key,string,position,distance,remaining_distance,filter,to_perform); } int diff=1; if(position<string.size() && string[position]==current_node->c) { diff=0; } // ++KEY current_key.push_back(current_node->c); // CURRENT valueT data = current_node->data; if(data!=default_value) { int new_remaining_distance=string.size() - position - 1; if(new_remaining_distance<0) { new_remaining_distance = 0; } new_remaining_distance = remaining_distance - diff - new_remaining_distance; if(new_remaining_distance>=0) { if(filter) { data = filter->perform(current_key,distance-new_remaining_distance,data); } if(data!=default_value && to_perform) { to_perform->perform(current_key,distance-new_remaining_distance,data); } } } // CURRENT, NEXT other_index=current_node->next; if (other_index!=UNDEFINED_INDEX) { int new_remaining_distance = remaining_distance - diff; if (new_remaining_distance>=0) { close_match_recurse(storage->get(other_index),current_key,string,position+1,distance,new_remaining_distance,filter,to_perform); } } // SKIP_INPUT if(other_index!=UNDEFINED_INDEX && remaining_distance>0) { close_match_recurse(storage->get(other_index),current_key,string,position,distance,remaining_distance-1,filter,to_perform); } // --KEY current_key.resize(current_key.size()-1); // SKIP_BASE if(position<string.size() && remaining_distance>0) { close_match_recurse(current_node,current_key,string,position+1,distance,remaining_distance-1,filter,to_perform); } // RIGHT other_index = current_node->right; if(other_index!=UNDEFINED_INDEX) { close_match_recurse(storage->get(other_index),current_key,string,position,distance,remaining_distance,filter,to_perform); } } /**************************** match *************************************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const { stringT key; match_recurse(storage->get(root),key,string,0,filter,to_perform,false); if(to_perform) { return to_perform->result(); } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::match_recurse(tst_node<charT,valueT>* current_node,stringT& current_key,const stringT & string, size_t position,tst_filter<charT,valueT,stringT>* filter, tst_action<charT,valueT,stringT>* to_perform, bool advance) const { stringT this_key(current_key); while(true) { charT c = string[position]; switch(c) { case static_cast<charT>('?'): { match_joker_recurse(current_node,this_key,string,position,filter,to_perform,advance); return; } case static_cast<charT>('*'): { match_star_recurse(current_node,this_key,string,position,filter,to_perform,advance); return; } default: { int other_index; if(advance) { other_index = current_node->next; if(other_index!=UNDEFINED_INDEX) { current_node = storage->get(other_index); advance = false; } else { return; } } while(true) { if(c == current_node->c) { this_key.push_back(current_node->c); if(position==(string.size()-1)) { valueT data = current_node->data; if(data!=default_value) { if(filter) { data = filter->perform(this_key,0,data); } if(to_perform) { to_perform->perform(this_key,0,data); } } return; } else { ++position; advance = true; break; } } else if(c > current_node->c) { other_index = current_node->right; if(other_index!=UNDEFINED_INDEX) { current_node = storage->get(other_index); } else { return; } } else { other_index = current_node->left; if(other_index!=UNDEFINED_INDEX) { current_node = storage->get(other_index); } else { return; } } } } } } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::match_joker_recurse(tst_node<charT,valueT>* current_node,stringT& current_key,const stringT & string, size_t position,tst_filter<charT,valueT,stringT>* filter, tst_action<charT,valueT,stringT>* to_perform,bool advance) const { int other_index; if(advance) { other_index=current_node->next; if(other_index!=UNDEFINED_INDEX) { current_node = storage->get(other_index); } else { return; } } // LEFT other_index=current_node->left; if(other_index!=UNDEFINED_INDEX) { match_joker_recurse(storage->get(other_index),current_key,string,position,filter,to_perform,false); } // MATCH_CURRENT // ++KEY current_key.push_back(current_node->c); if(position==(string.size()-1)) { valueT data = current_node->data; if(data!=default_value) { if(filter) { data = filter->perform(current_key,0,data); } if(to_perform) { to_perform->perform(current_key,0,data); } } } else { match_recurse(current_node,current_key,string,position+1,filter,to_perform,true); } // --KEY current_key.resize(current_key.size()-1); // RIGHT other_index=current_node->right; if(other_index!=UNDEFINED_INDEX) { match_joker_recurse(storage->get(other_index),current_key,string,position,filter,to_perform,false); } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::match_star_recurse(tst_node<charT,valueT>* current_node,stringT& current_key,const stringT & string, size_t position,tst_filter<charT,valueT,stringT>* filter, tst_action<charT,valueT,stringT>* to_perform,bool advance) const { int other_index; if(advance) { // PREVIOUS_MATCH if(position==(string.size()-1)) { valueT data = current_node->data; if(data!=default_value) { if(filter) { data = filter->perform(current_key,0,data); } if(to_perform) { to_perform->perform(current_key,0,data); } } } other_index=current_node->next; if(other_index!=UNDEFINED_INDEX) { current_node = storage->get(other_index); } else { return; } } // MATCH_WITHOUT_ME match_recurse(current_node,current_key,string,position+1,filter,to_perform,false); // MATCH_CURRENT current_key.push_back(current_node->c); if(position==(string.size()-1)) { valueT data = current_node->data; if(data!=default_value) { if(filter) { data = filter->perform(current_key,0,data); } if(to_perform) { to_perform->perform(current_key,0,data); } } } // MATCH_SAME match_star_recurse(current_node,current_key,string,position,filter,to_perform,true); // MATCH_NEXT match_recurse(current_node,current_key,string,position+1,filter,to_perform,true); // --KEY current_key.resize(current_key.size()-1); // LEFT other_index=current_node->left; if(other_index!=UNDEFINED_INDEX) { match_star_recurse(storage->get(other_index),current_key,string,position,filter,to_perform,false); } // RIGHT other_index=current_node->right; if(other_index!=UNDEFINED_INDEX) { match_star_recurse(storage->get(other_index),current_key,string,position,filter,to_perform,false); } } /**************************** walk *************************************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const { stringT key; walk_recurse(storage->get(root),key,filter,to_perform); if(to_perform) { return to_perform->result(); } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,const stringT & string) const { int index = root; int best_node = UNDEFINED_INDEX; tst_node<charT,valueT>* start = find_node(&index,&best_node,string); if(start) { valueT data = start->data; if(data!=default_value) { if(filter) { data = filter->perform(string,0,data); } if(to_perform) { to_perform->perform(string,0,data); } } index = start->next; if(index!=UNDEFINED_INDEX) { stringT key(string); walk_recurse(storage->get(index),key,filter,to_perform); } } if(to_perform) { return to_perform->result(); } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::walk_recurse(tst_node<charT,valueT>* current_node,stringT& current_key,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const { int other_index; other_index=current_node->left; if(other_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(other_index),current_key,filter,to_perform); } // ++KEY current_key.push_back(current_node->c); valueT data = current_node->data; if(data!=default_value) { if(filter) { data = filter->perform(current_key,0,data); } if(to_perform) { to_perform->perform(current_key,0,data); } } other_index=current_node->next; if(other_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(other_index),current_key,filter,to_perform); } // --KEY current_key.resize(current_key.size()-1); other_index=current_node->right; if(other_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(other_index),current_key,filter,to_perform); } } /**************************** prefix_match *************************************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::prefix_match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const { stringT current_key; size_t position=0; valueT biggest=default_value; int biggest_length=0; int current_index=root; tst_node<charT,valueT>* current_node; int diff; charT c; while(position<string.size()) { c = string[position]; ++position; current_key.push_back(c); while(current_index!=UNDEFINED_INDEX) { current_node=storage->get(current_index); diff=c-current_node->c; if(diff==0) { if(current_node->data!=default_value) { biggest=current_node->data; biggest_length=current_key.size(); if(filter) { biggest=filter->perform(current_key.substr(0,biggest_length),0,biggest); } } if(position<string.size()) { current_index=current_node->next; break; } else { if(biggest!=default_value && to_perform) { to_perform->perform(current_key.substr(0,biggest_length),0,biggest); } current_index=current_node->next; if(current_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(current_index),current_key,filter,to_perform); } return to_perform->result(); } } else if(diff>0) { current_index=current_node->right; } else { current_index=current_node->left; } } if(current_index==UNDEFINED_INDEX) { break; } } if(biggest!=default_value && to_perform) { to_perform->perform(current_key.substr(0,biggest_length),0,biggest); } return to_perform->result(); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> inline int tst<charT,valueT,storageT,serializerT,stringT>::find_char(tst_node<charT,valueT> **n_current, charT c) const { while(1) { int diff = c - (*n_current)->c; if(diff == 0) { return 1; } else { int ni_next; if(diff>0) { ni_next = (*n_current)->right; } else { ni_next = (*n_current)->left; } if(ni_next==UNDEFINED_INDEX) { *n_current = storage->get(root); return 0; } else { *n_current = storage->get(ni_next); } } } } /**************************** scan *************************************/ #ifdef SCANNER template<typename charT,typename valueT,typename stringT> inline void emit(int match,const stringT & string,size_t start, size_t stop,valueT value,tst_action<charT,valueT,stringT>* to_perform) { size_t length = stop-start; if(length>0) { to_perform->perform(string.substr(start,length), match * length, value); } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::scan(const stringT & string,tst_action<charT,valueT,stringT>* to_perform) { // NOTE : yes, this code uses goto. // It's actually FTW because it simplifies the code instead of // forcing the abusive use of break, continue, all the more // that C++ doesn't support labeled continue. // To make sense of it all, you can have a look at // the file scan algorithm.graphml // with yED : http://www.yworks.com/en/products_yed_about.html // This way you can match nodes from the graph with the code below using the // labels (A), (B), etc. // Current position in the input string size_t si=0; // First string index for a non match size_t si_nm=0; // First string index for a match int si_ms=UNDEFINED_INDEX; // Best match int si_bme=UNDEFINED_INDEX; tst_node<charT,valueT> *n_best_match = NULL; // Current node tst_node<charT,valueT> *n_current = storage->get(root); // Main loop MAIN: { // // NON-MATCH state // assert(si_ms == UNDEFINED_INDEX); // (A) check input if(si < string.size()) { if(find_char(&n_current,string[si])) { // (B) found si_ms = si; ++si; // this goto is implicit // goto POTENTIAL_MATCH; } else { // (C) not found ++si; goto MAIN; } } else { // (D) end input - emit(-1,string,si_nm,si,default_value,to_perform); - return to_perform->result(); + goto EXIT; } POTENTIAL_MATCH: { // // POTENTIAL_MATCH state // assert(si_ms != UNDEFINED_INDEX); // (E) check data if(n_current->data != default_value) { // (F) store best match si_bme = si; n_best_match = n_current; } // (G) move next ? n_current = storage->get(n_current->next); if(n_current != NULL) { // (H) check input if(si < string.size()) { if(find_char(&n_current, string[si])) { // (L) ++si; goto POTENTIAL_MATCH; } else { goto END_MATCH; } } else { // (M) end match if(si_bme!=UNDEFINED_INDEX) { goto EMIT_AND_LOOP; } else { // (N) - emit(-1,string,si_nm,si,default_value,to_perform); + goto EXIT; } - return to_perform->result(); } } else END_MATCH: { // (I) end match if(si_bme!=UNDEFINED_INDEX) EMIT_AND_LOOP: { // (J) emit and loop emit(-1,string,si_nm,si_ms,default_value,to_perform); emit(1,string,si_ms,si_bme,n_best_match->data,to_perform); si = si_bme; si_nm = si; si_ms = UNDEFINED_INDEX; si_bme = UNDEFINED_INDEX; n_current = storage->get(root); goto MAIN; } else { // (K) backtrack // TODO : prevent backtrack using tree analysis si = si_ms + 1; si_ms = UNDEFINED_INDEX; si_bme = UNDEFINED_INDEX; n_current = storage->get(root); goto MAIN; } } // (I) } // (E) } // MAIN + + EXIT: + { + emit(-1,string,si_nm,si,default_value,to_perform); + return to_perform->result(); + } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::scan_with_stop_chars(const stringT & string,const stringT& stop_chars,tst_action<charT,valueT,stringT>* to_perform) const { // Le premier caractère de la chaine ne correspondant pas à un match size_t si_non_match_start=0; // Le noeud pour lequel on a enregistré un match (noeud avec un objet associé) int ni_best_match=UNDEFINED_INDEX; // Le premier caractère de la chaine correspondant à un match int si_match_start=UNDEFINED_INDEX; // La position actuelle dans la chaîne (index) size_t si_current=0; // Le numéro du noeud actuel de l'arbre int ni_current=root; // Le noeud actuel de l'arbre tst_node<charT,valueT> *n_current; // Boucle principale while(1) { n_current=storage->get(ni_current); // On avance dans l'arbre d'un cran if(si_current<string.size()) { int diff = string[si_current]-n_current->c; if(diff>0) { ni_current = n_current->right; } else if(diff<0) { ni_current = n_current->left; } else { // ok, le caractère courant est accepté if(si_match_start==UNDEFINED_INDEX) { // On teste si le début de match est le début de chaine ou après un stop_char if(si_current==0 || stop_chars.find(string[si_current-1])<stop_chars.size()) { // oui, on enregistre le début si_match_start=si_current; } else { // non, on passe à la suite ++si_current; } } if(si_match_start!=UNDEFINED_INDEX) { // si le démarrage a bien pris if(n_current->data!=default_value && (si_current==(string.size()-1) || stop_chars.find(string[si_current+1])<stop_chars.size())) { // on a une donnée dans le noeud courant // et on est en fin de chaîne ou le caractère précédent est un stop_char ni_best_match = ni_current; } ++si_current; if(si_current<string.size()) { // Si on peut avancer, on avance ni_current = n_current->next; } else { // Fin de chaine ==> pas de match possible ni_current = UNDEFINED_INDEX; } } } } else { // On est toujours en fin de chaine ==> pas de match possible ni_current = UNDEFINED_INDEX; } if(ni_current==UNDEFINED_INDEX) { // Le caractère courant n'est pas accepté if(ni_best_match!=UNDEFINED_INDEX) { // Si on a un match réussi en cours // Si le match en cours démarre après la zone de non-match // C'est qu'on a bien une zone de non-match int non_match_length = si_match_start-si_non_match_start; if(non_match_length>0) { // On l'envoie. to_perform->perform(string.substr(si_non_match_start,non_match_length),-non_match_length,default_value); } // On envoie maintenant le match // On connait sa longueur grâce à la position dans l'arbre // TODO: voir si on ne pourrait pas de passer de ça tst_node<charT,valueT> *match_node=storage->get(ni_best_match); int match_length = match_node->position+1; // On envoie le match to_perform->perform(string.substr(si_match_start,match_length),match_length,match_node->data); // On repositionne la zone de non-match juste après la fin du match si_non_match_start=si_match_start+match_length; // Annulation du match ni_best_match=UNDEFINED_INDEX; // On backtracke // backtrack de naze parce qu'on ne peut pas utiliser // les infos de backtrack à cause des séparateurs. si_current = si_non_match_start; ni_current = root; ni_best_match=UNDEFINED_INDEX; si_match_start=UNDEFINED_INDEX; } else if(si_match_start!=UNDEFINED_INDEX) { // Si le caractère courant n'est pas accepté, qu'on avait commencé // un match mais que celui-ci n'avait pas réussi, on va backtracker. // backtrack de naze parce qu'on ne peut pas utiliser // les infos de backtrack à cause des séparateurs. si_current=si_match_start+1; ni_current = root; ni_best_match=UNDEFINED_INDEX; si_match_start=UNDEFINED_INDEX; } else { // le caractère courant n'est pas accepté et on n'avait pas de match en cours if(si_current<string.size()) { // si on peut avancer d'un caractère on le fait ++si_current; // on revient à la racine ni_current = root; } else { // si on est à la fin de la chaîne on sort de la boucle pour la fin. break; } } } else { // on avance tranquillement dans l'arbre... } } // on n'arrive ici que si on est arrivé à la fin de la chaine en entrée if((si_current - si_non_match_start)>0) { // charT'il y avait un non-match en cours // on l'envoie to_perform->perform(string.substr(si_non_match_start,si_current - si_non_match_start),-static_cast<int>(si_current - si_non_match_start),default_value); } return to_perform->result(); } #endif /**************************** file I/O *************************************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::read(std::istream& file) { // We check the version number int version_length; file.read((char*)(&version_length),sizeof(size_t)); char* version=(char*)tst_malloc(version_length+1); version[version_length]=0; assert(version); file.read(version,version_length); if(strcmp(TST_VERSION,version)!=0) { tst_free(version); throw TSTException("Invalid version number"); } else { tst_free(version); } serializerT reader; default_value = reader.read(file); // On efface le stockage storage->erase(); if(file.get()) { root = read_node(file,&reader,0); } else { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> int tst<charT,valueT,storageT,serializerT,stringT>::read_node(std::istream& file,serializerT* reader,int depth) { char bitmask = file.get(); node_info<charT,valueT> node_info; storage->new_node(&node_info); file.read((char*)(&(node_info.node->c)),sizeof(charT)); if(bitmask & 16) { node_info.node->store(reader->read(file)); } else { node_info.node->store(default_value); } #ifdef SCANNER // TODO : inutile, peut être recalculé ? file.read((char*)(&(node_info.node->position)),sizeof(int)); #endif int other_index; if(bitmask & 1) { // En deux étapes car le noeud peut bouger physiquement. // Normalement tout se passe bien mais c'est plus rassurant ainsi. other_index = read_node(file,reader,depth+1); storage->get(node_info.index)->next = other_index; } else { storage->get(node_info.index)->next = UNDEFINED_INDEX; } if(bitmask & 2) { other_index = read_node(file,reader,depth+1); storage->get(node_info.index)->left = other_index; } else { storage->get(node_info.index)->left = UNDEFINED_INDEX; } if(bitmask & 4) { other_index = read_node(file,reader,depth+1); storage->get(node_info.index)->right = other_index; } else { storage->get(node_info.index)->right = UNDEFINED_INDEX; } return node_info.index; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::write(std::ostream& file) const { // We save the version number size_t version_length = strlen(TST_VERSION); file.write((char*)(&version_length),sizeof(size_t)); file.write(TST_VERSION,(std::streamsize)version_length); serializerT writer; writer.write(file,default_value); if(root!=UNDEFINED_INDEX) { file.put(1); write_node(file,&writer,root); } else { file.put(0); } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::write_node(std::ostream& file,serializerT* writer,int index) const { tst_node<charT,valueT>* node = storage->get(index); char bitmask=0; if(node->next!=UNDEFINED_INDEX) bitmask |= 1; if(node->left!=UNDEFINED_INDEX) bitmask |= 2; if(node->right!=UNDEFINED_INDEX) bitmask |= 4; if(node->data!=default_value) bitmask |=16; file.put(bitmask); file.write((char*)(&(node->c)),sizeof(charT)); if(bitmask & 16) { writer->write(file,node->data); } #ifdef SCANNER file.write((char*)(&(node->position)),sizeof(int)); #endif if(bitmask & 1) write_node(file,writer,node->next); if(bitmask & 2) write_node(file,writer,node->left); if(bitmask & 4) write_node(file,writer,node->right); } #endif diff --git a/python/pythonTST.vcproj b/python/pythonTST.vcproj index cfc9adf..9c7d490 100644 --- a/python/pythonTST.vcproj +++ b/python/pythonTST.vcproj @@ -1,463 +1,463 @@ <?xml version="1.0" encoding="Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="9,00" Name="pythonTST" ProjectGUID="{A5208316-015E-4611-B812-6E2F7CCD33A2}" RootNamespace="pythonTST" Keyword="Win32Proj" TargetFrameworkVersion="131072" > <Platforms> <Platform Name="Win32" /> </Platforms> <ToolFiles> </ToolFiles> <Configurations> <Configuration Name="Debug|Win32" OutputDirectory="Debug" IntermediateDirectory="Debug" ConfigurationType="2" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" UseOfMFC="0" CharacterSet="2" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="D:\projets\python-svn\PC;D:\projets\python-svn\Include;..\include" PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS;SCANNER" MinimalRebuild="false" BasicRuntimeChecks="3" RuntimeLibrary="1" BufferSecurityCheck="true" RuntimeTypeInfo="true" UsePrecompiledHeader="0" DebugInformationFormat="3" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/_tst_d.pyd" LinkIncremental="1" AdditionalLibraryDirectories="&quot;D:\projets\python-svn\PCbuild&quot;" GenerateDebugInformation="true" ProgramDatabaseFile="$(OutDir)/_tst_d.pdb" GenerateMapFile="true" MapExports="true" SubSystem="2" RandomizedBaseAddress="1" DataExecutionPrevention="0" ImportLibrary="$(OutDir)/pyd.lib" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> <Configuration Name="Release|Win32" OutputDirectory="Release" IntermediateDirectory="Release" ConfigurationType="2" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" CharacterSet="2" WholeProgramOptimization="1" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="3" InlineFunctionExpansion="2" EnableIntrinsicFunctions="true" FavorSizeOrSpeed="1" AdditionalIncludeDirectories="E:\Python24\include;..\include" PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" RuntimeLibrary="0" StructMemberAlignment="1" UsePrecompiledHeader="0" WarningLevel="3" Detect64BitPortabilityProblems="true" DebugInformationFormat="3" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/_tst.pyd" LinkIncremental="1" AdditionalLibraryDirectories="E:\Python24\libs" GenerateDebugInformation="true" SubSystem="2" OptimizeReferences="2" EnableCOMDATFolding="2" RandomizedBaseAddress="1" DataExecutionPrevention="0" ImportLibrary="$(OutDir)/pyd.lib" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> <Configuration Name="Debug CRM|Win32" OutputDirectory="$(ConfigurationName)" IntermediateDirectory="$(ConfigurationName)" ConfigurationType="2" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" UseOfMFC="0" CharacterSet="2" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" CommandLine="" AdditionalDependencies="" Outputs="" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="&quot;E:\projets\Python-2.6.4\include&quot;;&quot;E:\projets\Python-2.6.4\PC&quot;;..\include" PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" MinimalRebuild="false" BasicRuntimeChecks="3" RuntimeLibrary="1" BufferSecurityCheck="true" RuntimeTypeInfo="true" UsePrecompiledHeader="0" WarningLevel="3" Detect64BitPortabilityProblems="true" DebugInformationFormat="3" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/_tst_d.pyd" LinkIncremental="1" AdditionalLibraryDirectories="&quot;E:\projets\Python-2.6.4\PCbuild&quot;" GenerateDebugInformation="true" ProgramDatabaseFile="$(OutDir)/_tst_d.pdb" GenerateMapFile="true" MapExports="true" SubSystem="2" RandomizedBaseAddress="1" DataExecutionPrevention="0" ImportLibrary="$(OutDir)/pyd.lib" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> <Configuration Name="Release CRM|Win32" OutputDirectory="$(ConfigurationName)" IntermediateDirectory="$(ConfigurationName)" ConfigurationType="2" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" CharacterSet="2" WholeProgramOptimization="1" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="3" InlineFunctionExpansion="2" EnableIntrinsicFunctions="true" FavorSizeOrSpeed="1" AdditionalIncludeDirectories="C:\Python24\include;..\include" PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" RuntimeLibrary="0" StructMemberAlignment="1" UsePrecompiledHeader="0" WarningLevel="3" Detect64BitPortabilityProblems="true" DebugInformationFormat="3" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/_tst.pyd" LinkIncremental="1" AdditionalLibraryDirectories="C:\Python24\libs" GenerateDebugInformation="true" SubSystem="2" OptimizeReferences="2" EnableCOMDATFolding="2" RandomizedBaseAddress="1" DataExecutionPrevention="0" ImportLibrary="$(OutDir)/pyd.lib" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> </Configurations> <References> </References> <Files> <Filter Name="Source Files" Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" > <File RelativePath=".\bug.py" > </File> <File RelativePath=".\test\test.py" > </File> <File RelativePath=".\tst.i" > <FileConfiguration Name="Debug|Win32" > <Tool Name="VCCustomBuildTool" - CommandLine="E:\swigwin-1.3.40\swig -c++ -O -DSCANNER -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" + CommandLine="E:\swigwin-1.3.39\swig -c++ -O -DSCANNER -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" AdditionalDependencies="..\include\tst.h;pythonTST.h" Outputs="tst_wrap.cxx" /> </FileConfiguration> <FileConfiguration Name="Release|Win32" > <Tool Name="VCCustomBuildTool" - CommandLine="E:\swigwin-1.3.40\swig -O -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" + CommandLine="E:\swigwin-1.3.39\swig -O -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" AdditionalDependencies="..\tst.h;pythonTST.h" Outputs="tst_wrap.cxx" /> </FileConfiguration> <FileConfiguration Name="Debug CRM|Win32" > <Tool Name="VCCustomBuildTool" - CommandLine="E:\swigwin-1.3.40\swig -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" + CommandLine="E:\swigwin-1.3.39\swig -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" AdditionalDependencies="..\include\tst.h;pythonTST.h" Outputs="tst_wrap.cxx" /> </FileConfiguration> <FileConfiguration Name="Release CRM|Win32" > <Tool Name="VCCustomBuildTool" - CommandLine="E:\swigwin-1.3.40\swig -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" + CommandLine="E:\swigwin-1.3.39\swig -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" AdditionalDependencies="..\tst.h;pythonTST.h" Outputs="tst_wrap.cxx" /> </FileConfiguration> </File> <File RelativePath=".\tst.py" > </File> <File RelativePath=".\tst_wrap.cxx" > </File> </Filter> <Filter Name="Header Files" Filter="h;hpp;hxx;hm;inl;inc;xsd" UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" > <File RelativePath="..\include\debug.h" > </File> <File RelativePath="..\include\fundamentals.h" > </File> <File RelativePath=".\PythonReference.h" > </File> <File RelativePath=".\pythonTST.h" > </File> <File RelativePath="..\include\tst.h" > </File> </Filter> <Filter Name="Resource Files" Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx" UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}" > </Filter> </Files> <Globals> </Globals> </VisualStudioProject> diff --git a/scan algorithm.graphml b/scan algorithm.graphml index c37ed3d..e6291ca 100644 --- a/scan algorithm.graphml +++ b/scan algorithm.graphml @@ -1,540 +1,515 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd"> <!--Created by yFiles for Java 2.7--> <key for="graphml" id="d0" yfiles.type="resources"/> <key attr.name="url" attr.type="string" for="node" id="d1"/> <key attr.name="description" attr.type="string" for="node" id="d2"/> <key for="node" id="d3" yfiles.type="nodegraphics"/> <key attr.name="url" attr.type="string" for="edge" id="d4"/> <key attr.name="description" attr.type="string" for="edge" id="d5"/> <key for="edge" id="d6" yfiles.type="edgegraphics"/> <graph edgedefault="directed" id="G"> <node id="n0"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="132.20703125" width="90.001953125" x="422.3133091517857" y="0.0"/> + <y:Geometry height="132.20703125" width="90.001953125" x="475.6902932787698" y="0.0"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="92.20703125" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="50.001953125" x="20.0" y="20.0">START : NM = 0 MS = -1 BM = -1 n = root i = 0</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n1"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="104.703125" x="401.8750248015873" y="192.20703125"/> + <y:Geometry height="73.40234375" width="104.703125" x="455.25200892857146" y="192.20703125"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.703125" x="20.0" y="20.0">(A) check input</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n2"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="60.681640625" x="526.5635447668651" y="356.6611328125"/> + <y:Geometry height="73.40234375" width="60.681640625" x="546.3079892113095" y="356.6611328125"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="20.681640625" x="20.0" y="20.0">(C) i++</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n3"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="104.673828125" x="401.8896732390873" y="356.6611328125"/> - <y:Fill color="#FFCC00" transparent="false"/> - <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.673828125" x="20.0" y="20.0">(D) -emit 0,NM,i</y:NodeLabel> - <y:Shape type="parallelogram"/> - </y:ShapeNode> - </data> - </node> - <node id="n4"> - <data key="d3"> - <y:ShapeNode> - <y:Geometry height="73.40234375" width="119.71484375" x="241.57749875992062" y="487.41392299107133"/> + <y:Geometry height="73.40234375" width="119.71484375" x="217.4219432043651" y="487.41392299107144"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="79.71484375" x="20.0" y="20.0">(E) check n-&gt;data</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> - <node id="n5"> + <node id="n4"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="104.703125" x="239.84446924603174" y="915.672581845238"/> + <y:Geometry height="73.40234375" width="104.703125" x="239.84446924603174" y="915.6727120535714"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.703125" x="20.0" y="20.0">(H) check input</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> - <node id="n6"> + <node id="n5"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="60.681640625" x="358.5448939732143" y="1092.776097470238"/> + <y:Geometry height="73.40234375" width="60.681640625" x="358.5448939732143" y="1092.7762276785716"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="20.681640625" x="20.0" y="20.0">(L) i++</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> - <node id="n7"> + <node id="n6"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="58.701171875" width="69.3359375" x="402.2244915674603" y="1452.385472470238"/> + <y:Geometry height="58.701171875" width="69.3359375" x="446.7669518849206" y="1437.3856026785716"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="29.3359375" x="20.0" y="20.0">END</y:NodeLabel> <y:Shape type="ellipse"/> </y:ShapeNode> </data> </node> - <node id="n8"> + <node id="n7"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="78.341796875" x="198.3417999751984" y="644.5174386160713"/> + <y:Geometry height="73.40234375" width="78.341796875" x="268.0370380704365" y="644.5174386160714"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="38.341796875" x="20.0" y="20.0">(F) BM = i</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> - <node id="n9"> + <node id="n8"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="109.3671875" x="210.1707713293651" y="767.919652157738"/> + <y:Geometry height="73.40234375" width="109.3671875" x="210.1707713293651" y="767.9197823660714"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="69.3671875" x="20.0" y="20.0">(G) move next ?</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> - <node id="n10"> + <node id="n9"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="88.103515625" width="120.0078125" x="179.01593501984127" y="1284.879613095238"/> + <y:Geometry height="88.103515625" width="120.0078125" x="179.01593501984127" y="1269.8797433035716"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="48.103515625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="80.0078125" x="20.0" y="20.0">(J) emit 0,NM,MS emit 1,MS,BM</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> - <node id="n11"> + <node id="n10"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="88.103515625" width="78.341796875" x="232.33545076884923" y="349.310546875"/> + <y:Geometry height="88.103515625" width="78.341796875" x="208.17989521329366" y="349.310546875"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="48.103515625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="38.341796875" x="20.0" y="20.0">(B) MS = i i++</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> - <node id="n12"> + <node id="n11"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="92.697265625" x="131.59938306051586" y="1092.776097470238"/> + <y:Geometry height="73.40234375" width="92.697265625" x="131.59938306051586" y="1092.7762276785716"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="52.697265625" x="20.0" y="20.0">(I) BM&gt;=0 ?</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> - <node id="n13"> + <node id="n12"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="117.505859375" width="124.015625" x="35.000124007936506" y="1270.178441220238"/> + <y:Geometry height="117.505859375" width="124.015625" x="35.000124007936506" y="1255.1785714285716"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="77.505859375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="84.015625" x="20.0" y="20.0">(K) BACKTRACK : i=MS+1 MS = -1 n = root</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> - <node id="n14"> + <node id="n13"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="92.697265625" x="245.84739893353174" y="1092.776097470238"/> + <y:Geometry height="73.40234375" width="92.697265625" x="245.84739893353174" y="1092.7762276785716"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="52.697265625" x="20.0" y="20.0">(M) BM&gt;=0 ?</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> - <node id="n15"> + <node id="n14"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="117.505859375" width="87.669921875" x="195.18488033234127" y="1422.983128720238"/> + <y:Geometry height="117.505859375" width="87.669921875" x="195.18488033234127" y="1407.9832589285716"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="77.505859375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="47.669921875" x="20.0" y="20.0">(J) i=BM NM=BM MS=-1 n=root</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> - <node id="n16"> + <node id="n15"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="104.673828125" x="329.55237165178573" y="1292.230199032738"/> + <y:Geometry height="73.40234375" width="104.673828125" x="429.0980065724206" y="1277.2303292410716"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.673828125" x="20.0" y="20.0">(N) emit 0,NM,i</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <edge id="e0" source="n1" target="n2"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="34.901041666666686" sy="12.232421875" tx="0.0" ty="-36.701171875"> - <y:Point x="489.127628968254" y="290.609375"/> - <y:Point x="556.904206969246" y="290.609375"/> + <y:Point x="542.5046130952381" y="290.609375"/> + <y:Point x="576.6486514136905" y="290.609375"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7975265623853919" textColor="#000000" visible="true" width="54.044921875" x="11.73170633340618" y="68.53323364257812">not found</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.733852288392566" textColor="#000000" visible="true" width="54.044921875" x="-21.9008633823056" y="68.53323364257812">not found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e1" source="n2" target="n1"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="36.701171875" tx="39.263671875" ty="-9.169921875"> - <y:Point x="556.9043650793651" y="455.0634765625"/> - <y:Point x="607.245238095238" y="455.0634765625"/> - <y:Point x="607.245238095238" y="167.20703125"/> - <y:Point x="493.4902591765873" y="167.20703125"/> + <y:Path sx="0.0" sy="36.701171875" tx="39.26367187500006" ty="-9.169921875"> + <y:Point x="576.6488095238095" y="455.0634765625"/> + <y:Point x="626.9896825396826" y="455.0634765625"/> + <y:Point x="626.9896825396826" y="167.20703125"/> + <y:Point x="546.8672433035715" y="167.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e2" source="n1" target="n3"> + <edge id="e2" source="n1" target="n15"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="36.701171875" tx="0.0" ty="-36.701171875"/> + <y:Path sx="0.0" sy="36.701171875" tx="26.16845703125" ty="-36.701171875"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5" textColor="#000000" visible="true" width="53.376953125" x="-55.376958840990824" y="36.17529296875">end input</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5263157894736842" textColor="#000000" visible="true" width="53.376953125" x="-55.37706193144396" y="522.0564644031956">end input</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e3" source="n0" target="n1"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="66.103515625" tx="13.087919957398071" ty="-27.544921875046924"/> + <y:Path sx="0.0" sy="66.103515625" tx="13.087919957398128" ty="-27.544921875046924"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e4" source="n5" target="n6"> + <edge id="e4" source="n4" target="n5"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="34.901041666666686" sy="12.232421875" tx="0.0" ty="-36.701171875"> - <y:Point x="327.0970734126984" y="1014.074925595238"/> - <y:Point x="388.88568018353175" y="1014.074925595238"/> + <y:Point x="327.0970734126984" y="1014.0750558035714"/> + <y:Point x="388.88568018353175" y="1014.0750558035714"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7637317424852962" textColor="#000000" visible="true" width="34.029296875" x="25.759317914896712" y="74.85794561476928">found</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7637317424852961" textColor="#000000" visible="true" width="34.029296875" x="25.759317914896712" y="74.85795375279031">found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e5" source="n3" target="n7"> - <data key="d6"> - <y:PolyLineEdge> - <y:Path sx="0.0" sy="36.701171875" tx="17.33398383009643" ty="-25.4443359375"/> - <y:LineStyle color="#000000" type="line" width="1.0"/> - <y:Arrows source="none" target="standard"/> - <y:BendStyle smoothed="false"/> - </y:PolyLineEdge> - </data> - </edge> - <edge id="e6" source="n5" target="n14"> + <edge id="e5" source="n4" target="n13"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="36.701171875" tx="0.0" ty="-36.701171875"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.6666666666666666" textColor="#000000" visible="true" width="53.376953125" x="-55.376966300843264" y="53.29164109002977">end input</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.6666666666666666" textColor="#000000" visible="true" width="53.376953125" x="-55.376966300843264" y="53.291649228050574">end input</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e7" source="n6" target="n4"> + <edge id="e6" source="n5" target="n3"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="36.701171875" tx="29.9287109375" ty="-18.357421875"> - <y:Point x="388.8857142857143" y="1191.178441220238"/> - <y:Point x="439.2265873015873" y="1191.178441220238"/> - <y:Point x="439.2265873015873" y="462.4139229910714"/> - <y:Point x="331.3636315724206" y="462.4139229910714"/> + <y:Point x="388.8857142857143" y="1191.1785714285716"/> + <y:Point x="439.2265873015873" y="1191.1785714285716"/> + <y:Point x="439.2265873015873" y="462.41392299107144"/> + <y:Point x="307.2080760168651" y="462.41392299107144"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e8" source="n4" target="n8"> + <edge id="e7" source="n3" target="n7"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="-29.9287109375" sy="18.357421875" tx="0.0" ty="-36.701171875"> - <y:Point x="271.5062096974206" y="585.8162667410713"/> - <y:Point x="237.51273561507938" y="585.8162667410713"/> - </y:Path> + <y:Path sx="29.928741511945418" sy="18.357421875025466" tx="0.0" ty="-36.701171875"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="54.6953125" x="-90.68880273885367" y="73.21873256138383">not NULL</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="54.6953125" x="-56.69545848145407" y="73.21873256138394">not NULL</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e9" source="n4" target="n9"> + <edge id="e8" source="n3" target="n8"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="29.92870818740124" sy="18.357421875000227" tx="27.341796875" ty="-18.357421875"> - <y:Point x="331.3636532738095" y="705.5691964285713"/> - <y:Point x="292.1961619543651" y="705.5691964285713"/> + <y:Path sx="-29.9287109375" sy="18.357421875" tx="-27.34177001798554" ty="-18.357421875019554"> + <y:Point x="247.3506541418651" y="585.8162667410714"/> + <y:Point x="237.51230158730158" y="585.8162667410714"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.4956707313707325" textColor="#000000" visible="true" width="34.6796875" x="-36.67965699479407" y="124.2410307384672">NULL</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5647066052328362" textColor="#000000" visible="true" width="34.6796875" x="-46.51791994691905" y="120.48240443638394">NULL</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e10" source="n8" target="n9"> + <edge id="e9" source="n7" target="n8"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="36.701171875" tx="-27.34184464530668" ty="-18.357421875062187"/> + <y:Path sx="0.0" sy="36.701171875" tx="27.341796875" ty="-18.357421875"> + <y:Point x="307.2079365079365" y="742.9197823660714"/> + <y:Point x="292.1961619543651" y="742.9197823660714"/> + </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e11" source="n5" target="n12"> + <edge id="e10" source="n4" target="n11"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="-34.901041666666686" sy="12.232421875" tx="23.17431640625" ty="-18.357421875"> - <y:Point x="257.29499007936505" y="1014.074925595238"/> - <y:Point x="223.81888950892858" y="1014.074925595238"/> - <y:Point x="223.81888950892858" y="1067.776097470238"/> - <y:Point x="201.12233227926586" y="1067.776097470238"/> + <y:Point x="257.29499007936505" y="1014.0750558035714"/> + <y:Point x="223.81888950892858" y="1014.0750558035714"/> + <y:Point x="223.81888950892858" y="1067.7762276785716"/> + <y:Point x="201.12233227926586" y="1067.7762276785716"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7276478307488919" textColor="#000000" visible="true" width="54.044921875" x="-89.52101527622767" y="83.42044561476928">not found</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7276478307488922" textColor="#000000" visible="true" width="54.044921875" x="-89.52101527622767" y="83.42045375279031">not found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e12" source="n9" target="n12"> + <edge id="e11" source="n8" target="n11"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="-27.341796875" sy="18.357421875" tx="-23.17432532134086" ty="-18.357421875002046"> - <y:Point x="237.5125682043651" y="866.321995907738"/> - <y:Point x="154.77380952380952" y="866.321995907738"/> + <y:Path sx="-27.341796875" sy="18.357421875" tx="-23.17432532134086" ty="-18.35742187500182"> + <y:Point x="237.5125682043651" y="866.3221261160714"/> + <y:Point x="154.77380952380952" y="866.3221261160714"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5872751774254696" textColor="#000000" visible="true" width="17.34765625" x="-102.0864677677692" y="122.99489629836307">no</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5872751774254694" textColor="#000000" visible="true" width="17.34765625" x="-102.0864677677692" y="122.99490443638399">no</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e13" source="n1" target="n11"> + <edge id="e12" source="n1" target="n10"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="-34.901041666666686" sy="12.232421875" tx="0.0" ty="-44.0517578125"> - <y:Point x="419.3255456349206" y="290.609375"/> - <y:Point x="271.5063151041667" y="290.609375"/> + <y:Point x="472.70252976190477" y="290.609375"/> + <y:Point x="247.3507595486111" y="290.609375"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="34.029296875" x="-183.84849542094543" y="79.29544067382812">found</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="34.029296875" x="-261.3810346190791" y="79.29544067382812">found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e14" source="n11" target="n4"> + <edge id="e13" source="n10" target="n3"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="44.0517578125" tx="-29.92876211998106" ty="-18.35742187507151"/> + <y:Path sx="0.0" sy="44.0517578125" tx="-29.928762119980917" ty="-18.35742187507151"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e15" source="n10" target="n15"> + <edge id="e14" source="n9" target="n14"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="44.0517578125" tx="0.0" ty="-58.7529296875"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e16" source="n9" target="n5"> + <edge id="e15" source="n8" target="n4"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="27.34182899995352" sy="18.357421875028308" tx="0.0" ty="-36.701171875"/> + <y:Path sx="27.34182899995352" sy="18.357421875028194" tx="0.0" ty="-36.701171875"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="22.673828125" x="-24.673976157073014" y="63.86813848586303">yes</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="22.673828125" x="-24.673976157073014" y="63.868146623883945">yes</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e17" source="n12" target="n10"> + <edge id="e16" source="n11" target="n9"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="23.174336131201812" sy="18.357421875010232" tx="-30.001953125" ty="-44.0517578125"> - <y:Point x="201.12223152281746" y="1259.879613095238"/> - <y:Point x="209.01788814484127" y="1259.879613095238"/> + <y:Path sx="23.174339890666516" sy="18.35742187501478" tx="-30.001953125" ty="-44.0517578125"> + <y:Point x="201.12223152281746" y="1244.8797433035716"/> + <y:Point x="209.01788814484127" y="1244.8797433035716"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5204039228973768" textColor="#000000" visible="true" width="22.673828125" x="-24.67391760275683" y="71.05205775669629">yes</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.372675606634203" textColor="#000000" visible="true" width="22.673828125" x="-24.673924265550284" y="52.90623256138406">yes</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e18" source="n12" target="n13"> + <edge id="e17" source="n11" target="n12"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="-23.17431640625" sy="18.357421875" tx="0.0" ty="-58.7529296875"> - <y:Point x="154.77369946676586" y="1191.178441220238"/> - <y:Point x="97.00795510912698" y="1191.178441220238"/> + <y:Point x="154.77369946676586" y="1191.1785714285716"/> + <y:Point x="97.00795510912698" y="1191.1785714285716"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7565598105185114" textColor="#000000" visible="true" width="17.34765625" x="-77.11340846827596" y="68.93063848586303">no</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.9999999999999999" textColor="#000000" visible="true" width="17.34765625" x="-77.1134136987111" y="78.51756068638406">no</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e19" source="n14" target="n16"> + <edge id="e18" source="n13" target="n15"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="23.17431640625" sy="18.357421875" tx="0.0" ty="-36.701171875"> - <y:Point x="315.37034815228174" y="1206.178441220238"/> - <y:Point x="381.8893043154762" y="1206.178441220238"/> + <y:Path sx="23.174337722874213" sy="18.35742187501205" tx="-26.16845703125" ty="-36.701171875"> + <y:Point x="315.37025669642856" y="1244.8797433035716"/> + <y:Point x="455.2664636036706" y="1244.8797433035716"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7058037221240121" textColor="#000000" visible="true" width="17.34765625" x="47.17127842739666" y="78.08558640252977">no</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.14949888358247876" textColor="#000000" visible="true" width="17.34765625" x="-19.34773132167578" y="52.90623256138406">no</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e20" source="n16" target="n7"> + <edge id="e19" source="n15" target="n6"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="36.701171875" tx="-17.333984375" ty="-25.4443359375"> - <y:Point x="381.88928571428573" y="1390.632542782738"/> - <y:Point x="419.5584759424603" y="1390.632542782738"/> - </y:Path> + <y:Path sx="0.0" sy="36.701171875" tx="0.0" ty="-29.3505859375"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e21" source="n14" target="n10"> + <edge id="e20" source="n13" target="n9"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="-23.174328623199813" sy="18.357421875003865" tx="30.001953125" ty="-44.0517578125"/> + <y:Path sx="-23.17433039033739" sy="18.357421875005684" tx="30.001953125" ty="-44.0517578125"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.75" textColor="#000000" visible="true" width="22.673828125" x="-24.67376420484362" y="88.28122442336303">yes</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.6666666666666666" textColor="#000000" visible="true" width="22.673828125" x="-24.673770157148738" y="71.6353992280508">yes</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e22" source="n13" target="n1"> + <edge id="e21" source="n12" target="n1"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="58.7529296875" tx="-39.263671875" ty="-9.169921875"> - <y:Point x="97.0079365079365" y="1412.684300595238"/> - <y:Point x="15.0" y="1412.684300595238"/> + <y:Point x="97.0079365079365" y="1397.6844308035716"/> + <y:Point x="15.0" y="1397.6844308035716"/> <y:Point x="15.0" y="167.20703125"/> - <y:Point x="414.9629154265873" y="167.20703125"/> + <y:Point x="468.33989955357146" y="167.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e23" source="n15" target="n1"> + <edge id="e22" source="n14" target="n1"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="58.7529296875" tx="-13.087890625" ty="-27.544921875"> - <y:Point x="239.01984126984127" y="1565.488988095238"/> - <y:Point x="0.0" y="1565.488988095238"/> + <y:Point x="239.01984126984127" y="1550.4891183035716"/> + <y:Point x="0.0" y="1550.4891183035716"/> <y:Point x="0.0" y="152.20703125"/> - <y:Point x="441.1386966765873" y="152.20703125"/> + <y:Point x="494.51568080357146" y="152.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> </graph> <data key="d0"> <y:Resources/> </data> </graphml>
nlehuen/pytst
f876f38544f3c326f8fd26a7fbf6b1337c4d48ff
Fix a small glitch in the algorithm graph.
diff --git a/scan algorithm.graphml b/scan algorithm.graphml index a03fad3..c37ed3d 100644 --- a/scan algorithm.graphml +++ b/scan algorithm.graphml @@ -1,553 +1,540 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd"> <!--Created by yFiles for Java 2.7--> <key for="graphml" id="d0" yfiles.type="resources"/> <key attr.name="url" attr.type="string" for="node" id="d1"/> <key attr.name="description" attr.type="string" for="node" id="d2"/> <key for="node" id="d3" yfiles.type="nodegraphics"/> <key attr.name="url" attr.type="string" for="edge" id="d4"/> <key attr.name="description" attr.type="string" for="edge" id="d5"/> <key for="edge" id="d6" yfiles.type="edgegraphics"/> <graph edgedefault="directed" id="G"> <node id="n0"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="132.20703125" width="90.001953125" x="381.1379123263889" y="0.0"/> + <y:Geometry height="132.20703125" width="90.001953125" x="422.3133091517857" y="0.0"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="92.20703125" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="50.001953125" x="20.0" y="20.0">START : NM = 0 MS = -1 BM = -1 n = root i = 0</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n1"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="104.703125" x="386.8750248015873" y="192.20703125"/> + <y:Geometry height="73.40234375" width="104.703125" x="401.8750248015873" y="192.20703125"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.703125" x="20.0" y="20.0">(A) check input</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n2"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="60.681640625" x="511.5635447668651" y="356.6611328125"/> + <y:Geometry height="73.40234375" width="60.681640625" x="526.5635447668651" y="356.6611328125"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="20.681640625" x="20.0" y="20.0">(C) i++</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n3"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="104.673828125" x="386.8896732390873" y="356.6611328125"/> + <y:Geometry height="73.40234375" width="104.673828125" x="401.8896732390873" y="356.6611328125"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.673828125" x="20.0" y="20.0">(D) emit 0,NM,i</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n4"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="119.71484375" x="226.57749875992062" y="487.41392299107133"/> + <y:Geometry height="73.40234375" width="119.71484375" x="241.57749875992062" y="487.41392299107133"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="79.71484375" x="20.0" y="20.0">(E) check n-&gt;data</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n5"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="104.703125" x="224.84446924603174" y="915.672581845238"/> + <y:Geometry height="73.40234375" width="104.703125" x="239.84446924603174" y="915.672581845238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.703125" x="20.0" y="20.0">(H) check input</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n6"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="60.681640625" x="343.5448939732143" y="1092.776097470238"/> + <y:Geometry height="73.40234375" width="60.681640625" x="358.5448939732143" y="1092.776097470238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="20.681640625" x="20.0" y="20.0">(L) i++</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n7"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="58.701171875" width="69.3359375" x="387.2244915674603" y="1452.385472470238"/> + <y:Geometry height="58.701171875" width="69.3359375" x="402.2244915674603" y="1452.385472470238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="29.3359375" x="20.0" y="20.0">END</y:NodeLabel> <y:Shape type="ellipse"/> </y:ShapeNode> </data> </node> <node id="n8"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="102.8046875" width="120.0078125" x="491.14014136904757" y="14.701171875"/> - <y:Fill color="#FFCC00" transparent="false"/> - <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="48.103515625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="80.0078125" x="20.0" y="27.3505859375">(O) -emit 0,NM,MS -emit 1,MS,BM</y:NodeLabel> - <y:Shape type="parallelogram"/> - </y:ShapeNode> - </data> - </node> - <node id="n9"> - <data key="d3"> - <y:ShapeNode> - <y:Geometry height="73.40234375" width="78.341796875" x="183.3417999751984" y="644.5174386160713"/> + <y:Geometry height="73.40234375" width="78.341796875" x="198.3417999751984" y="644.5174386160713"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="38.341796875" x="20.0" y="20.0">(F) BM = i</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> - <node id="n10"> + <node id="n9"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="109.3671875" x="195.17077132936507" y="767.919652157738"/> + <y:Geometry height="73.40234375" width="109.3671875" x="210.1707713293651" y="767.919652157738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="69.3671875" x="20.0" y="20.0">(G) move next ?</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> - <node id="n11"> + <node id="n10"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="88.103515625" width="120.0078125" x="164.01593501984127" y="1284.879613095238"/> + <y:Geometry height="88.103515625" width="120.0078125" x="179.01593501984127" y="1284.879613095238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="48.103515625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="80.0078125" x="20.0" y="20.0">(J) emit 0,NM,MS emit 1,MS,BM</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> - <node id="n12"> + <node id="n11"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="88.103515625" width="78.341796875" x="217.33545076884923" y="349.310546875"/> + <y:Geometry height="88.103515625" width="78.341796875" x="232.33545076884923" y="349.310546875"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="48.103515625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="38.341796875" x="20.0" y="20.0">(B) MS = i i++</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> - <node id="n13"> + <node id="n12"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="92.697265625" x="116.59938306051586" y="1092.776097470238"/> + <y:Geometry height="73.40234375" width="92.697265625" x="131.59938306051586" y="1092.776097470238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="52.697265625" x="20.0" y="20.0">(I) BM&gt;=0 ?</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> - <node id="n14"> + <node id="n13"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="117.505859375" width="124.015625" x="20.000124007936506" y="1270.178441220238"/> + <y:Geometry height="117.505859375" width="124.015625" x="35.000124007936506" y="1270.178441220238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="77.505859375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="84.015625" x="20.0" y="20.0">(K) BACKTRACK : i=MS+1 MS = -1 n = root</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> - <node id="n15"> + <node id="n14"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="92.697265625" x="230.84739893353174" y="1092.776097470238"/> + <y:Geometry height="73.40234375" width="92.697265625" x="245.84739893353174" y="1092.776097470238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="52.697265625" x="20.0" y="20.0">(M) BM&gt;=0 ?</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> - <node id="n16"> + <node id="n15"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="117.505859375" width="87.669921875" x="180.18488033234127" y="1422.983128720238"/> + <y:Geometry height="117.505859375" width="87.669921875" x="195.18488033234127" y="1422.983128720238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="77.505859375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="47.669921875" x="20.0" y="20.0">(J) i=BM NM=BM MS=-1 n=root</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> - <node id="n17"> + <node id="n16"> <data key="d3"> <y:ShapeNode> - <y:Geometry height="73.40234375" width="104.673828125" x="314.55237165178573" y="1292.230199032738"/> + <y:Geometry height="73.40234375" width="104.673828125" x="329.55237165178573" y="1292.230199032738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.673828125" x="20.0" y="20.0">(N) emit 0,NM,i</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <edge id="e0" source="n1" target="n2"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="34.90104166666674" sy="12.232421875" tx="0.0" ty="-36.701171875"> - <y:Point x="474.127628968254" y="290.609375"/> - <y:Point x="541.904206969246" y="290.609375"/> + <y:Path sx="34.901041666666686" sy="12.232421875" tx="0.0" ty="-36.701171875"> + <y:Point x="489.127628968254" y="290.609375"/> + <y:Point x="556.904206969246" y="290.609375"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7975265623853919" textColor="#000000" visible="true" width="54.044921875" x="11.73170633340618" y="68.53323364257812">not found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e1" source="n2" target="n1"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="36.701171875" tx="39.263671875" ty="-9.169921875"> - <y:Point x="541.9043650793651" y="455.0634765625"/> - <y:Point x="592.245238095238" y="455.0634765625"/> - <y:Point x="592.245238095238" y="167.20703125"/> - <y:Point x="478.4902591765873" y="167.20703125"/> + <y:Point x="556.9043650793651" y="455.0634765625"/> + <y:Point x="607.245238095238" y="455.0634765625"/> + <y:Point x="607.245238095238" y="167.20703125"/> + <y:Point x="493.4902591765873" y="167.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e2" source="n1" target="n3"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="36.701171875" tx="0.0" ty="-36.701171875"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5" textColor="#000000" visible="true" width="53.376953125" x="-55.376958840990824" y="36.17529296875">end input</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e3" source="n0" target="n1"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="66.103515625" tx="-13.087919957398071" ty="-27.544921875046924"/> + <y:Path sx="0.0" sy="66.103515625" tx="13.087919957398071" ty="-27.544921875046924"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e4" source="n5" target="n6"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="34.901041666666686" sy="12.232421875" tx="0.0" ty="-36.701171875"> - <y:Point x="312.0970734126984" y="1014.074925595238"/> - <y:Point x="373.88568018353175" y="1014.074925595238"/> + <y:Point x="327.0970734126984" y="1014.074925595238"/> + <y:Point x="388.88568018353175" y="1014.074925595238"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7637317424852962" textColor="#000000" visible="true" width="34.029296875" x="25.759317914896712" y="74.85794561476928">found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e5" source="n3" target="n7"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="36.701171875" tx="17.333983830096372" ty="-25.4443359375"/> + <y:Path sx="0.0" sy="36.701171875" tx="17.33398383009643" ty="-25.4443359375"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e6" source="n5" target="n15"> + <edge id="e6" source="n5" target="n14"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="36.701171875" tx="0.0" ty="-36.701171875"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.6666666666666666" textColor="#000000" visible="true" width="53.376953125" x="-55.376966300843264" y="53.29164109002977">end input</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e7" source="n6" target="n4"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="36.701171875" tx="29.9287109375" ty="-18.357421875"> - <y:Point x="373.8857142857143" y="1191.178441220238"/> - <y:Point x="424.2265873015873" y="1191.178441220238"/> - <y:Point x="424.2265873015873" y="462.4139229910714"/> - <y:Point x="316.3636315724206" y="462.4139229910714"/> + <y:Point x="388.8857142857143" y="1191.178441220238"/> + <y:Point x="439.2265873015873" y="1191.178441220238"/> + <y:Point x="439.2265873015873" y="462.4139229910714"/> + <y:Point x="331.3636315724206" y="462.4139229910714"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e8" source="n4" target="n9"> + <edge id="e8" source="n4" target="n8"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="-29.9287109375" sy="18.357421875" tx="0.0" ty="-36.701171875"> - <y:Point x="256.5062096974206" y="585.8162667410713"/> - <y:Point x="222.51273561507938" y="585.8162667410713"/> + <y:Point x="271.5062096974206" y="585.8162667410713"/> + <y:Point x="237.51273561507938" y="585.8162667410713"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="54.6953125" x="-90.68880273885367" y="73.21873256138383">not NULL</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e9" source="n4" target="n10"> + <edge id="e9" source="n4" target="n9"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="29.9287081874013" sy="18.357421875000227" tx="27.341796874999943" ty="-18.357421875"> - <y:Point x="316.3636532738095" y="705.5691964285713"/> - <y:Point x="277.19616195436504" y="705.5691964285713"/> + <y:Path sx="29.92870818740124" sy="18.357421875000227" tx="27.341796875" ty="-18.357421875"> + <y:Point x="331.3636532738095" y="705.5691964285713"/> + <y:Point x="292.1961619543651" y="705.5691964285713"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.49567073137073236" textColor="#000000" visible="true" width="34.6796875" x="-36.67965699479407" y="124.2410307384672">NULL</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.4956707313707325" textColor="#000000" visible="true" width="34.6796875" x="-36.67965699479407" y="124.2410307384672">NULL</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e10" source="n9" target="n10"> + <edge id="e10" source="n8" target="n9"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="36.701171875" tx="-27.341844645306708" ty="-18.357421875062187"/> + <y:Path sx="0.0" sy="36.701171875" tx="-27.34184464530668" ty="-18.357421875062187"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e11" source="n5" target="n13"> + <edge id="e11" source="n5" target="n12"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="-34.901041666666686" sy="12.232421875" tx="23.17431640625" ty="-18.357421875"> - <y:Point x="242.29499007936505" y="1014.074925595238"/> - <y:Point x="208.81888950892858" y="1014.074925595238"/> - <y:Point x="208.81888950892858" y="1067.776097470238"/> - <y:Point x="186.12233227926586" y="1067.776097470238"/> + <y:Point x="257.29499007936505" y="1014.074925595238"/> + <y:Point x="223.81888950892858" y="1014.074925595238"/> + <y:Point x="223.81888950892858" y="1067.776097470238"/> + <y:Point x="201.12233227926586" y="1067.776097470238"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7276478307488919" textColor="#000000" visible="true" width="54.044921875" x="-89.52101527622767" y="83.42044561476928">not found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e12" source="n10" target="n13"> + <edge id="e12" source="n9" target="n12"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="-27.341796875" sy="18.357421875" tx="-23.17432532134086" ty="-18.357421875002046"> - <y:Point x="222.51256820436507" y="866.321995907738"/> - <y:Point x="139.77380952380952" y="866.321995907738"/> + <y:Point x="237.5125682043651" y="866.321995907738"/> + <y:Point x="154.77380952380952" y="866.321995907738"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5872751774254694" textColor="#000000" visible="true" width="17.34765625" x="-102.08646776776918" y="122.99489629836307">no</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5872751774254696" textColor="#000000" visible="true" width="17.34765625" x="-102.0864677677692" y="122.99489629836307">no</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e13" source="n1" target="n12"> + <edge id="e13" source="n1" target="n11"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="-34.90104166666674" sy="12.232421875" tx="0.0" ty="-44.0517578125"> - <y:Point x="404.3255456349206" y="290.609375"/> - <y:Point x="256.5063151041667" y="290.609375"/> + <y:Path sx="-34.901041666666686" sy="12.232421875" tx="0.0" ty="-44.0517578125"> + <y:Point x="419.3255456349206" y="290.609375"/> + <y:Point x="271.5063151041667" y="290.609375"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="34.029296875" x="-183.84849542094543" y="79.29544067382812">found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e14" source="n12" target="n4"> + <edge id="e14" source="n11" target="n4"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="44.0517578125" tx="-29.928762119981116" ty="-18.35742187507151"/> + <y:Path sx="0.0" sy="44.0517578125" tx="-29.92876211998106" ty="-18.35742187507151"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e15" source="n11" target="n16"> + <edge id="e15" source="n10" target="n15"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="44.0517578125" tx="0.0" ty="-58.7529296875"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e16" source="n10" target="n5"> + <edge id="e16" source="n9" target="n5"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="27.34182899995352" sy="18.357421875028308" tx="0.0" ty="-36.701171875"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="22.673828125" x="-24.673976157073014" y="63.86813848586303">yes</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e17" source="n13" target="n11"> + <edge id="e17" source="n12" target="n10"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="23.174336131201812" sy="18.357421875010232" tx="-30.001953125" ty="-44.0517578125"> - <y:Point x="186.12223152281746" y="1259.879613095238"/> - <y:Point x="194.01788814484127" y="1259.879613095238"/> + <y:Point x="201.12223152281746" y="1259.879613095238"/> + <y:Point x="209.01788814484127" y="1259.879613095238"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5204039228973768" textColor="#000000" visible="true" width="22.673828125" x="-24.67391760275683" y="71.05205775669629">yes</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e18" source="n13" target="n14"> + <edge id="e18" source="n12" target="n13"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="-23.17431640625" sy="18.357421875" tx="0.0" ty="-58.7529296875"> - <y:Point x="139.77369946676586" y="1191.178441220238"/> - <y:Point x="82.00795510912698" y="1191.178441220238"/> + <y:Point x="154.77369946676586" y="1191.178441220238"/> + <y:Point x="97.00795510912698" y="1191.178441220238"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7565598105185114" textColor="#000000" visible="true" width="17.34765625" x="-77.11340846827596" y="68.93063848586303">no</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e19" source="n15" target="n17"> + <edge id="e19" source="n14" target="n16"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="23.17431640625" sy="18.357421875" tx="0.0" ty="-36.701171875"> - <y:Point x="300.37034815228174" y="1206.178441220238"/> - <y:Point x="366.8893043154762" y="1206.178441220238"/> + <y:Point x="315.37034815228174" y="1206.178441220238"/> + <y:Point x="381.8893043154762" y="1206.178441220238"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7058037221240121" textColor="#000000" visible="true" width="17.34765625" x="47.17127842739666" y="78.08558640252977">no</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e20" source="n17" target="n7"> + <edge id="e20" source="n16" target="n7"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="36.701171875" tx="-17.333984375" ty="-25.4443359375"> - <y:Point x="366.88928571428573" y="1390.632542782738"/> - <y:Point x="404.5584759424603" y="1390.632542782738"/> + <y:Point x="381.88928571428573" y="1390.632542782738"/> + <y:Point x="419.5584759424603" y="1390.632542782738"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e21" source="n15" target="n11"> + <edge id="e21" source="n14" target="n10"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="-23.174328623199756" sy="18.357421875003865" tx="30.001953125" ty="-44.0517578125"/> + <y:Path sx="-23.174328623199813" sy="18.357421875003865" tx="30.001953125" ty="-44.0517578125"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.75" textColor="#000000" visible="true" width="22.673828125" x="-24.673764204843565" y="88.28122442336303">yes</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.75" textColor="#000000" visible="true" width="22.673828125" x="-24.67376420484362" y="88.28122442336303">yes</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e22" source="n14" target="n1"> + <edge id="e22" source="n13" target="n1"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="58.7529296875" tx="-39.263671875" ty="-9.169921875"> - <y:Point x="82.0079365079365" y="1412.684300595238"/> - <y:Point x="0.0" y="1412.684300595238"/> - <y:Point x="0.0" y="167.20703125"/> - <y:Point x="399.9629154265873" y="167.20703125"/> + <y:Point x="97.0079365079365" y="1412.684300595238"/> + <y:Point x="15.0" y="1412.684300595238"/> + <y:Point x="15.0" y="167.20703125"/> + <y:Point x="414.9629154265873" y="167.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e23" source="n16" target="n1"> + <edge id="e23" source="n15" target="n1"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="58.7529296875" tx="13.087890625" ty="-27.544921875"> - <y:Point x="224.01984126984127" y="1565.488988095238"/> - <y:Point x="607.245238095238" y="1565.488988095238"/> - <y:Point x="607.245238095238" y="152.20703125"/> - <y:Point x="452.3144779265873" y="152.20703125"/> + <y:Path sx="0.0" sy="58.7529296875" tx="-13.087890625" ty="-27.544921875"> + <y:Point x="239.01984126984127" y="1565.488988095238"/> + <y:Point x="0.0" y="1565.488988095238"/> + <y:Point x="0.0" y="152.20703125"/> + <y:Point x="441.1386966765873" y="152.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> </graph> <data key="d0"> <y:Resources/> </data> </graphml>
nlehuen/pytst
7ffe4bcea820124f77a3bb519d2c418ea15bc727
Increased version number to 1.18.
diff --git a/include/tst.h b/include/tst.h index c717785..2b92538 100644 --- a/include/tst.h +++ b/include/tst.h @@ -1,534 +1,534 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __TST__H_INCLUDED__ #define __TST__H_INCLUDED__ -const char* const TST_VERSION = "1.18RC"; +const char* const TST_VERSION = "1.18"; #include "debug.h" #include <iostream> #ifdef __PYTHON__BUILD__ #include "Python.h" #define tst_malloc PyMem_Malloc #define tst_realloc PyMem_Realloc #define tst_free PyMem_Free // Add / remove SCANNER functions // #define SCANNER #else #include "stdlib.h" #define tst_malloc malloc #define tst_realloc realloc #define tst_free free // Pour ajouter/supprimer les fonctions de scanning. // #define SCANNER #endif template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst; #include "fundamentals.h" #include "memory_storage.h" #include "iterators.h" template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst { public: friend class lexical_iterator<charT,valueT,storageT,serializerT,stringT>; friend class match_iterator<charT,valueT,storageT,serializerT,stringT>; typedef charT character_type; typedef valueT value_type; typedef storageT storage_type; typedef serializerT serializer_type; tst(); virtual ~tst() { delete storage; } void pack() { storage->pack(root); } valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,const stringT & string) const; valueT close_match(const stringT & string,int maximum_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT prefix_match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT get(const stringT & string) const; valueT get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory); valueT put(const stringT & string,valueT data); void remove(const stringT & string); bool contains(const stringT & string) const; void write(std::ostream &file) const; void read(std::istream &file); lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator() const { stringT key; return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,key,root); } lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; find_node(&current_index,&best_node,string); return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,string.substr(0,string.size()-1),current_index); } match_iterator<charT,valueT,storageT,serializerT,stringT> close_match_iterator(const stringT & string,int distance) const { return match_iterator<charT,valueT,storageT,serializerT,stringT>(this,string,distance,root); } int get_number_of_nodes() const { return storage->size(); } valueT get_default_value() const { return default_value; } #ifdef SCANNER valueT scan(const stringT & string,tst_action<charT,valueT,stringT>* to_perform); valueT scan_with_stop_chars(const stringT & string,const stringT& stop_chars,tst_action<charT,valueT,stringT>* to_perform) const; #endif protected: void set_storage(storageT* new_storage) { delete storage; storage = new_storage; } private: storageT* storage; valueT default_value; int root; void walk_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void close_match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,const size_t position, const int distance, const int remaining_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_joker_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_star_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; int build_node(node_info<charT,valueT>* current_node,const stringT & string,size_t current_position); void remove_node(int* current_index,const stringT & string,const size_t position); int find_char(tst_node<charT,valueT>** current_node, charT c) const; tst_node<charT,valueT>* find_node(int* current_index,int* best_node, const stringT & string) const; void balance_node(node_info<charT,valueT>* bal); void ll(node_info<charT,valueT>* bal); void rr(node_info<charT,valueT>* bal); void lr(node_info<charT,valueT>* bal); void rl(node_info<charT,valueT>* bal); void compute_height_and_balance(node_info<charT,valueT>* current_node_info) const; void write_node(std::ostream& file,serializerT* writer,int index) const; int read_node(std::istream& file,serializerT* reader,int depth); #ifdef SCANNER void compute_backtrack(tst_node<charT,valueT> *current_node,const stringT & string,int si_match_start,int si_match_end); #endif }; template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst<charT,valueT,storageT,serializerT,stringT>::tst() : storage(new storage_type(16)), default_value() { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } /*************************** high-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return current_node->data; } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> bool tst<charT,valueT,storageT,serializerT,stringT>::contains(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return true; } else { return false; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::put(const stringT & string,valueT data) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; return storage->get(node_index)->store(data); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; tst_node<charT,valueT>* current_node=storage->get(node_index); valueT data = current_node->data; if(data==default_value) { data=factory->perform(string,0,current_node->data); current_node->store(data); return data; } else { return data; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove(const stringT & string) { remove_node(&root,string,0); if(root==UNDEFINED_INDEX) { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } } /**************************** low-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst_node<charT,valueT>* tst<charT,valueT,storageT,serializerT,stringT>::find_node(int* current_index,int* best_node,const stringT & string) const { tst_node<charT,valueT>* current_node; int diff; size_t pos=0; while(*current_index!=UNDEFINED_INDEX) { current_node=storage->get(*current_index); if(current_node->c==0) { *current_index=UNDEFINED_INDEX; return 0; } else { diff=string[pos]-(current_node->c); } if(diff==0) { if(current_node->data!=default_value) { *best_node=*current_index; } ++pos; if(pos<string.size()) { *current_index = current_node->next; } else { return current_node; } } else if(diff>0) { *current_index=current_node->right; } else { *current_index=current_node->left; } } return 0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> int tst<charT,valueT,storageT,serializerT,stringT>::build_node(node_info<charT,valueT>* current_node_info,const stringT & string,size_t current_position) { int diff,result; if(current_node_info->node->c==0) { current_node_info->node->c=string[current_position]; #ifdef SCANNER current_node_info->node->position=current_position; #endif diff=0; } else { diff=string[current_position]-(current_node_info->node->c); } current_node_info->height=-1; current_node_info->balance_performed=0; if(diff==0) { ++current_position; compute_height_and_balance(current_node_info); // TODO : est-ce bien necessaire ? if(current_position<string.size()) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->next; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->next = next_node_info.index; return result; } else { return current_node_info->index; } } else if(diff>0) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->right; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->right = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->left==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = next_node_info.height; current_node_info->left_balance = 0; current_node_info->right_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->left; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = next_node_info.height-other_node_info.height; current_node_info->left_balance = other_node_info.balance; current_node_info->right_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } else { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->left; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->left = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->right==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = -next_node_info.height; current_node_info->right_balance = 0; current_node_info->left_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->right; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = other_node_info.height-next_node_info.height; current_node_info->right_balance = other_node_info.balance; current_node_info->left_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove_node(int* current_index,const stringT & string,const size_t current_position) { tst_node<charT,valueT>* current_node = storage->get(*current_index); int diff,*next_index; if(current_node->c==0) { return; } else { diff=string[current_position]-(current_node->c); } if(diff==0) { if(current_position+1<string.size()) { next_index = &(current_node->next); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position+1); } } else { current_node->store(default_value); } } else if(diff>0) { next_index = &(current_node->right); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } else { next_index = &(current_node->left); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } current_node=storage->get(*current_index); if( current_node->data==default_value && current_node->next==UNDEFINED_INDEX && current_node->right==UNDEFINED_INDEX && current_node->left==UNDEFINED_INDEX) { storage->delete_node(*current_index); *current_index=UNDEFINED_INDEX; } else { node_info<charT,valueT> current_node_info; current_node_info.index=*current_index; current_node_info.node=current_node; current_node_info.height=-1; balance_node(&current_node_info); *current_index = current_node_info.index; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::balance_node(node_info<charT,valueT>* bal) { if(bal->height==-1) { compute_height_and_balance(bal); } bal->balance_performed=0; if(bal->balance>1) { if(bal->right_balance>0) { rr(bal); } else { rl(bal); } bal->balance_performed=1; } else if(bal->balance<-1) { if(bal->left_balance<0) { ll(bal); } else { lr(bal); } bal->balance_performed=1; } assert(abs(bal->balance)<2); assert(abs(bal->right_balance)<2); assert(abs(bal->left_balance)<2); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::ll(node_info<charT,valueT>* bal) { int left_index=bal->node->left; tst_node<charT,valueT>* left_node=storage->get(left_index); int left_right_index=left_node->right; bal->node->left=left_right_index; left_node->right=bal->index; bal->index=left_index; bal->node=storage->get(left_index); bal->height=bal->height-1; bal->balance=0; bal->right_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rr(node_info<charT,valueT>* bal) { int right_index=bal->node->right; tst_node<charT,valueT>* right_node=storage->get(right_index); int right_left_index=right_node->left; bal->node->right=right_left_index; right_node->left=bal->index; bal->index=right_index; bal->node=storage->get(right_index); bal->height=bal->height-1; bal->balance=0; bal->left_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::lr(node_info<charT,valueT>* bal) { node_info<charT,valueT> left; left.index = bal->node->left; left.node = storage->get(left.index); rr(&left); bal->node->left=left.index; ll(bal); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rl(node_info<charT,valueT>* bal) { node_info<charT,valueT> right; right.index = bal->node->right; right.node = storage->get(right.index); ll(&right); bal->node->right=right.index; rr(bal); } diff --git a/python/setup.py b/python/setup.py index da4bf76..c77ea22 100644 --- a/python/setup.py +++ b/python/setup.py @@ -1,49 +1,49 @@ # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from distutils.core import setup, Extension import sys extra_compile_args = [] setup( name = "pytst", - version = "1.18RC", + version = "1.18", author = "Nicolas Lehuen", author_email = "nicolas@lehuen.com", url = "http://github.com/nlehuen/pytst", description = "An implementation of a Ternary Search Tree (TST) in C++ with Python bindings", py_modules = ["tst"], ext_modules = [ Extension( "_tst", ["tst_wrap.cxx"], include_dirs=['../include'], extra_compile_args = extra_compile_args, define_macros=[('SCANNER', None),], ) ], download_url = "http://github.com/nlehuen/pytst/downloads", classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: C++', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Scientific/Engineering :: Information Analysis', ] )
nlehuen/pytst
931341eb5efbad0f463f2d0dbde2453b7b4fc1a2
No more need for backtracking information, this saves memory.
diff --git a/include/fundamentals.h b/include/fundamentals.h index 4f4bddc..a4f6a8e 100644 --- a/include/fundamentals.h +++ b/include/fundamentals.h @@ -1,139 +1,133 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __FUNDAMENTALS__H_INCLUDED__ #define __FUNDAMENTALS__H_INCLUDED__ #include <exception> const int UNDEFINED_INDEX=-1; class TSTException : public std::exception { public: TSTException(const char* _message) : message(_message) { } const char* what() { return message; } private: const char* message; }; template <typename charT,typename valueT> class tst_node { public: tst_node() : c(0) ,data() ,next(UNDEFINED_INDEX) ,right(UNDEFINED_INDEX) ,left(UNDEFINED_INDEX) #ifdef SCANNER ,position(UNDEFINED_INDEX) - ,backtrack(UNDEFINED_INDEX) - ,backtrack_match_index(UNDEFINED_INDEX) #endif { } charT c; valueT data; int next; int right; int left; #ifdef SCANNER int position; - int backtrack; - int backtrack_match_index; #endif valueT store(valueT value) { valueT old = data; data = value; return old; } void reset() { c = 0; data = valueT(); next = UNDEFINED_INDEX; right = UNDEFINED_INDEX; left = UNDEFINED_INDEX; #ifdef SCANNER position = UNDEFINED_INDEX; - backtrack = UNDEFINED_INDEX; - backtrack_match_index = UNDEFINED_INDEX; #endif } }; template <typename charT,typename valueT> class node_info { public: int index; tst_node<charT,valueT>* node; int height; int balance; int right_balance; int left_balance; int balance_performed; node_info() : index(UNDEFINED_INDEX) ,node(0) ,height(0) ,balance(0) ,right_balance(0) ,left_balance(0) ,balance_performed(0) { } }; template <typename charT,typename valueT,typename stringT> class tst_action { public: tst_action() {} virtual ~tst_action() {} virtual void perform(const stringT & string,int remaining_distance,valueT data)=0; virtual valueT result()=0; }; template <typename charT,typename valueT,typename stringT> class tst_filter { public: tst_filter() {} virtual ~tst_filter() {} virtual valueT perform(const stringT & string,int remaining_distance,valueT data)=0; }; template <typename valueT> class null_reader_writer { public: void write(FILE* file, valueT value) { } valueT read(FILE* file) { return valueT(); } }; #endif diff --git a/include/tst.h b/include/tst.h index f58b323..cb98e61 100644 --- a/include/tst.h +++ b/include/tst.h @@ -883,595 +883,591 @@ template<typename charT,typename valueT,typename storageT,typename serializerT, return to_perform->result(); } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,const stringT & string) const { int index = root; int best_node = UNDEFINED_INDEX; tst_node<charT,valueT>* start = find_node(&index,&best_node,string); if(start) { valueT data = start->data; if(data!=default_value) { if(filter) { data = filter->perform(string,0,data); } if(to_perform) { to_perform->perform(string,0,data); } } index = start->next; if(index!=UNDEFINED_INDEX) { stringT key(string); walk_recurse(storage->get(index),key,filter,to_perform); } } if(to_perform) { return to_perform->result(); } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::walk_recurse(tst_node<charT,valueT>* current_node,stringT& current_key,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const { int other_index; other_index=current_node->left; if(other_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(other_index),current_key,filter,to_perform); } // ++KEY current_key.push_back(current_node->c); valueT data = current_node->data; if(data!=default_value) { if(filter) { data = filter->perform(current_key,0,data); } if(to_perform) { to_perform->perform(current_key,0,data); } } other_index=current_node->next; if(other_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(other_index),current_key,filter,to_perform); } // --KEY current_key.resize(current_key.size()-1); other_index=current_node->right; if(other_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(other_index),current_key,filter,to_perform); } } /**************************** prefix_match *************************************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::prefix_match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const { stringT current_key; size_t position=0; valueT biggest=default_value; int biggest_length=0; int current_index=root; tst_node<charT,valueT>* current_node; int diff; charT c; while(position<string.size()) { c = string[position]; ++position; current_key.push_back(c); while(current_index!=UNDEFINED_INDEX) { current_node=storage->get(current_index); diff=c-current_node->c; if(diff==0) { if(current_node->data!=default_value) { biggest=current_node->data; biggest_length=current_key.size(); if(filter) { biggest=filter->perform(current_key.substr(0,biggest_length),0,biggest); } } if(position<string.size()) { current_index=current_node->next; break; } else { if(biggest!=default_value && to_perform) { to_perform->perform(current_key.substr(0,biggest_length),0,biggest); } current_index=current_node->next; if(current_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(current_index),current_key,filter,to_perform); } return to_perform->result(); } } else if(diff>0) { current_index=current_node->right; } else { current_index=current_node->left; } } if(current_index==UNDEFINED_INDEX) { break; } } if(biggest!=default_value && to_perform) { to_perform->perform(current_key.substr(0,biggest_length),0,biggest); } return to_perform->result(); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> inline int tst<charT,valueT,storageT,serializerT,stringT>::find_char(tst_node<charT,valueT> **n_current, charT c) const { while(1) { int diff = c - (*n_current)->c; if(diff == 0) { return 1; } else { int ni_next; if(diff>0) { ni_next = (*n_current)->right; } else { ni_next = (*n_current)->left; } if(ni_next==UNDEFINED_INDEX) { *n_current = storage->get(root); return 0; } else { *n_current = storage->get(ni_next); } } } } /**************************** scan *************************************/ #ifdef SCANNER template<typename charT,typename valueT,typename stringT> inline void emit(int match,const stringT & string,size_t start, size_t stop,valueT value,tst_action<charT,valueT,stringT>* to_perform) { size_t length = stop-start; if(length>0) { to_perform->perform(string.substr(start,length), match * length, value); } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::scan(const stringT & string,tst_action<charT,valueT,stringT>* to_perform) { // NOTE : yes, this code uses goto. // It's actually FTW because it simplifies the code instead of // forcing the abusive use of break, continue, all the more // that C++ doesn't support labeled continue. // To make sense of it all, you can have a look at // the file scan algorithm.graphml // with yED : http://www.yworks.com/en/products_yed_about.html // This way you can match nodes from the graph with the code below using the // labels (A), (B), etc. // Current position in the input string size_t si=0; // First string index for a non match size_t si_nm=0; // First string index for a match int si_ms=UNDEFINED_INDEX; // Best match int si_bme=UNDEFINED_INDEX; tst_node<charT,valueT> *n_best_match = NULL; // Current node tst_node<charT,valueT> *n_current = storage->get(root); // Main loop MAIN: { // // NON-MATCH state // assert(si_ms == UNDEFINED_INDEX); // (A) check input if(si < string.size()) { if(find_char(&n_current,string[si])) { // (B) found si_ms = si; ++si; // this goto is implicit // goto POTENTIAL_MATCH; } else { // (C) not found ++si; goto MAIN; } } else { // (D) end input emit(-1,string,si_nm,si,default_value,to_perform); return to_perform->result(); } POTENTIAL_MATCH: { // // POTENTIAL_MATCH state // assert(si_ms != UNDEFINED_INDEX); // (E) check data if(n_current->data != default_value) { // (F) store best match si_bme = si; n_best_match = n_current; } // (G) move next ? n_current = storage->get(n_current->next); if(n_current != NULL) { // (H) check input if(si < string.size()) { if(find_char(&n_current, string[si])) { // (L) ++si; goto POTENTIAL_MATCH; } else { goto END_MATCH; } } else { // (M) end match if(si_bme!=UNDEFINED_INDEX) { goto EMIT_AND_LOOP; } else { // (N) emit(-1,string,si_nm,si,default_value,to_perform); } return to_perform->result(); } } else END_MATCH: { // (I) end match if(si_bme!=UNDEFINED_INDEX) EMIT_AND_LOOP: { // (J) emit and loop emit(-1,string,si_nm,si_ms,default_value,to_perform); emit(1,string,si_ms,si_bme,n_best_match->data,to_perform); si = si_bme; si_nm = si; si_ms = UNDEFINED_INDEX; si_bme = UNDEFINED_INDEX; n_current = storage->get(root); goto MAIN; } else { // (K) backtrack // TODO : prevent backtrack using tree analysis si = si_ms + 1; si_ms = UNDEFINED_INDEX; si_bme = UNDEFINED_INDEX; n_current = storage->get(root); goto MAIN; } } // (I) } // (E) } // MAIN } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::scan_with_stop_chars(const stringT & string,const stringT& stop_chars,tst_action<charT,valueT,stringT>* to_perform) const { // Le premier caractère de la chaine ne correspondant pas à un match size_t si_non_match_start=0; // Le noeud pour lequel on a enregistré un match (noeud avec un objet associé) int ni_best_match=UNDEFINED_INDEX; // Le premier caractère de la chaine correspondant à un match int si_match_start=UNDEFINED_INDEX; // La position actuelle dans la chaîne (index) size_t si_current=0; // Le numéro du noeud actuel de l'arbre int ni_current=root; // Le noeud actuel de l'arbre tst_node<charT,valueT> *n_current; // Boucle principale while(1) { n_current=storage->get(ni_current); // On avance dans l'arbre d'un cran if(si_current<string.size()) { int diff = string[si_current]-n_current->c; if(diff>0) { ni_current = n_current->right; } else if(diff<0) { ni_current = n_current->left; } else { // ok, le caractère courant est accepté if(si_match_start==UNDEFINED_INDEX) { // On teste si le début de match est le début de chaine ou après un stop_char if(si_current==0 || stop_chars.find(string[si_current-1])<stop_chars.size()) { // oui, on enregistre le début si_match_start=si_current; } else { // non, on passe à la suite ++si_current; } } if(si_match_start!=UNDEFINED_INDEX) { // si le démarrage a bien pris if(n_current->data!=default_value && (si_current==(string.size()-1) || stop_chars.find(string[si_current+1])<stop_chars.size())) { // on a une donnée dans le noeud courant // et on est en fin de chaîne ou le caractère précédent est un stop_char ni_best_match = ni_current; } ++si_current; if(si_current<string.size()) { // Si on peut avancer, on avance ni_current = n_current->next; } else { // Fin de chaine ==> pas de match possible ni_current = UNDEFINED_INDEX; } } } } else { // On est toujours en fin de chaine ==> pas de match possible ni_current = UNDEFINED_INDEX; } if(ni_current==UNDEFINED_INDEX) { // Le caractère courant n'est pas accepté if(ni_best_match!=UNDEFINED_INDEX) { // Si on a un match réussi en cours // Si le match en cours démarre après la zone de non-match // C'est qu'on a bien une zone de non-match int non_match_length = si_match_start-si_non_match_start; if(non_match_length>0) { // On l'envoie. to_perform->perform(string.substr(si_non_match_start,non_match_length),-non_match_length,default_value); } // On envoie maintenant le match // On connait sa longueur grâce à la position dans l'arbre // TODO: voir si on ne pourrait pas de passer de ça tst_node<charT,valueT> *match_node=storage->get(ni_best_match); int match_length = match_node->position+1; // On envoie le match to_perform->perform(string.substr(si_match_start,match_length),match_length,match_node->data); // On repositionne la zone de non-match juste après la fin du match si_non_match_start=si_match_start+match_length; // Annulation du match ni_best_match=UNDEFINED_INDEX; // On backtracke // backtrack de naze parce qu'on ne peut pas utiliser // les infos de backtrack à cause des séparateurs. si_current = si_non_match_start; ni_current = root; ni_best_match=UNDEFINED_INDEX; si_match_start=UNDEFINED_INDEX; } else if(si_match_start!=UNDEFINED_INDEX) { // Si le caractère courant n'est pas accepté, qu'on avait commencé // un match mais que celui-ci n'avait pas réussi, on va backtracker. // backtrack de naze parce qu'on ne peut pas utiliser // les infos de backtrack à cause des séparateurs. si_current=si_match_start+1; ni_current = root; ni_best_match=UNDEFINED_INDEX; si_match_start=UNDEFINED_INDEX; } else { // le caractère courant n'est pas accepté et on n'avait pas de match en cours if(si_current<string.size()) { // si on peut avancer d'un caractère on le fait ++si_current; // on revient à la racine ni_current = root; } else { // si on est à la fin de la chaîne on sort de la boucle pour la fin. break; } } } else { // on avance tranquillement dans l'arbre... } } // on n'arrive ici que si on est arrivé à la fin de la chaine en entrée if((si_current - si_non_match_start)>0) { // charT'il y avait un non-match en cours // on l'envoie to_perform->perform(string.substr(si_non_match_start,si_current - si_non_match_start),-static_cast<int>(si_current - si_non_match_start),default_value); } return to_perform->result(); } #endif /**************************** file I/O *************************************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::read(std::istream& file) { // We check the version number int version_length; file.read((char*)(&version_length),sizeof(size_t)); char* version=(char*)tst_malloc(version_length+1); version[version_length]=0; assert(version); file.read(version,version_length); if(strcmp(TST_VERSION,version)!=0) { tst_free(version); throw TSTException("Invalid version number"); } else { tst_free(version); } serializerT reader; default_value = reader.read(file); // On efface le stockage storage->erase(); if(file.get()) { root = read_node(file,&reader,0); } else { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> int tst<charT,valueT,storageT,serializerT,stringT>::read_node(std::istream& file,serializerT* reader,int depth) { char bitmask = file.get(); node_info<charT,valueT> node_info; storage->new_node(&node_info); file.read((char*)(&(node_info.node->c)),sizeof(charT)); if(bitmask & 16) { node_info.node->store(reader->read(file)); } else { node_info.node->store(default_value); } #ifdef SCANNER // TODO : inutile, peut être recalculé ? file.read((char*)(&(node_info.node->position)),sizeof(int)); - file.read((char*)(&(node_info.node->backtrack)),sizeof(int)); - file.read((char*)(&(node_info.node->backtrack_match_index)),sizeof(int)); #endif int other_index; if(bitmask & 1) { // En deux étapes car le noeud peut bouger physiquement. // Normalement tout se passe bien mais c'est plus rassurant ainsi. other_index = read_node(file,reader,depth+1); storage->get(node_info.index)->next = other_index; } else { storage->get(node_info.index)->next = UNDEFINED_INDEX; } if(bitmask & 2) { other_index = read_node(file,reader,depth+1); storage->get(node_info.index)->left = other_index; } else { storage->get(node_info.index)->left = UNDEFINED_INDEX; } if(bitmask & 4) { other_index = read_node(file,reader,depth+1); storage->get(node_info.index)->right = other_index; } else { storage->get(node_info.index)->right = UNDEFINED_INDEX; } return node_info.index; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::write(std::ostream& file) const { // We save the version number size_t version_length = strlen(TST_VERSION); file.write((char*)(&version_length),sizeof(size_t)); file.write(TST_VERSION,(std::streamsize)version_length); serializerT writer; writer.write(file,default_value); if(root!=UNDEFINED_INDEX) { file.put(1); write_node(file,&writer,root); } else { file.put(0); } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::write_node(std::ostream& file,serializerT* writer,int index) const { tst_node<charT,valueT>* node = storage->get(index); char bitmask=0; if(node->next!=UNDEFINED_INDEX) bitmask |= 1; if(node->left!=UNDEFINED_INDEX) bitmask |= 2; if(node->right!=UNDEFINED_INDEX) bitmask |= 4; if(node->data!=default_value) bitmask |=16; file.put(bitmask); file.write((char*)(&(node->c)),sizeof(charT)); if(bitmask & 16) { writer->write(file,node->data); } #ifdef SCANNER file.write((char*)(&(node->position)),sizeof(int)); - file.write((char*)(&(node->backtrack)),sizeof(int)); - file.write((char*)(&(node->backtrack_match_index)),sizeof(int)); #endif if(bitmask & 1) write_node(file,writer,node->next); if(bitmask & 2) write_node(file,writer,node->left); if(bitmask & 4) write_node(file,writer,node->right); } #endif diff --git a/python/pythonTST.vcproj b/python/pythonTST.vcproj index bfd5fd1..cedebf2 100644 --- a/python/pythonTST.vcproj +++ b/python/pythonTST.vcproj @@ -1,457 +1,461 @@ <?xml version="1.0" encoding="Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="9,00" Name="pythonTST" ProjectGUID="{A5208316-015E-4611-B812-6E2F7CCD33A2}" RootNamespace="pythonTST" Keyword="Win32Proj" TargetFrameworkVersion="131072" > <Platforms> <Platform Name="Win32" /> </Platforms> <ToolFiles> </ToolFiles> <Configurations> <Configuration Name="Debug|Win32" OutputDirectory="Debug" IntermediateDirectory="Debug" ConfigurationType="2" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" UseOfMFC="0" CharacterSet="2" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="D:\projets\python-svn\PC;D:\projets\python-svn\Include;..\include" PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS;SCANNER" MinimalRebuild="false" BasicRuntimeChecks="3" RuntimeLibrary="1" BufferSecurityCheck="true" RuntimeTypeInfo="true" UsePrecompiledHeader="0" DebugInformationFormat="3" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/_tst_d.pyd" LinkIncremental="1" AdditionalLibraryDirectories="&quot;D:\projets\python-svn\PCbuild&quot;" GenerateDebugInformation="true" ProgramDatabaseFile="$(OutDir)/_tst_d.pdb" GenerateMapFile="true" MapExports="true" SubSystem="2" RandomizedBaseAddress="1" DataExecutionPrevention="0" ImportLibrary="$(OutDir)/pyd.lib" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> <Configuration Name="Release|Win32" OutputDirectory="Release" IntermediateDirectory="Release" ConfigurationType="2" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" CharacterSet="2" WholeProgramOptimization="1" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="3" InlineFunctionExpansion="2" EnableIntrinsicFunctions="true" FavorSizeOrSpeed="1" AdditionalIncludeDirectories="E:\Python24\include;..\include" PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" RuntimeLibrary="0" StructMemberAlignment="1" UsePrecompiledHeader="0" WarningLevel="3" Detect64BitPortabilityProblems="true" DebugInformationFormat="3" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/_tst.pyd" LinkIncremental="1" AdditionalLibraryDirectories="E:\Python24\libs" GenerateDebugInformation="true" SubSystem="2" OptimizeReferences="2" EnableCOMDATFolding="2" RandomizedBaseAddress="1" DataExecutionPrevention="0" ImportLibrary="$(OutDir)/pyd.lib" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> <Configuration Name="Debug CRM|Win32" OutputDirectory="$(ConfigurationName)" IntermediateDirectory="$(ConfigurationName)" ConfigurationType="2" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" UseOfMFC="0" CharacterSet="2" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" CommandLine="" AdditionalDependencies="" Outputs="" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="&quot;E:\projets\Python-2.6.4\include&quot;;&quot;E:\projets\Python-2.6.4\PC&quot;;..\include" PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" MinimalRebuild="false" BasicRuntimeChecks="3" RuntimeLibrary="1" BufferSecurityCheck="true" RuntimeTypeInfo="true" UsePrecompiledHeader="0" DebugInformationFormat="3" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/_tst_d.pyd" LinkIncremental="1" AdditionalLibraryDirectories="&quot;E:\projets\Python-2.6.4\PCbuild&quot;" GenerateDebugInformation="true" ProgramDatabaseFile="$(OutDir)/_tst_d.pdb" GenerateMapFile="true" MapExports="true" SubSystem="2" RandomizedBaseAddress="1" DataExecutionPrevention="0" ImportLibrary="$(OutDir)/pyd.lib" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> <Configuration Name="Release CRM|Win32" OutputDirectory="$(ConfigurationName)" IntermediateDirectory="$(ConfigurationName)" ConfigurationType="2" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" CharacterSet="2" WholeProgramOptimization="1" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="3" InlineFunctionExpansion="2" EnableIntrinsicFunctions="true" FavorSizeOrSpeed="1" AdditionalIncludeDirectories="C:\Python24\include;..\include" PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" RuntimeLibrary="0" StructMemberAlignment="1" UsePrecompiledHeader="0" WarningLevel="3" Detect64BitPortabilityProblems="true" DebugInformationFormat="3" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/_tst.pyd" LinkIncremental="1" AdditionalLibraryDirectories="C:\Python24\libs" GenerateDebugInformation="true" SubSystem="2" OptimizeReferences="2" EnableCOMDATFolding="2" RandomizedBaseAddress="1" DataExecutionPrevention="0" ImportLibrary="$(OutDir)/pyd.lib" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> </Configurations> <References> </References> <Files> <Filter Name="Source Files" Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" > <File RelativePath=".\bug.py" > </File> + <File + RelativePath=".\test\test.py" + > + </File> <File RelativePath=".\tst.i" > <FileConfiguration Name="Debug|Win32" > <Tool Name="VCCustomBuildTool" CommandLine="E:\swigwin-1.3.40\swig -c++ -O -DSCANNER -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" AdditionalDependencies="..\include\tst.h;pythonTST.h" Outputs="tst_wrap.cxx" /> </FileConfiguration> <FileConfiguration Name="Release|Win32" > <Tool Name="VCCustomBuildTool" CommandLine="E:\swigwin-1.3.40\swig -O -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" AdditionalDependencies="..\tst.h;pythonTST.h" Outputs="tst_wrap.cxx" /> </FileConfiguration> <FileConfiguration Name="Debug CRM|Win32" > <Tool Name="VCCustomBuildTool" CommandLine="E:\swigwin-1.3.40\swig -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" AdditionalDependencies="..\include\tst.h;pythonTST.h" Outputs="tst_wrap.cxx" /> </FileConfiguration> <FileConfiguration Name="Release CRM|Win32" > <Tool Name="VCCustomBuildTool" CommandLine="E:\swigwin-1.3.40\swig -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" AdditionalDependencies="..\tst.h;pythonTST.h" Outputs="tst_wrap.cxx" /> </FileConfiguration> </File> <File RelativePath=".\tst.py" > </File> <File RelativePath=".\tst_wrap.cxx" > </File> </Filter> <Filter Name="Header Files" Filter="h;hpp;hxx;hm;inl;inc;xsd" UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" > <File RelativePath="..\include\debug.h" > </File> <File RelativePath="..\include\fundamentals.h" > </File> <File RelativePath=".\PythonReference.h" > </File> <File RelativePath=".\pythonTST.h" > </File> <File RelativePath="..\include\tst.h" > </File> </Filter> <Filter Name="Resource Files" Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx" UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}" > </Filter> </Files> <Globals> </Globals> </VisualStudioProject> diff --git a/python/test/test.py b/python/test/test.py index 95f9c6f..032e499 100644 --- a/python/test/test.py +++ b/python/test/test.py @@ -258,560 +258,567 @@ class TestMatch(unittest.TestCase): self.assertEquals(d,dict(abc=(0,"abc"))) def testJoker2(self): d = self.tree.match("???",None,DictAction()) self.assertEquals(d,{'abc': (0, 'abc'), 'bbc': (0, 'bbc')}) def testJoker3(self): d = self.tree.match("??",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab')}) def testStar1(self): d = self.tree.match("a*c",None,DictAction()) self.assertEquals(d,dict(abc=(0,"abc"))) def testStar2(self): d = self.tree.match("a*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'abc': (0, 'abc')}) def testStar2_1(self): d = self.tree.match("ab*",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab'), 'abc': (0, 'abc')}) def testStar2_2(self): d = self.tree.match("*b",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab')}) d = self.tree.match("*bbc",None,DictAction()) self.assertEquals(d,{'bbc': (0, 'bbc')}) def testStar3(self): d = self.tree.match("*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) d = self.tree.match("*?*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) def testStar3_1(self): d = self.tree.match("**",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) d = self.tree.match("***",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) def testStar4(self): d = self.tree.match("e*ny",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar5(self): d = self.tree.match("*****y",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar6(self): d = self.tree.match("????*",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar7(self): d = self.tree.match("ef?f*n?",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) class TestIterators(unittest.TestCase): def setUp(self): self.tree = TST() self.keys = dict( titi = 1, toto = 2, tati = 3, a = 5 ) for k, v in self.keys.iteritems(): self.tree[k] = v def testLexical1(self): d = {} for k, v in self.tree: d[k] = v self.assertEqual(d,self.keys) def testLexical2(self): d = {} for k, v in self.tree.iterator('t'): d[k] = v self.keys.pop('a') self.assertEqual(d,self.keys) def testCloseMatch(self): d = {} for k, v in self.tree.close_match_iterator('t',1): d[k] = v self.assertEqual(d,dict( a = 5 )) d = {} for k, v in self.tree.close_match_iterator('tito',1): d[k] = v self.assertEqual(d,dict( titi = 1, toto = 2 )) d = {} for k, v in self.tree.close_match_iterator('tuto',1): d[k] = v self.assertEqual(d,dict( toto = 2 )) class TestCallableAction(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['foo'] = 'bar' def testCA1(self): res = {} def callback(key, length, obj): res[key] = obj def result(): res['hello'] = 'world' return res self.assertEqual( self.tree.walk(None, CallableAction(callback, result)), {'foo':'bar', 'hello':'world'} ) def testCA2(self): res = {} def callback(key, length, obj): # Provoke an exception print 0 / 0 res[key] = obj def result(): return res try: self.tree.walk(None, CallableAction(callback, result)), self.fail("Should have raised an exception") except ZeroDivisionError: pass def testCA3(self): res = {} def callback(key, length, obj): res[key] = obj def result(): # Provoke an exception return 0/0 try: self.tree.walk(None, CallableAction(callback, result)), self.fail("Should have raised an exception") except ZeroDivisionError: pass class TestCallableFilter(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['foo'] = 'bar' self.tree['bar'] = 'foo' def testCF1(self): res = {} def cfilter(key, length, obj): res[key] = obj return obj self.tree.walk(CallableFilter(cfilter),None) self.assertEqual( res, {'foo':'bar', 'bar':'foo'} ) def testCF2(self): def cfilter(key, length, obj): if key=='foo': return 'boo' else: return obj self.assertEqual( self.tree.walk(CallableFilter(cfilter),DictAction()), {'foo':(0,'boo'),'bar':(0,'foo')} ) def testCF3(self): def cfilter(key, length, obj): if key=='foo': # raises an exception return 0 / 0 else: return obj try: self.tree.walk(CallableFilter(cfilter),DictAction()), self.fail("Should have raised an exception") except ZeroDivisionError: pass class TestHighCapacity(unittest.TestCase): def setUp(self): tree = TST() timer_start('build_big') keys = map(str,xrange(100000)) random.shuffle(keys) timer_end('build_big') timer_start('write_big') for k in keys: tree[k] = k timer_end('write_big') self.keys, self.tree = keys, tree def testGet(self): timer_start('read_big') for k in self.keys: self.assertEqual(self.tree[k],k) timer_end('read_big') def testFullPack(self): timer_start('delete_full') for k in self.keys: del self.tree[k] timer_end('delete_full') self.tree.pack() for k in self.keys: self.assertEqual(self.tree[k],None) sample = random.sample(self.keys,len(self.keys)/10) random.shuffle(sample) timer_start('refill_post_pack/10') for k in sample: self.tree[k] = k timer_end('refill_post_pack/10',10) for k in sample: self.assertEqual(self.tree[k],k) del self.tree[k] self.tree.pack() for k in self.keys: self.assertEqual(self.tree[k],None) self.tree.write_to_file('test.tst') def testDelete(self): sample = random.sample(self.keys,len(self.keys)/10) random.shuffle(sample) timer_start('delete_big/10') for k in sample: del self.tree[k] timer_end('delete_big/10',10) random.shuffle(sample) timer_start('refill_pre_pack/10') for k in sample: self.tree[k] = k timer_end('refill_pre_pack/10',10) self.testGet() random.shuffle(sample) timer_start('delete_big/10') for k in sample: del self.tree[k] timer_end('delete_big/10',10) self.tree.pack() random.shuffle(sample) timer_start('refill_post_pack/10') for k in sample: self.tree[k] = k timer_end('refill_post_pack/10',10) self.testGet() timer_start('delete_big/10') for k in self.keys[:len(self.keys)/10]: del self.tree[k] timer_end('delete_big/10',10) timer_start('pack/10') self.tree.pack() timer_end('pack/10',10) timer_start('check_delete_big') for k in self.keys[:len(self.keys)/10]: self.assertEqual(self.tree[k],None) for k in self.keys[len(self.keys)/10+1:]: self.assertEqual(self.tree[k],k) timer_end('check_delete_big') def testUpdate(self): timer_start('build_big/10') old_keys = self.keys[:len(self.keys)/10] new_keys = map(lambda x:str(int(x) + 1),old_keys) timer_end('build_big/10',10) timer_start('update_big/10') for k,kp in izip(old_keys,new_keys): self.assertEqual(self.tree.put(k,kp),k) timer_end('update_big/10',10) timer_start('check_update_big') for k,kp in izip(old_keys,new_keys): self.assertEqual(self.tree[k],kp) timer_end('check_update_big') class TestScan(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['Nicolas']='Nicolas' self.tree['olaf']='olaf' self.tree['lazlo']='lazlo' self.tree['Nicolas-Antoinette']='Nicolas-Antoinette' self.tree['Antoinette']='Antoinette' self.tree['Antoine']='Antoine' self.tree['astride']='astride' self.tree['VICTOIRE']='VICTOIRE' self.tree['IAN']='IAN' self.tree['x']='x' self.tree['V']='V' self.tree['ROBERT']='ROBERT' self.tree['A N']='A N' self.tree['olaaf']='olaaf' self.tree['laslo']='laslo' def testScanMikeThornton(self): t = TST() t['ccc'] = 1 self.assertEqual(t.scan('cc',TupleListAction()),[('cc',-2,None)]) self.assertEqual(t.scan('ccd',TupleListAction()),[('ccd',-3,None)]) def testScan0_1(self): self.assertEqual(self.tree.scan('Nicolas',TupleListAction()),[('Nicolas', 7, 'Nicolas'),]) def testScan0_2(self): self.assertEqual(self.tree.scan(' Nicolas',TupleListAction()),[(' ',-1,None),('Nicolas', 7, 'Nicolas'),]) def testScan0_3(self): self.assertEqual(self.tree.scan('Nicolas ',TupleListAction()),[('Nicolas', 7, 'Nicolas'),(' ',-1,None),]) def testScan0_4(self): self.assertEqual(self.tree.scan(' Nicolas ',TupleListAction()),[(' ',-1,None),('Nicolas', 7, 'Nicolas'),(' ',-1,None),]) def testScan0_5(self): self.assertEqual(self.tree.scan(' ',TupleListAction()),[(' ',-1,None),]) def testScan0_6(self): self.assertEqual(self.tree.scan('la',TupleListAction()),[('la', -2, None)]) def testScan0_7(self): self.assertEqual(self.tree.scan('lazl',TupleListAction()),[('lazl', -4, None)]) def testScan1(self): timer_start("scan") for i in xrange(10000): self.assertEqual(self.tree.scan('lazlo',TupleListAction()),[('lazlo', 5, 'lazlo')]) self.assertEqual(self.tree.scan('Nicolazlo',TupleListAction()),[('Nico', -4, None), ('lazlo', 5, 'lazlo')]) timer_end("scan") def testScan24(self): self.assertEqual(self.tree.scan('A NicoNicoNicolasNicoNico',TupleListAction()),[('A N', 3, 'A N'), ('icoNico', -7, None), ('Nicolas', 7, 'Nicolas'), ('NicoNico', -8, None)]) def testScan1_1(self): self.assertEqual(self.tree.scan('hippocampe',TupleListAction()),[('hippocampe', -10, None)]) def testScan2(self): self.assertEqual(self.tree.scan('NicolaNicolaNicolaNicolaNicola',TupleListAction()),[('NicolaNicolaNicolaNicolaNicola', -30, None)]) def testScan3(self): self.assertEqual(self.tree.scan('Nicolasstupide',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('stupide', -7, None)]) def testScan4(self): self.assertEqual(self.tree.scan('Nicolast',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('t', -1, None)]) def testScan5(self): self.assertEqual(self.tree.scan('xxxNicolas',TupleListAction()),[('x', 1, 'x'), ('x', 1, 'x'), ('x', 1, 'x'), ('Nicolas', 7, 'Nicolas')]) def testScan6(self): self.assertEqual(self.tree.scan('xxx Nicolas',TupleListAction()),[('x', 1, 'x'), ('x', 1, 'x'), ('x', 1, 'x'), (' ', -1, None), ('Nicolas', 7, 'Nicolas')]) def testScan7(self): self.assertEqual(self.tree.scan('Antoinette Antoinette',TupleListAction()),[('Antoinette', 10, 'Antoinette'), (' ', -1, None), ('Antoinette', 10, 'Antoinette')]) def testScan8(self): self.assertEqual(self.tree.scan('Nicolas-Antoinette',TupleListAction()),[('Nicolas-Antoinette', 18, 'Nicolas-Antoinette')]) def testScan9(self): self.assertEqual(self.tree.scan('Nicolas-Antoine',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) def testScan9_1(self): self.assertEqual(self.tree.scan('Nicolas-Antoine-Antoine',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) def testScan9_2(self): self.assertEqual(self.tree.scan('Nicolas-Antoine-Antoine-',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None)]) def testScan10(self): self.assertEqual(self.tree.scan('Nicolas-Antoinet',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('t', -1, None)]) def testScanWithStopChars1(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolas',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas')]) def testScanWithStopChars2(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolasstupide',' -',TupleListAction()),[('Nicolasstupide', -14, None)]) def testScanWithStopChars25(self): timer_start("scan_stop_chars") for i in xrange(10000): self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) timer_end("scan_stop_chars") def testScanWithStopChars3(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolast',' -',TupleListAction()),[('Nicolast', -8, None)]) def testScanWithStopChars4(self): self.assertEqual(self.tree.scan_with_stop_chars('xxxNicolas',' -',TupleListAction()),[('xxxNicolas', -10, None)]) def testScanWithStopChars5(self): self.assertEqual(self.tree.scan_with_stop_chars('xxx Nicolas',' -',TupleListAction()),[('xxx ', -4, None),('Nicolas', 7, 'Nicolas')]) def testScanWithStopChars6(self): self.assertEqual(self.tree.scan_with_stop_chars('xxxAntoine Nicolas',' -',TupleListAction()),[('xxxAntoine ', -11, None),('Nicolas', 7, 'Nicolas')]) def testScanWithStopChars8(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoinette',' -',TupleListAction()),[('Nicolas-Antoinette', 18, 'Nicolas-Antoinette')]) def testScanWithStopChars9(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoine',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) def testScanWithStopChars10(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoinet',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-Antoinet', -9, None)]) def testScanVicieux(self): self.assertEqual(self.tree.scan_with_stop_chars('xxxAntoine A Nicolas',' -',TupleListAction()),[('xxxAntoine A ', -13, None),('Nicolas', 7, 'Nicolas')]) def testScanVicieux2(self): self.assertEqual(self.tree.scan_with_stop_chars('Antoinette Antoinette',' -',TupleListAction()),[('Antoinette', 10, 'Antoinette'), (' ', -1, None), ('Antoinette', 10, 'Antoinette')]) def testScanVicieux3(self): self.assertEqual(self.tree.scan_with_stop_chars('nastride lazlo',' -',TupleListAction()),[('nastride ', -9, None), ('lazlo', 5, 'lazlo')]) self.assertEqual(self.tree.scan_with_stop_chars('VIAN ROBERT',' -',TupleListAction()),[('VIAN ', -5, None), ('ROBERT', 6, 'ROBERT')]) def testScanKeithDavidson1(self): t = TST() t['333'] = 'ccc' # self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) def testScanKeithDavidson2(self): t = TST() t['333'] = 'ccc' self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) def testScanKeithDavidson2_1(self): t = TST() t['333'] = 'ccc' self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) def testScanKeithDavidson3(self): t = TST() t['333'] = 'ccc' self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) self.assertEqual(t.scan('.3.',TupleListAction()),[('.3.',-3,None)]) self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) def testScanKeithDavidson4(self): t = TST() t['3333'] = 'ccc' # self.assertEqual(t.scan('.333.',TupleListAction()),[('.333.',-5,None)]) self.assertEqual(t.scan('.333333.',TupleListAction()),[('.',-1,None),('3333',4,'ccc'),('33.',-3,None)]) def testScanKeithDavidson5(self): t = TST() t['3333'] = 'ccc' self.assertEqual(t.scan('.333.',TupleListAction()),[('.333.',-5,None)]) self.assertEqual(t.scan('.333333.',TupleListAction()),[('.',-1,None),('3333',4,'ccc'),('33.',-3,None)]) def testScanKeithDavidson6(self): t = TST() t['333'] = 'ccc' self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) def testScanKeithDavidson7(self): t = TST() t['333'] = 'ccc' self.assertEqual(t.scan('.3.',TupleListAction()),[('.3.',-3,None)]) self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) class TestNewScan(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['333'] = 'A' self.tree['334'] = 'B' self.tree['3333'] = 'C' self.tree['33378'] = 'D' + self.tree['3339993339'] = 'E' def testA(self): self.assertEqual(self.tree.scan('3',TupleListAction()),[('3',-1,None)]) self.assertEqual(self.tree.scan('33',TupleListAction()),[('33',-2,None)]) self.assertEqual(self.tree.scan('3333',TupleListAction()),[('3333',4,'C')]) def testB(self): self.assertEqual(self.tree.scan('',TupleListAction()),[]) self.assertEqual(self.tree.scan('coucou',TupleListAction()),[('coucou',-6,None)]) def testC(self): self.assertEqual(self.tree.scan('3337',TupleListAction()),[('333',3,'A'),('7',-1,None)]) self.assertEqual(self.tree.scan('23337',TupleListAction()),[('2',-1,None),('333',3,'A'),('7',-1,None)]) def testD(self): self.assertEqual(self.tree.scan('333',TupleListAction()),[('333',3,'A')]) self.assertEqual(self.tree.scan('3333',TupleListAction()),[('3333',4,'C')]) self.assertEqual(self.tree.scan('33378',TupleListAction()),[('33378',5,'D')]) self.assertEqual(self.tree.scan('0333',TupleListAction()),[('0',-1,None),('333',3,'A')]) self.assertEqual(self.tree.scan('335333',TupleListAction()),[('335',-3,None),('333',3,'A')]) def testE(self): self.assertEqual(self.tree.scan('34',TupleListAction()),[('34',-2,None)]) self.assertEqual(self.tree.scan('335',TupleListAction()),[('335',-3,None)]) self.assertEqual(self.tree.scan('2335',TupleListAction()),[('2335',-4,None)]) self.assertEqual(self.tree.scan('33332335',TupleListAction()),[('3333',4,'C'),('2335',-4,None)]) + def testF(self): + self.assertEqual(self.tree.scan('3339993339',TupleListAction()),[('3339993339',10,'E')]) + self.assertEqual(self.tree.scan('333999333',TupleListAction()),[('333',3,'A'),('999',-3,None),('333',3,'A')]) + self.assertEqual(self.tree.scan('3339993333',TupleListAction()),[('333',3,'A'),('999',-3,None),('3333',4,'C')]) + self.assertEqual(self.tree.scan('3339993338',TupleListAction()),[('333',3,'A'),('999',-3,None),('333',3,'A'),('8',-1,None)]) + if __name__ == '__main__': print "Testing pytst %s"%TST_VERSION comment = ' '.join(sys.argv[1:]) suite = unittest.TestSuite(( unittest.makeSuite(TestCollectors), unittest.makeSuite(TestBasics), unittest.makeSuite(TestHighCapacity), unittest.makeSuite(TestScan), unittest.makeSuite(TestNewScan), unittest.makeSuite(TestIterators), unittest.makeSuite(TestMatch), unittest.makeSuite(TestCallableAction), unittest.makeSuite(TestCallableFilter), )) for i in xrange(3): unittest.TextTestRunner().run(suite) print_timers(comment)
nlehuen/pytst
f9d379644e2a96fa1b2f697c533a8dcb6a002525
New, improved scan algorithm. This solves the bug reported by Keith Davidson. It's not optimal yet (see the "TODO : prevent backtrack using tree analysis" comment) but it works correctly which is most important for now.
diff --git a/include/memory_storage.h b/include/memory_storage.h index 7c31723..212833c 100644 --- a/include/memory_storage.h +++ b/include/memory_storage.h @@ -1,166 +1,166 @@ -/* - # $Id$ - # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> - # - # This library is free software; you can redistribute it and/or - # modify it under the terms of the GNU Lesser General Public - # License as published by the Free Software Foundation; either - # version 2.1 of the License, or (at your option) any later version. - # - # This library is distributed in the hope that it will be useful, - # but WITHOUT ANY WARRANTY; without even the implied warranty of - # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - # Lesser General Public License for more details. - # - # You should have received a copy of the GNU Lesser General Public - # License along with this library; if not, write to the Free Software - # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -#ifndef __MEMORY_STORAGE__H_INCLUDED__ -#define __MEMORY_STORAGE__H_INCLUDED__ - -#include <vector> -#include <map> -#include <algorithm> - -template <typename charT,typename valueT> -class memory_storage { -public: - typedef typename std::vector< tst_node<charT,valueT> > array_type; - typedef typename array_type::iterator iterator_type; - typedef typename array_type::reverse_iterator reverse_iterator_type; - typedef typename array_type::size_type size_type; - - memory_storage(int initial_size) : array(), empty(UNDEFINED_INDEX) { - array.reserve(initial_size); - } - - ~memory_storage() { - } - - inline tst_node<charT,valueT>* get(int index) { - return &(array[index]); - } - - inline void delete_node(int index) { - get(index)->next = empty; - empty = index; - } - - void new_node(node_info<charT,valueT>* info); - void pack(int& root); - - void erase() { - array_type().swap(array); - }; - - typename array_type::size_type size() { - return array.size(); - } - -protected: - array_type array; - int empty; -}; - -template <typename charT,typename valueT> -void memory_storage<charT,valueT>::new_node(node_info<charT,valueT>* info) { - if(empty!=UNDEFINED_INDEX) { - // si on a un noeud vide on l'utilise. - info->index=empty; - info->node=get(empty); - info->node->reset(); - - // on passe au noeud vide suivant. - empty = get(empty)->next; - } - else { - // on construit un noeud supplémentaire dans le tableau. - info->index = (int)array.size(); - array.resize(array.size()+1); - // array.push_back(tst_node<charT,valueT>()); // Plus ou moins rapide ? - info->node=get(info->index); - } -} - -template <typename charT,typename valueT> -void memory_storage<charT,valueT>::pack(int& root) { - if(empty == UNDEFINED_INDEX) { - return; - } - - // Etape 1 : on construit un vector des numéros de noeuds vide - std::vector<int> empty_nodes; - while(empty!=UNDEFINED_INDEX) { - empty_nodes.push_back(empty); - empty = get(empty)->next; - } - - // Etape 2 : on trie ce vecteur - std::sort(empty_nodes.begin(),empty_nodes.end()); - - // Etape 3 : on remplit les noeuds vides avec des noeuds pleins pris en - // fin du storage - std::map<int,int> mapping; // sera utile en étape 4 - int current_empty_node=0, last_empty_node = static_cast<int>(empty_nodes.size())-1; - int last_node_index = static_cast<int>(array.size())-1 ; - - while(current_empty_node<=last_empty_node) { - int last_empty_node_index = empty_nodes[last_empty_node]; - if(last_empty_node_index<last_node_index) { - // le dernier noeud est plein - // on l'échange avec le premier noeud vide - int current_empty_node_index = empty_nodes[current_empty_node]; - mapping[last_node_index] = current_empty_node_index; - array[current_empty_node_index] = array[last_node_index]; - --last_node_index; - ++current_empty_node; - } - else { - // le dernier noeud est vide - // on le supprime - --last_node_index; - --last_empty_node; - } - } - - // Etape 4 : on réécrit les indices - std::map<int,int>::const_iterator item,end(mapping.end()); - - // La racine a peut-être bougé ? - item = mapping.find(root); - if(item!=end) { - root = item->second; - } - - last_empty_node = 0; - while(last_empty_node <= last_node_index) { - tst_node<charT,valueT>* node = get(last_empty_node); - if(node->left!=UNDEFINED_INDEX) { - item = mapping.find(node->left); - if(item!=end) { - node->left = item->second; - } - } - if(node->right!=UNDEFINED_INDEX) { - item = mapping.find(node->right); - if(item!=end) { - node->right = item->second; - } - } - if(node->next!=UNDEFINED_INDEX) { - item = mapping.find(node->next); - if(item!=end) { - node->next = item->second; - } - } - - ++last_empty_node; - } - - // Etape 5 : on redimensionne le tableau - array.resize(last_node_index+1); - array_type(array).swap(array); -} - -#endif +/* + # $Id$ + # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> + # + # This library is free software; you can redistribute it and/or + # modify it under the terms of the GNU Lesser General Public + # License as published by the Free Software Foundation; either + # version 2.1 of the License, or (at your option) any later version. + # + # This library is distributed in the hope that it will be useful, + # but WITHOUT ANY WARRANTY; without even the implied warranty of + # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + # Lesser General Public License for more details. + # + # You should have received a copy of the GNU Lesser General Public + # License along with this library; if not, write to the Free Software + # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#ifndef __MEMORY_STORAGE__H_INCLUDED__ +#define __MEMORY_STORAGE__H_INCLUDED__ + +#include <vector> +#include <map> +#include <algorithm> + +template <typename charT,typename valueT> +class memory_storage { +public: + typedef typename std::vector< tst_node<charT,valueT> > array_type; + typedef typename array_type::iterator iterator_type; + typedef typename array_type::reverse_iterator reverse_iterator_type; + typedef typename array_type::size_type size_type; + + memory_storage(int initial_size) : array(), empty(UNDEFINED_INDEX) { + array.reserve(initial_size); + } + + ~memory_storage() { + } + + inline tst_node<charT,valueT>* get(int index) { + return index==UNDEFINED_INDEX ? NULL : &(array[index]); + } + + inline void delete_node(int index) { + get(index)->next = empty; + empty = index; + } + + void new_node(node_info<charT,valueT>* info); + void pack(int& root); + + void erase() { + array_type().swap(array); + }; + + typename array_type::size_type size() { + return array.size(); + } + +protected: + array_type array; + int empty; +}; + +template <typename charT,typename valueT> +void memory_storage<charT,valueT>::new_node(node_info<charT,valueT>* info) { + if(empty!=UNDEFINED_INDEX) { + // si on a un noeud vide on l'utilise. + info->index=empty; + info->node=get(empty); + info->node->reset(); + + // on passe au noeud vide suivant. + empty = get(empty)->next; + } + else { + // on construit un noeud supplémentaire dans le tableau. + info->index = (int)array.size(); + array.resize(array.size()+1); + // array.push_back(tst_node<charT,valueT>()); // Plus ou moins rapide ? + info->node=get(info->index); + } +} + +template <typename charT,typename valueT> +void memory_storage<charT,valueT>::pack(int& root) { + if(empty == UNDEFINED_INDEX) { + return; + } + + // Etape 1 : on construit un vector des numéros de noeuds vide + std::vector<int> empty_nodes; + while(empty!=UNDEFINED_INDEX) { + empty_nodes.push_back(empty); + empty = get(empty)->next; + } + + // Etape 2 : on trie ce vecteur + std::sort(empty_nodes.begin(),empty_nodes.end()); + + // Etape 3 : on remplit les noeuds vides avec des noeuds pleins pris en + // fin du storage + std::map<int,int> mapping; // sera utile en étape 4 + int current_empty_node=0, last_empty_node = static_cast<int>(empty_nodes.size())-1; + int last_node_index = static_cast<int>(array.size())-1 ; + + while(current_empty_node<=last_empty_node) { + int last_empty_node_index = empty_nodes[last_empty_node]; + if(last_empty_node_index<last_node_index) { + // le dernier noeud est plein + // on l'échange avec le premier noeud vide + int current_empty_node_index = empty_nodes[current_empty_node]; + mapping[last_node_index] = current_empty_node_index; + array[current_empty_node_index] = array[last_node_index]; + --last_node_index; + ++current_empty_node; + } + else { + // le dernier noeud est vide + // on le supprime + --last_node_index; + --last_empty_node; + } + } + + // Etape 4 : on réécrit les indices + std::map<int,int>::const_iterator item,end(mapping.end()); + + // La racine a peut-être bougé ? + item = mapping.find(root); + if(item!=end) { + root = item->second; + } + + last_empty_node = 0; + while(last_empty_node <= last_node_index) { + tst_node<charT,valueT>* node = get(last_empty_node); + if(node->left!=UNDEFINED_INDEX) { + item = mapping.find(node->left); + if(item!=end) { + node->left = item->second; + } + } + if(node->right!=UNDEFINED_INDEX) { + item = mapping.find(node->right); + if(item!=end) { + node->right = item->second; + } + } + if(node->next!=UNDEFINED_INDEX) { + item = mapping.find(node->next); + if(item!=end) { + node->next = item->second; + } + } + + ++last_empty_node; + } + + // Etape 5 : on redimensionne le tableau + array.resize(last_node_index+1); + array_type(array).swap(array); +} + +#endif diff --git a/include/tst.h b/include/tst.h index 9b0fef3..f58b323 100644 --- a/include/tst.h +++ b/include/tst.h @@ -1,1481 +1,1477 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __TST__H_INCLUDED__ #define __TST__H_INCLUDED__ const char* const TST_VERSION = "1.18RC"; #include "debug.h" #include <iostream> #ifdef __PYTHON__BUILD__ #include "Python.h" #define tst_malloc PyMem_Malloc #define tst_realloc PyMem_Realloc #define tst_free PyMem_Free // Pour ajouter/supprimer les fonctions de scanning. #define SCANNER #else #include "stdlib.h" #define tst_malloc malloc #define tst_realloc realloc #define tst_free free // Pour ajouter/supprimer les fonctions de scanning. // #define SCANNER #endif template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst; #include "fundamentals.h" #include "memory_storage.h" #include "iterators.h" template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst { public: friend class lexical_iterator<charT,valueT,storageT,serializerT,stringT>; friend class match_iterator<charT,valueT,storageT,serializerT,stringT>; typedef charT character_type; typedef valueT value_type; typedef storageT storage_type; typedef serializerT serializer_type; tst(); virtual ~tst() { delete storage; } void pack() { storage->pack(root); } valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,const stringT & string) const; valueT close_match(const stringT & string,int maximum_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT prefix_match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT get(const stringT & string) const; valueT get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory); valueT put(const stringT & string,valueT data); void remove(const stringT & string); bool contains(const stringT & string) const; void write(std::ostream &file) const; void read(std::istream &file); lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator() const { stringT key; return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,key,root); } lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; find_node(&current_index,&best_node,string); return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,string.substr(0,string.size()-1),current_index); } match_iterator<charT,valueT,storageT,serializerT,stringT> close_match_iterator(const stringT & string,int distance) const { return match_iterator<charT,valueT,storageT,serializerT,stringT>(this,string,distance,root); } int get_number_of_nodes() const { return storage->size(); } valueT get_default_value() const { return default_value; } #ifdef SCANNER valueT scan(const stringT & string,tst_action<charT,valueT,stringT>* to_perform); valueT scan_with_stop_chars(const stringT & string,const stringT& stop_chars,tst_action<charT,valueT,stringT>* to_perform) const; #endif protected: void set_storage(storageT* new_storage) { delete storage; storage = new_storage; } private: storageT* storage; valueT default_value; int root; void walk_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void close_match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,const size_t position, const int distance, const int remaining_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_joker_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_star_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; int build_node(node_info<charT,valueT>* current_node,const stringT & string,size_t current_position); void remove_node(int* current_index,const stringT & string,const size_t position); + int find_char(tst_node<charT,valueT>** current_node, charT c) const; tst_node<charT,valueT>* find_node(int* current_index,int* best_node, const stringT & string) const; void balance_node(node_info<charT,valueT>* bal); void ll(node_info<charT,valueT>* bal); void rr(node_info<charT,valueT>* bal); void lr(node_info<charT,valueT>* bal); void rl(node_info<charT,valueT>* bal); void compute_height_and_balance(node_info<charT,valueT>* current_node_info) const; void write_node(std::ostream& file,serializerT* writer,int index) const; int read_node(std::istream& file,serializerT* reader,int depth); #ifdef SCANNER void compute_backtrack(tst_node<charT,valueT> *current_node,const stringT & string,int si_match_start,int si_match_end); #endif }; template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst<charT,valueT,storageT,serializerT,stringT>::tst() : storage(new storage_type(16)), default_value() { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } /*************************** high-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return current_node->data; } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> bool tst<charT,valueT,storageT,serializerT,stringT>::contains(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return true; } else { return false; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::put(const stringT & string,valueT data) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; return storage->get(node_index)->store(data); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; tst_node<charT,valueT>* current_node=storage->get(node_index); valueT data = current_node->data; if(data==default_value) { data=factory->perform(string,0,current_node->data); current_node->store(data); return data; } else { return data; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove(const stringT & string) { remove_node(&root,string,0); if(root==UNDEFINED_INDEX) { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } } /**************************** low-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst_node<charT,valueT>* tst<charT,valueT,storageT,serializerT,stringT>::find_node(int* current_index,int* best_node,const stringT & string) const { tst_node<charT,valueT>* current_node; int diff; size_t pos=0; while(*current_index!=UNDEFINED_INDEX) { current_node=storage->get(*current_index); if(current_node->c==0) { *current_index=UNDEFINED_INDEX; return 0; } else { diff=string[pos]-(current_node->c); } if(diff==0) { if(current_node->data!=default_value) { *best_node=*current_index; } ++pos; if(pos<string.size()) { *current_index = current_node->next; } else { return current_node; } } else if(diff>0) { *current_index=current_node->right; } else { *current_index=current_node->left; } } return 0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> int tst<charT,valueT,storageT,serializerT,stringT>::build_node(node_info<charT,valueT>* current_node_info,const stringT & string,size_t current_position) { int diff,result; if(current_node_info->node->c==0) { current_node_info->node->c=string[current_position]; #ifdef SCANNER current_node_info->node->position=current_position; #endif diff=0; } else { diff=string[current_position]-(current_node_info->node->c); } current_node_info->height=-1; current_node_info->balance_performed=0; if(diff==0) { ++current_position; compute_height_and_balance(current_node_info); // TODO : est-ce bien necessaire ? if(current_position<string.size()) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->next; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->next = next_node_info.index; return result; } else { return current_node_info->index; } } else if(diff>0) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->right; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->right = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->left==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = next_node_info.height; current_node_info->left_balance = 0; current_node_info->right_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->left; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = next_node_info.height-other_node_info.height; current_node_info->left_balance = other_node_info.balance; current_node_info->right_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } else { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->left; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->left = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->right==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = -next_node_info.height; current_node_info->right_balance = 0; current_node_info->left_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->right; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = other_node_info.height-next_node_info.height; current_node_info->right_balance = other_node_info.balance; current_node_info->left_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove_node(int* current_index,const stringT & string,const size_t current_position) { tst_node<charT,valueT>* current_node = storage->get(*current_index); int diff,*next_index; if(current_node->c==0) { return; } else { diff=string[current_position]-(current_node->c); } if(diff==0) { if(current_position+1<string.size()) { next_index = &(current_node->next); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position+1); } } else { current_node->store(default_value); } } else if(diff>0) { next_index = &(current_node->right); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } else { next_index = &(current_node->left); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } current_node=storage->get(*current_index); if( current_node->data==default_value && current_node->next==UNDEFINED_INDEX && current_node->right==UNDEFINED_INDEX && current_node->left==UNDEFINED_INDEX) { storage->delete_node(*current_index); *current_index=UNDEFINED_INDEX; } else { node_info<charT,valueT> current_node_info; current_node_info.index=*current_index; current_node_info.node=current_node; current_node_info.height=-1; balance_node(&current_node_info); *current_index = current_node_info.index; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::balance_node(node_info<charT,valueT>* bal) { if(bal->height==-1) { compute_height_and_balance(bal); } bal->balance_performed=0; if(bal->balance>1) { if(bal->right_balance>0) { rr(bal); } else { rl(bal); } bal->balance_performed=1; } else if(bal->balance<-1) { if(bal->left_balance<0) { ll(bal); } else { lr(bal); } bal->balance_performed=1; } assert(abs(bal->balance)<2); assert(abs(bal->right_balance)<2); assert(abs(bal->left_balance)<2); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::ll(node_info<charT,valueT>* bal) { int left_index=bal->node->left; tst_node<charT,valueT>* left_node=storage->get(left_index); int left_right_index=left_node->right; bal->node->left=left_right_index; left_node->right=bal->index; bal->index=left_index; bal->node=storage->get(left_index); bal->height=bal->height-1; bal->balance=0; bal->right_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rr(node_info<charT,valueT>* bal) { int right_index=bal->node->right; tst_node<charT,valueT>* right_node=storage->get(right_index); int right_left_index=right_node->left; bal->node->right=right_left_index; right_node->left=bal->index; bal->index=right_index; bal->node=storage->get(right_index); bal->height=bal->height-1; bal->balance=0; bal->left_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::lr(node_info<charT,valueT>* bal) { node_info<charT,valueT> left; left.index = bal->node->left; left.node = storage->get(left.index); rr(&left); bal->node->left=left.index; ll(bal); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rl(node_info<charT,valueT>* bal) { node_info<charT,valueT> right; right.index = bal->node->right; right.node = storage->get(right.index); ll(&right); bal->node->right=right.index; rr(bal); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::compute_height_and_balance(node_info<charT,valueT>* current_node_info) const { int left = current_node_info->node->left; int right = current_node_info->node->right; if(right!=UNDEFINED_INDEX) { node_info<charT,valueT> right_balance; right_balance.index=right; right_balance.node=storage->get(right); compute_height_and_balance(&right_balance); if(left!=UNDEFINED_INDEX) { node_info<charT,valueT> left_balance; left_balance.index=left; left_balance.node=storage->get(left); compute_height_and_balance(&left_balance); if(left_balance.height > right_balance.height) { current_node_info->height = left_balance.height+1; } else { current_node_info->height = right_balance.height+1; } current_node_info->balance = right_balance.height-left_balance.height; current_node_info->right_balance = right_balance.balance; current_node_info->left_balance = left_balance.balance; } else { current_node_info->height = right_balance.height + 1; current_node_info->balance = right_balance.height; current_node_info->right_balance = right_balance.balance; current_node_info->left_balance = 0; } } else { if(left!=UNDEFINED_INDEX) { node_info<charT,valueT> left_balance; left_balance.index=left; left_balance.node=storage->get(left); compute_height_and_balance(&left_balance); current_node_info->height = left_balance.height + 1; current_node_info->balance = -left_balance.height; current_node_info->right_balance = 0; current_node_info->left_balance = left_balance.balance; } else { current_node_info->height = 0; current_node_info->balance = 0; current_node_info->right_balance = 0; current_node_info->left_balance = 0; } } } /**************************** close_match *************************************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::close_match(const stringT & string, int maximum_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const { stringT key; close_match_recurse(storage->get(root),key,string,0,maximum_distance,maximum_distance,filter,to_perform); if(to_perform) { return to_perform->result(); } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::close_match_recurse(tst_node<charT,valueT>* current_node,stringT& current_key,const stringT & string, const size_t position, const int distance, const int remaining_distance,tst_filter<charT,valueT,stringT>* filter, tst_action<charT,valueT,stringT>* to_perform) const { // LEFT int other_index=current_node->left; if (other_index!=UNDEFINED_INDEX) { close_match_recurse(storage->get(other_index),current_key,string,position,distance,remaining_distance,filter,to_perform); } int diff=1; if(position<string.size() && string[position]==current_node->c) { diff=0; } // ++KEY current_key.push_back(current_node->c); // CURRENT valueT data = current_node->data; if(data!=default_value) { int new_remaining_distance=string.size() - position - 1; if(new_remaining_distance<0) { new_remaining_distance = 0; } new_remaining_distance = remaining_distance - diff - new_remaining_distance; if(new_remaining_distance>=0) { if(filter) { data = filter->perform(current_key,distance-new_remaining_distance,data); } if(data!=default_value && to_perform) { to_perform->perform(current_key,distance-new_remaining_distance,data); } } } // CURRENT, NEXT other_index=current_node->next; if (other_index!=UNDEFINED_INDEX) { int new_remaining_distance = remaining_distance - diff; if (new_remaining_distance>=0) { close_match_recurse(storage->get(other_index),current_key,string,position+1,distance,new_remaining_distance,filter,to_perform); } } // SKIP_INPUT if(other_index!=UNDEFINED_INDEX && remaining_distance>0) { close_match_recurse(storage->get(other_index),current_key,string,position,distance,remaining_distance-1,filter,to_perform); } // --KEY current_key.resize(current_key.size()-1); // SKIP_BASE if(position<string.size() && remaining_distance>0) { close_match_recurse(current_node,current_key,string,position+1,distance,remaining_distance-1,filter,to_perform); } // RIGHT other_index = current_node->right; if(other_index!=UNDEFINED_INDEX) { close_match_recurse(storage->get(other_index),current_key,string,position,distance,remaining_distance,filter,to_perform); } } /**************************** match *************************************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const { stringT key; match_recurse(storage->get(root),key,string,0,filter,to_perform,false); if(to_perform) { return to_perform->result(); } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::match_recurse(tst_node<charT,valueT>* current_node,stringT& current_key,const stringT & string, size_t position,tst_filter<charT,valueT,stringT>* filter, tst_action<charT,valueT,stringT>* to_perform, bool advance) const { stringT this_key(current_key); while(true) { charT c = string[position]; switch(c) { case static_cast<charT>('?'): { match_joker_recurse(current_node,this_key,string,position,filter,to_perform,advance); return; } case static_cast<charT>('*'): { match_star_recurse(current_node,this_key,string,position,filter,to_perform,advance); return; } default: { int other_index; if(advance) { other_index = current_node->next; if(other_index!=UNDEFINED_INDEX) { current_node = storage->get(other_index); advance = false; } else { return; } } while(true) { if(c == current_node->c) { this_key.push_back(current_node->c); if(position==(string.size()-1)) { valueT data = current_node->data; if(data!=default_value) { if(filter) { data = filter->perform(this_key,0,data); } if(to_perform) { to_perform->perform(this_key,0,data); } } return; } else { ++position; advance = true; break; } } else if(c > current_node->c) { other_index = current_node->right; if(other_index!=UNDEFINED_INDEX) { current_node = storage->get(other_index); } else { return; } } else { other_index = current_node->left; if(other_index!=UNDEFINED_INDEX) { current_node = storage->get(other_index); } else { return; } } } } } } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::match_joker_recurse(tst_node<charT,valueT>* current_node,stringT& current_key,const stringT & string, size_t position,tst_filter<charT,valueT,stringT>* filter, tst_action<charT,valueT,stringT>* to_perform,bool advance) const { int other_index; if(advance) { other_index=current_node->next; if(other_index!=UNDEFINED_INDEX) { current_node = storage->get(other_index); } else { return; } } // LEFT other_index=current_node->left; if(other_index!=UNDEFINED_INDEX) { match_joker_recurse(storage->get(other_index),current_key,string,position,filter,to_perform,false); } // MATCH_CURRENT // ++KEY current_key.push_back(current_node->c); if(position==(string.size()-1)) { valueT data = current_node->data; if(data!=default_value) { if(filter) { data = filter->perform(current_key,0,data); } if(to_perform) { to_perform->perform(current_key,0,data); } } } else { match_recurse(current_node,current_key,string,position+1,filter,to_perform,true); } // --KEY current_key.resize(current_key.size()-1); // RIGHT other_index=current_node->right; if(other_index!=UNDEFINED_INDEX) { match_joker_recurse(storage->get(other_index),current_key,string,position,filter,to_perform,false); } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::match_star_recurse(tst_node<charT,valueT>* current_node,stringT& current_key,const stringT & string, size_t position,tst_filter<charT,valueT,stringT>* filter, tst_action<charT,valueT,stringT>* to_perform,bool advance) const { int other_index; if(advance) { // PREVIOUS_MATCH if(position==(string.size()-1)) { valueT data = current_node->data; if(data!=default_value) { if(filter) { data = filter->perform(current_key,0,data); } if(to_perform) { to_perform->perform(current_key,0,data); } } } other_index=current_node->next; if(other_index!=UNDEFINED_INDEX) { current_node = storage->get(other_index); } else { return; } } // MATCH_WITHOUT_ME match_recurse(current_node,current_key,string,position+1,filter,to_perform,false); // MATCH_CURRENT current_key.push_back(current_node->c); if(position==(string.size()-1)) { valueT data = current_node->data; if(data!=default_value) { if(filter) { data = filter->perform(current_key,0,data); } if(to_perform) { to_perform->perform(current_key,0,data); } } } // MATCH_SAME match_star_recurse(current_node,current_key,string,position,filter,to_perform,true); // MATCH_NEXT match_recurse(current_node,current_key,string,position+1,filter,to_perform,true); // --KEY current_key.resize(current_key.size()-1); // LEFT other_index=current_node->left; if(other_index!=UNDEFINED_INDEX) { match_star_recurse(storage->get(other_index),current_key,string,position,filter,to_perform,false); } // RIGHT other_index=current_node->right; if(other_index!=UNDEFINED_INDEX) { match_star_recurse(storage->get(other_index),current_key,string,position,filter,to_perform,false); } } /**************************** walk *************************************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const { stringT key; walk_recurse(storage->get(root),key,filter,to_perform); if(to_perform) { return to_perform->result(); } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,const stringT & string) const { int index = root; int best_node = UNDEFINED_INDEX; tst_node<charT,valueT>* start = find_node(&index,&best_node,string); if(start) { valueT data = start->data; if(data!=default_value) { if(filter) { data = filter->perform(string,0,data); } if(to_perform) { to_perform->perform(string,0,data); } } index = start->next; if(index!=UNDEFINED_INDEX) { stringT key(string); walk_recurse(storage->get(index),key,filter,to_perform); } } if(to_perform) { return to_perform->result(); } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::walk_recurse(tst_node<charT,valueT>* current_node,stringT& current_key,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const { int other_index; other_index=current_node->left; if(other_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(other_index),current_key,filter,to_perform); } // ++KEY current_key.push_back(current_node->c); valueT data = current_node->data; if(data!=default_value) { if(filter) { data = filter->perform(current_key,0,data); } if(to_perform) { to_perform->perform(current_key,0,data); } } other_index=current_node->next; if(other_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(other_index),current_key,filter,to_perform); } // --KEY current_key.resize(current_key.size()-1); other_index=current_node->right; if(other_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(other_index),current_key,filter,to_perform); } } /**************************** prefix_match *************************************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::prefix_match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const { stringT current_key; size_t position=0; valueT biggest=default_value; int biggest_length=0; int current_index=root; tst_node<charT,valueT>* current_node; int diff; charT c; while(position<string.size()) { c = string[position]; ++position; current_key.push_back(c); while(current_index!=UNDEFINED_INDEX) { current_node=storage->get(current_index); diff=c-current_node->c; if(diff==0) { if(current_node->data!=default_value) { biggest=current_node->data; biggest_length=current_key.size(); if(filter) { biggest=filter->perform(current_key.substr(0,biggest_length),0,biggest); } } if(position<string.size()) { current_index=current_node->next; break; } else { if(biggest!=default_value && to_perform) { to_perform->perform(current_key.substr(0,biggest_length),0,biggest); } current_index=current_node->next; if(current_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(current_index),current_key,filter,to_perform); } return to_perform->result(); } } else if(diff>0) { current_index=current_node->right; } else { current_index=current_node->left; } } if(current_index==UNDEFINED_INDEX) { break; } } if(biggest!=default_value && to_perform) { to_perform->perform(current_key.substr(0,biggest_length),0,biggest); } return to_perform->result(); } -/**************************** scan *************************************/ - -#ifdef SCANNER template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> - valueT tst<charT,valueT,storageT,serializerT,stringT>::scan(const stringT & string,tst_action<charT,valueT,stringT>* to_perform) { - // Le premier caractère de la chaine ne correspondant pas à un match - size_t si_non_match_start=0; - // Le noeud pour lequel on a enregistré un match (noeud avec un objet associé) - int ni_best_match=UNDEFINED_INDEX; - // Le premier caractère de la chaine correspondant à un match - int si_match_start=UNDEFINED_INDEX; - // La position actuelle dans la chaîne (index) - size_t si_current=0; - // Le numéro du noeud actuel de l'arbre - int ni_current=root; - // Le noeud actuel de l'arbre - tst_node<charT,valueT> *n_current; - // Boucle principale - while(1) { - n_current = storage->get(ni_current); - - // On avance dans l'arbre d'un cran - if(si_current<string.size()) { - int diff=string[si_current]-n_current->c; - if(diff>0) { - ni_current=n_current->right; - } - else if(diff<0) { - ni_current=n_current->left; - } - else { - // ok, le caractère courant est accepté - if(si_match_start==UNDEFINED_INDEX) { - // Si on n'a pas encore enregistré un début de match - // on le fait - si_match_start=si_current; - } - - if(n_current->data!=default_value) { - // Si le noeud en cours contient une valeur - // on l'enregistre - ni_best_match=ni_current; - } + inline int tst<charT,valueT,storageT,serializerT,stringT>::find_char(tst_node<charT,valueT> **n_current, charT c) const { + while(1) { + int diff = c - (*n_current)->c; + if(diff == 0) { + return 1; + } + else { + int ni_next; + + if(diff>0) { + ni_next = (*n_current)->right; + } + else { + ni_next = (*n_current)->left; + } - ++si_current; - if(si_current<string.size()) { - // Si on peut avancer, on avance - ni_current=n_current->next; - } - else { - // Fin de chaine ==> pas de match possible - ni_current=UNDEFINED_INDEX; - } - } + if(ni_next==UNDEFINED_INDEX) { + *n_current = storage->get(root); + return 0; } else { - // On est toujours en fin de chaine ==> pas de match possible - ni_current=UNDEFINED_INDEX; + *n_current = storage->get(ni_next); } + } + } + } - if(ni_current==UNDEFINED_INDEX) { - // Le caractère courant n'est pas accepté - if(ni_best_match!=UNDEFINED_INDEX) { - // Si on a un match réussi en cours +/**************************** scan *************************************/ - // Si le match en cours démarre après la zone de non-match - // C'est qu'on a bien une zone de non-match - int non_match_length = si_match_start-si_non_match_start; - if(non_match_length>0) { - // On l'envoie. - to_perform->perform(string.substr(si_non_match_start,non_match_length),-non_match_length,default_value); - } +#ifdef SCANNER - // On envoie maintenant le match - // On connait sa longueur grâce à la position dans l'arbre - // TODO: voir si on ne pourrait pas de passer de ça - tst_node<charT,valueT> *match_node=storage->get(ni_best_match); - int match_length = match_node->position+1; - // On envoie le match - to_perform->perform(string.substr(si_match_start,match_length),match_length,match_node->data); - // On repositionne la zone de non-match juste après la fin du match - si_non_match_start=si_match_start+match_length; +template<typename charT,typename valueT,typename stringT> +inline void emit(int match,const stringT & string,size_t start, size_t stop,valueT value,tst_action<charT,valueT,stringT>* to_perform) { + size_t length = stop-start; + if(length>0) { + to_perform->perform(string.substr(start,length), match * length, value); + } +} - // Annulation du match - ni_best_match=UNDEFINED_INDEX; - // On backtracke - compute_backtrack(n_current,string,si_non_match_start,si_current); - // Le backtrack nous donne là où on se trouve dans le noeud juste après le match... - ni_current = n_current->backtrack; - // ... et là où on avait notre meilleur match - ni_best_match = n_current->backtrack_match_index; - - if(ni_current==root) { - // quand on a un retour à la racine, on n'a aucun match en cours - si_match_start=UNDEFINED_INDEX; - } - else { - // sinon c'est qu'un match est en cours, on va recalculer son point de démarrage - // grâce à la position du noeud - n_current=storage->get(ni_current); - si_match_start=si_current-n_current->position; - } - } - else if(si_match_start!=UNDEFINED_INDEX) { - if(si_current<string.size()) { - // Si on n'est pas en fin de chaîne... - // Si le caractère courant n'est pas accepté, qu'on avait commencé - // un match mais que celui-ci n'avait pas réussi, on va backtracker. - compute_backtrack(n_current,string,si_match_start+1,si_current); - ni_current = n_current->backtrack; - ni_best_match=n_current->backtrack_match_index; - - if(ni_current==root) { - // Quand on a un retour à la racine, on n'a aucun match en cours - si_match_start=UNDEFINED_INDEX; - } - else { - // sinon c'est qu'un match est en cours, on va recalculer son point de démarrage - // grâce à la position du noeud - n_current=storage->get(ni_current); - si_match_start=si_current-n_current->position; - } - } - else { - // Si on est en fin de chaîne, on sort. - break; - } - } - else { - // le caractère courant n'est pas accepté et on n'avait pas de match en cours - if(si_current<string.size()) { - // si on peut avancer d'un caractère on le fait - ++si_current; - // on revient à la racine - ni_current = root; - } - else { - // si on est à la fin de la chaîne on sort de la boucle pour la fin. - break; - } - } +template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> + valueT tst<charT,valueT,storageT,serializerT,stringT>::scan(const stringT & string,tst_action<charT,valueT,stringT>* to_perform) { + // NOTE : yes, this code uses goto. + // It's actually FTW because it simplifies the code instead of + // forcing the abusive use of break, continue, all the more + // that C++ doesn't support labeled continue. + // To make sense of it all, you can have a look at + // the file scan algorithm.graphml + // with yED : http://www.yworks.com/en/products_yed_about.html + // This way you can match nodes from the graph with the code below using the + // labels (A), (B), etc. + + // Current position in the input string + size_t si=0; + + // First string index for a non match + size_t si_nm=0; + + // First string index for a match + int si_ms=UNDEFINED_INDEX; + + // Best match + int si_bme=UNDEFINED_INDEX; + tst_node<charT,valueT> *n_best_match = NULL; + + // Current node + tst_node<charT,valueT> *n_current = storage->get(root); + + // Main loop + MAIN: + { + // + // NON-MATCH state + // + + assert(si_ms == UNDEFINED_INDEX); + + // (A) check input + if(si < string.size()) { + if(find_char(&n_current,string[si])) { + // (B) found + si_ms = si; + ++si; + // this goto is implicit + // goto POTENTIAL_MATCH; + } + else { + // (C) not found + ++si; + goto MAIN; + } + } + else { + // (D) end input + emit(-1,string,si_nm,si,default_value,to_perform); + return to_perform->result(); + } + + POTENTIAL_MATCH: + { + // + // POTENTIAL_MATCH state + // + + assert(si_ms != UNDEFINED_INDEX); + + // (E) check data + if(n_current->data != default_value) { + // (F) store best match + si_bme = si; + n_best_match = n_current; + } + + // (G) move next ? + n_current = storage->get(n_current->next); + if(n_current != NULL) { + + // (H) check input + if(si < string.size()) { + if(find_char(&n_current, string[si])) { + // (L) + ++si; + goto POTENTIAL_MATCH; + } + else { + goto END_MATCH; + } } else { - // on avance tranquillement dans l'arbre... + // (M) end match + if(si_bme!=UNDEFINED_INDEX) { + goto EMIT_AND_LOOP; + } + else { + // (N) + emit(-1,string,si_nm,si,default_value,to_perform); + } + + return to_perform->result(); } - } - // on n'arrive ici que si on est arrivé à la fin de la chaine en entrée - if((si_current - si_non_match_start)>0) { - // charT'il y avait un non-match en cours - // on l'envoie - to_perform->perform(string.substr(si_non_match_start,si_current - si_non_match_start),-static_cast<int>(si_current - si_non_match_start),default_value); - } - return to_perform->result(); -} + } + else END_MATCH: { -template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> - void tst<charT,valueT,storageT,serializerT,stringT>::compute_backtrack(tst_node<charT,valueT> *current_node,const stringT & string, int si_match_start, int si_match_end) { - if(current_node->backtrack==UNDEFINED_INDEX) { - while(si_match_start<si_match_end) { - current_node->backtrack=root; - current_node->backtrack_match_index=UNDEFINED_INDEX; - find_node(&(current_node->backtrack),&(current_node->backtrack_match_index),string.substr(si_match_start,si_match_end-si_match_start)); - if(current_node->backtrack==UNDEFINED_INDEX) { - ++si_match_start; - } - else { - current_node->backtrack=(storage->get(current_node->backtrack))->next; - break; - } + // (I) end match + if(si_bme!=UNDEFINED_INDEX) EMIT_AND_LOOP: { + // (J) emit and loop + emit(-1,string,si_nm,si_ms,default_value,to_perform); + emit(1,string,si_ms,si_bme,n_best_match->data,to_perform); + + si = si_bme; + si_nm = si; + si_ms = UNDEFINED_INDEX; + si_bme = UNDEFINED_INDEX; + n_current = storage->get(root); + goto MAIN; } - if(current_node->backtrack==UNDEFINED_INDEX) { - current_node->backtrack=root; - current_node->backtrack_match_index=UNDEFINED_INDEX; + else { + // (K) backtrack + // TODO : prevent backtrack using tree analysis + si = si_ms + 1; + si_ms = UNDEFINED_INDEX; + si_bme = UNDEFINED_INDEX; + n_current = storage->get(root); + goto MAIN; } - } -} + + } // (I) + } // (E) + + } // MAIN +} template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::scan_with_stop_chars(const stringT & string,const stringT& stop_chars,tst_action<charT,valueT,stringT>* to_perform) const { // Le premier caractère de la chaine ne correspondant pas à un match size_t si_non_match_start=0; // Le noeud pour lequel on a enregistré un match (noeud avec un objet associé) int ni_best_match=UNDEFINED_INDEX; // Le premier caractère de la chaine correspondant à un match int si_match_start=UNDEFINED_INDEX; // La position actuelle dans la chaîne (index) size_t si_current=0; // Le numéro du noeud actuel de l'arbre int ni_current=root; // Le noeud actuel de l'arbre tst_node<charT,valueT> *n_current; // Boucle principale while(1) { n_current=storage->get(ni_current); // On avance dans l'arbre d'un cran if(si_current<string.size()) { int diff = string[si_current]-n_current->c; if(diff>0) { ni_current = n_current->right; } else if(diff<0) { ni_current = n_current->left; } else { // ok, le caractère courant est accepté if(si_match_start==UNDEFINED_INDEX) { // On teste si le début de match est le début de chaine ou après un stop_char if(si_current==0 || stop_chars.find(string[si_current-1])<stop_chars.size()) { // oui, on enregistre le début si_match_start=si_current; } else { // non, on passe à la suite ++si_current; } } if(si_match_start!=UNDEFINED_INDEX) { // si le démarrage a bien pris if(n_current->data!=default_value && (si_current==(string.size()-1) || stop_chars.find(string[si_current+1])<stop_chars.size())) { // on a une donnée dans le noeud courant // et on est en fin de chaîne ou le caractère précédent est un stop_char ni_best_match = ni_current; } ++si_current; if(si_current<string.size()) { // Si on peut avancer, on avance ni_current = n_current->next; } else { // Fin de chaine ==> pas de match possible ni_current = UNDEFINED_INDEX; } } } } else { // On est toujours en fin de chaine ==> pas de match possible ni_current = UNDEFINED_INDEX; } if(ni_current==UNDEFINED_INDEX) { // Le caractère courant n'est pas accepté if(ni_best_match!=UNDEFINED_INDEX) { // Si on a un match réussi en cours // Si le match en cours démarre après la zone de non-match // C'est qu'on a bien une zone de non-match int non_match_length = si_match_start-si_non_match_start; if(non_match_length>0) { // On l'envoie. to_perform->perform(string.substr(si_non_match_start,non_match_length),-non_match_length,default_value); } // On envoie maintenant le match // On connait sa longueur grâce à la position dans l'arbre // TODO: voir si on ne pourrait pas de passer de ça tst_node<charT,valueT> *match_node=storage->get(ni_best_match); int match_length = match_node->position+1; // On envoie le match to_perform->perform(string.substr(si_match_start,match_length),match_length,match_node->data); // On repositionne la zone de non-match juste après la fin du match si_non_match_start=si_match_start+match_length; // Annulation du match ni_best_match=UNDEFINED_INDEX; // On backtracke // backtrack de naze parce qu'on ne peut pas utiliser // les infos de backtrack à cause des séparateurs. si_current = si_non_match_start; ni_current = root; ni_best_match=UNDEFINED_INDEX; si_match_start=UNDEFINED_INDEX; } else if(si_match_start!=UNDEFINED_INDEX) { // Si le caractère courant n'est pas accepté, qu'on avait commencé // un match mais que celui-ci n'avait pas réussi, on va backtracker. // backtrack de naze parce qu'on ne peut pas utiliser // les infos de backtrack à cause des séparateurs. si_current=si_match_start+1; ni_current = root; ni_best_match=UNDEFINED_INDEX; si_match_start=UNDEFINED_INDEX; } else { // le caractère courant n'est pas accepté et on n'avait pas de match en cours if(si_current<string.size()) { // si on peut avancer d'un caractère on le fait ++si_current; // on revient à la racine ni_current = root; } else { // si on est à la fin de la chaîne on sort de la boucle pour la fin. break; } } } else { // on avance tranquillement dans l'arbre... } } // on n'arrive ici que si on est arrivé à la fin de la chaine en entrée if((si_current - si_non_match_start)>0) { // charT'il y avait un non-match en cours // on l'envoie to_perform->perform(string.substr(si_non_match_start,si_current - si_non_match_start),-static_cast<int>(si_current - si_non_match_start),default_value); } return to_perform->result(); } #endif /**************************** file I/O *************************************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::read(std::istream& file) { // We check the version number int version_length; file.read((char*)(&version_length),sizeof(size_t)); char* version=(char*)tst_malloc(version_length+1); version[version_length]=0; assert(version); file.read(version,version_length); if(strcmp(TST_VERSION,version)!=0) { tst_free(version); throw TSTException("Invalid version number"); } else { tst_free(version); } serializerT reader; default_value = reader.read(file); // On efface le stockage storage->erase(); if(file.get()) { root = read_node(file,&reader,0); } else { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> int tst<charT,valueT,storageT,serializerT,stringT>::read_node(std::istream& file,serializerT* reader,int depth) { char bitmask = file.get(); node_info<charT,valueT> node_info; storage->new_node(&node_info); file.read((char*)(&(node_info.node->c)),sizeof(charT)); if(bitmask & 16) { node_info.node->store(reader->read(file)); } else { node_info.node->store(default_value); } #ifdef SCANNER // TODO : inutile, peut être recalculé ? file.read((char*)(&(node_info.node->position)),sizeof(int)); file.read((char*)(&(node_info.node->backtrack)),sizeof(int)); file.read((char*)(&(node_info.node->backtrack_match_index)),sizeof(int)); #endif int other_index; if(bitmask & 1) { // En deux étapes car le noeud peut bouger physiquement. // Normalement tout se passe bien mais c'est plus rassurant ainsi. other_index = read_node(file,reader,depth+1); storage->get(node_info.index)->next = other_index; } else { storage->get(node_info.index)->next = UNDEFINED_INDEX; } if(bitmask & 2) { other_index = read_node(file,reader,depth+1); storage->get(node_info.index)->left = other_index; } else { storage->get(node_info.index)->left = UNDEFINED_INDEX; } if(bitmask & 4) { other_index = read_node(file,reader,depth+1); storage->get(node_info.index)->right = other_index; } else { storage->get(node_info.index)->right = UNDEFINED_INDEX; } return node_info.index; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::write(std::ostream& file) const { // We save the version number size_t version_length = strlen(TST_VERSION); file.write((char*)(&version_length),sizeof(size_t)); file.write(TST_VERSION,(std::streamsize)version_length); serializerT writer; writer.write(file,default_value); if(root!=UNDEFINED_INDEX) { file.put(1); write_node(file,&writer,root); } else { file.put(0); } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::write_node(std::ostream& file,serializerT* writer,int index) const { tst_node<charT,valueT>* node = storage->get(index); char bitmask=0; if(node->next!=UNDEFINED_INDEX) bitmask |= 1; if(node->left!=UNDEFINED_INDEX) bitmask |= 2; if(node->right!=UNDEFINED_INDEX) bitmask |= 4; if(node->data!=default_value) bitmask |=16; file.put(bitmask); file.write((char*)(&(node->c)),sizeof(charT)); if(bitmask & 16) { writer->write(file,node->data); } #ifdef SCANNER file.write((char*)(&(node->position)),sizeof(int)); file.write((char*)(&(node->backtrack)),sizeof(int)); file.write((char*)(&(node->backtrack_match_index)),sizeof(int)); #endif if(bitmask & 1) write_node(file,writer,node->next); if(bitmask & 2) write_node(file,writer,node->left); if(bitmask & 4) write_node(file,writer,node->right); } #endif diff --git a/python/pythonTST.vcproj b/python/pythonTST.vcproj index d2a02e6..bfd5fd1 100644 --- a/python/pythonTST.vcproj +++ b/python/pythonTST.vcproj @@ -1,457 +1,457 @@ <?xml version="1.0" encoding="Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="9,00" Name="pythonTST" ProjectGUID="{A5208316-015E-4611-B812-6E2F7CCD33A2}" RootNamespace="pythonTST" Keyword="Win32Proj" TargetFrameworkVersion="131072" > <Platforms> <Platform Name="Win32" /> </Platforms> <ToolFiles> </ToolFiles> <Configurations> <Configuration Name="Debug|Win32" OutputDirectory="Debug" IntermediateDirectory="Debug" ConfigurationType="2" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" UseOfMFC="0" CharacterSet="2" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="D:\projets\python-svn\PC;D:\projets\python-svn\Include;..\include" PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS;SCANNER" MinimalRebuild="false" BasicRuntimeChecks="3" RuntimeLibrary="1" BufferSecurityCheck="true" RuntimeTypeInfo="true" UsePrecompiledHeader="0" DebugInformationFormat="3" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/_tst_d.pyd" LinkIncremental="1" AdditionalLibraryDirectories="&quot;D:\projets\python-svn\PCbuild&quot;" GenerateDebugInformation="true" ProgramDatabaseFile="$(OutDir)/_tst_d.pdb" GenerateMapFile="true" MapExports="true" SubSystem="2" RandomizedBaseAddress="1" DataExecutionPrevention="0" ImportLibrary="$(OutDir)/pyd.lib" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> <Configuration Name="Release|Win32" OutputDirectory="Release" IntermediateDirectory="Release" ConfigurationType="2" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" CharacterSet="2" WholeProgramOptimization="1" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="3" InlineFunctionExpansion="2" EnableIntrinsicFunctions="true" FavorSizeOrSpeed="1" AdditionalIncludeDirectories="E:\Python24\include;..\include" PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" RuntimeLibrary="0" StructMemberAlignment="1" UsePrecompiledHeader="0" WarningLevel="3" Detect64BitPortabilityProblems="true" DebugInformationFormat="3" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/_tst.pyd" LinkIncremental="1" AdditionalLibraryDirectories="E:\Python24\libs" GenerateDebugInformation="true" SubSystem="2" OptimizeReferences="2" EnableCOMDATFolding="2" RandomizedBaseAddress="1" DataExecutionPrevention="0" ImportLibrary="$(OutDir)/pyd.lib" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> <Configuration Name="Debug CRM|Win32" OutputDirectory="$(ConfigurationName)" IntermediateDirectory="$(ConfigurationName)" ConfigurationType="2" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" UseOfMFC="0" CharacterSet="2" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" CommandLine="" AdditionalDependencies="" Outputs="" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="&quot;E:\projets\Python-2.6.4\include&quot;;&quot;E:\projets\Python-2.6.4\PC&quot;;..\include" PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" MinimalRebuild="false" BasicRuntimeChecks="3" RuntimeLibrary="1" BufferSecurityCheck="true" RuntimeTypeInfo="true" UsePrecompiledHeader="0" DebugInformationFormat="3" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/_tst_d.pyd" LinkIncremental="1" AdditionalLibraryDirectories="&quot;E:\projets\Python-2.6.4\PCbuild&quot;" GenerateDebugInformation="true" ProgramDatabaseFile="$(OutDir)/_tst_d.pdb" GenerateMapFile="true" MapExports="true" SubSystem="2" RandomizedBaseAddress="1" DataExecutionPrevention="0" ImportLibrary="$(OutDir)/pyd.lib" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> <Configuration Name="Release CRM|Win32" OutputDirectory="$(ConfigurationName)" IntermediateDirectory="$(ConfigurationName)" ConfigurationType="2" InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" CharacterSet="2" WholeProgramOptimization="1" > <Tool Name="VCPreBuildEventTool" /> <Tool Name="VCCustomBuildTool" /> <Tool Name="VCXMLDataGeneratorTool" /> <Tool Name="VCWebServiceProxyGeneratorTool" /> <Tool Name="VCMIDLTool" /> <Tool Name="VCCLCompilerTool" Optimization="3" InlineFunctionExpansion="2" EnableIntrinsicFunctions="true" FavorSizeOrSpeed="1" AdditionalIncludeDirectories="C:\Python24\include;..\include" PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" RuntimeLibrary="0" StructMemberAlignment="1" UsePrecompiledHeader="0" WarningLevel="3" Detect64BitPortabilityProblems="true" DebugInformationFormat="3" /> <Tool Name="VCManagedResourceCompilerTool" /> <Tool Name="VCResourceCompilerTool" /> <Tool Name="VCPreLinkEventTool" /> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/_tst.pyd" LinkIncremental="1" AdditionalLibraryDirectories="C:\Python24\libs" GenerateDebugInformation="true" SubSystem="2" OptimizeReferences="2" EnableCOMDATFolding="2" RandomizedBaseAddress="1" DataExecutionPrevention="0" ImportLibrary="$(OutDir)/pyd.lib" TargetMachine="1" /> <Tool Name="VCALinkTool" /> <Tool Name="VCManifestTool" /> <Tool Name="VCXDCMakeTool" /> <Tool Name="VCBscMakeTool" /> <Tool Name="VCFxCopTool" /> <Tool Name="VCAppVerifierTool" /> <Tool Name="VCPostBuildEventTool" /> </Configuration> </Configurations> <References> </References> <Files> <Filter Name="Source Files" Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" > <File RelativePath=".\bug.py" > </File> - <File - RelativePath=".\setup.py" - > - </File> <File RelativePath=".\tst.i" > <FileConfiguration Name="Debug|Win32" > <Tool Name="VCCustomBuildTool" CommandLine="E:\swigwin-1.3.40\swig -c++ -O -DSCANNER -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" AdditionalDependencies="..\include\tst.h;pythonTST.h" Outputs="tst_wrap.cxx" /> </FileConfiguration> <FileConfiguration Name="Release|Win32" > <Tool Name="VCCustomBuildTool" CommandLine="E:\swigwin-1.3.40\swig -O -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" AdditionalDependencies="..\tst.h;pythonTST.h" Outputs="tst_wrap.cxx" /> </FileConfiguration> <FileConfiguration Name="Debug CRM|Win32" > <Tool Name="VCCustomBuildTool" CommandLine="E:\swigwin-1.3.40\swig -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" AdditionalDependencies="..\include\tst.h;pythonTST.h" Outputs="tst_wrap.cxx" /> </FileConfiguration> <FileConfiguration Name="Release CRM|Win32" > <Tool Name="VCCustomBuildTool" CommandLine="E:\swigwin-1.3.40\swig -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" AdditionalDependencies="..\tst.h;pythonTST.h" Outputs="tst_wrap.cxx" /> </FileConfiguration> </File> <File RelativePath=".\tst.py" > </File> <File RelativePath=".\tst_wrap.cxx" > </File> </Filter> <Filter Name="Header Files" Filter="h;hpp;hxx;hm;inl;inc;xsd" UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" > <File RelativePath="..\include\debug.h" > </File> + <File + RelativePath="..\include\fundamentals.h" + > + </File> <File RelativePath=".\PythonReference.h" > </File> <File RelativePath=".\pythonTST.h" > </File> <File RelativePath="..\include\tst.h" > </File> </Filter> <Filter Name="Resource Files" Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx" UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}" > </Filter> </Files> <Globals> </Globals> </VisualStudioProject> diff --git a/python/test/test.py b/python/test/test.py index 6c9bdeb..95f9c6f 100644 --- a/python/test/test.py +++ b/python/test/test.py @@ -86,692 +86,732 @@ class TestRefCount(unittest.TestCase): self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) def testOverwrite(self): self.tree[self.a]=self.a a2 = self.tree.put(self.a,'coucou') self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) del(a2) self.assertEqual(sys.getrefcount(self.a),self.rc_a) def testWalkList(self): l=self.tree.walk(None,ListAction()) self.assertEqual(sys.getrefcount(self.a),self.rc_a) self.tree[self.a]=self.a self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) l=self.tree.walk(None,ListAction()) self.assertEqual(sys.getrefcount(self.a),self.rc_a+2) del(l) self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) def testWalkDict(self): self.tree[self.a]=self.a self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) d=self.tree.walk(None,DictAction()) self.assertEqual(sys.getrefcount(self.a),self.rc_a+2) del(d) self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) del self.tree[self.a] self.assertEqual(sys.getrefcount(self.a),self.rc_a) def testRemove(self): del(self.tree) self.assertEqual(sys.getrefcount(None),self.rc_None) self.assertEqual(sys.getrefcount(self.a),self.rc_a) class TestCollectors(unittest.TestCase): def setUp(self): self.tree = TST() self.keys = dict( a = 1, ab = 2, abc = 3, b = 4 ) for k,v in self.keys.iteritems(): self.tree[k] = v def testListAction(self): l = self.tree.walk(None,ListAction()) self.assertEqual(l,[1,2,3,4]) def testTupleListAction(self): l = self.tree.walk(None,TupleListAction()) self.assertEqual(l,[('a',0,1),('ab',0,2),('abc',0,3),('b',0,4)]) def testDictAction(self): l = self.tree.walk(None,DictAction()) self.assertEqual(l,dict(a=(0,1),ab=(0,2),abc=(0,3),b=(0,4))) def skey(): format = '%%.%if'%random.randint(1,10) return format%random.random() class TestBasics(unittest.TestCase): def setUp(self): self.tree = TST() self.keys = dict([ (skey(),random.random()) for x in xrange(250) ]) for k,v in self.keys.iteritems(): self.tree[k] = v def testGet(self): for k,v in self.keys.iteritems(): self.assertEqual(self.tree[k],v) def testWithRemove(self): for k in random.sample(self.keys,len(self.keys)/8): del self.keys[k] del self.tree[k] self.tree.pack() self.testGet() def testWithUpdate(self): for k in random.sample(self.keys,len(self.keys)/8): v = self.keys[k] nv = random.random() self.keys[k] = nv self.assertEqual(self.tree.put(k,nv),v) self.testGet() def testWalk(self): timer_start("walk") for i in xrange(100): d = self.tree.walk(None,DictAction()) timer_end("walk") for k,v in d.iteritems(): self.assertEquals(self.tree[k],v[1]) def testWalkWithRoot(self): ref = self.tree.walk(None,DictAction()) timer_start("walk_root") for i in xrange(100): d = self.tree.walk(None,DictAction(),'0.1') timer_end("walk_root") for k, v in ref.iteritems(): if k.startswith('0.1'): self.assert_(k in d) self.assertEquals(v,d[k]) for k, v in d.iteritems(): self.assert_(k.startswith('0.1')) self.assertEquals(self.tree[k],v[1]) def testCloseMatch(self): for k1 in self.keys.iterkeys(): timer_start("close_match") d = self.tree.close_match(k1,4,None,DictAction()) timer_end("close_match") for k2 in self.keys.iterkeys(): distance = levenshtein(k1,k2) if distance<=4: self.assert_(k2 in d,"Match manquant pour %s : %s (distance = %i)"%( k1, k2, distance, )) self.assert_(k2 in d and d[k2][0]==distance,"Mauvaise distance pour %s et %s : %i != %s"%( k1, k2, distance, d.get(k2)[0] )) else: self.assert_(k2 not in d,"Mauvaise distance pour %s et %s : %i > 4 mais trouvé %s"%( k1, k2, distance, d.get(k2) )) def testPrefixMatch(self): for k1 in self.keys.iterkeys(): timer_start("prefix_match") d = self.tree.prefix_match(k1[:len(k1)/2],None,DictAction()) timer_end("prefix_match") self.assert_(k1 in d,"Une cle manque dans un prefix_match pour %s"%(k1,)) k2 = k1 + k1 timer_start("prefix_match") d = self.tree.prefix_match(k2,None,DictAction()) timer_end("prefix_match") self.assert_(k2 not in d,"Une cle manque dans un prefix_match pour %s"%(k1,)) def testWriteRead(self): self.tree.write_to_file('test.tst') self.tree = TST() self.tree.read_from_file('test.tst') self.testGet() class TestMatch(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['abc'] = 'abc' self.tree['ab'] = 'ab' self.tree['a'] = 'a' self.tree['bbc'] = 'bbc' self.tree['efgfjhny'] = 'ok' def testJoker1(self): d = self.tree.match("a?c",None,DictAction()) self.assertEquals(d,dict(abc=(0,"abc"))) def testJoker2(self): d = self.tree.match("???",None,DictAction()) self.assertEquals(d,{'abc': (0, 'abc'), 'bbc': (0, 'bbc')}) def testJoker3(self): d = self.tree.match("??",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab')}) def testStar1(self): d = self.tree.match("a*c",None,DictAction()) self.assertEquals(d,dict(abc=(0,"abc"))) def testStar2(self): d = self.tree.match("a*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'abc': (0, 'abc')}) def testStar2_1(self): d = self.tree.match("ab*",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab'), 'abc': (0, 'abc')}) def testStar2_2(self): d = self.tree.match("*b",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab')}) d = self.tree.match("*bbc",None,DictAction()) self.assertEquals(d,{'bbc': (0, 'bbc')}) def testStar3(self): d = self.tree.match("*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) d = self.tree.match("*?*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) def testStar3_1(self): d = self.tree.match("**",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) d = self.tree.match("***",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) def testStar4(self): d = self.tree.match("e*ny",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar5(self): d = self.tree.match("*****y",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar6(self): d = self.tree.match("????*",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar7(self): d = self.tree.match("ef?f*n?",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) class TestIterators(unittest.TestCase): def setUp(self): self.tree = TST() self.keys = dict( titi = 1, toto = 2, tati = 3, a = 5 ) for k, v in self.keys.iteritems(): self.tree[k] = v def testLexical1(self): d = {} for k, v in self.tree: d[k] = v self.assertEqual(d,self.keys) def testLexical2(self): d = {} for k, v in self.tree.iterator('t'): d[k] = v self.keys.pop('a') self.assertEqual(d,self.keys) def testCloseMatch(self): d = {} for k, v in self.tree.close_match_iterator('t',1): d[k] = v self.assertEqual(d,dict( a = 5 )) d = {} for k, v in self.tree.close_match_iterator('tito',1): d[k] = v self.assertEqual(d,dict( titi = 1, toto = 2 )) d = {} for k, v in self.tree.close_match_iterator('tuto',1): d[k] = v self.assertEqual(d,dict( toto = 2 )) class TestCallableAction(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['foo'] = 'bar' def testCA1(self): res = {} def callback(key, length, obj): res[key] = obj def result(): res['hello'] = 'world' return res self.assertEqual( self.tree.walk(None, CallableAction(callback, result)), {'foo':'bar', 'hello':'world'} ) def testCA2(self): res = {} def callback(key, length, obj): # Provoke an exception print 0 / 0 res[key] = obj def result(): return res try: self.tree.walk(None, CallableAction(callback, result)), self.fail("Should have raised an exception") except ZeroDivisionError: pass def testCA3(self): res = {} def callback(key, length, obj): res[key] = obj def result(): # Provoke an exception return 0/0 try: self.tree.walk(None, CallableAction(callback, result)), self.fail("Should have raised an exception") except ZeroDivisionError: pass class TestCallableFilter(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['foo'] = 'bar' self.tree['bar'] = 'foo' def testCF1(self): res = {} def cfilter(key, length, obj): res[key] = obj return obj self.tree.walk(CallableFilter(cfilter),None) self.assertEqual( res, {'foo':'bar', 'bar':'foo'} ) def testCF2(self): def cfilter(key, length, obj): if key=='foo': return 'boo' else: return obj self.assertEqual( self.tree.walk(CallableFilter(cfilter),DictAction()), {'foo':(0,'boo'),'bar':(0,'foo')} ) def testCF3(self): def cfilter(key, length, obj): if key=='foo': # raises an exception return 0 / 0 else: return obj try: self.tree.walk(CallableFilter(cfilter),DictAction()), self.fail("Should have raised an exception") except ZeroDivisionError: pass class TestHighCapacity(unittest.TestCase): def setUp(self): tree = TST() timer_start('build_big') keys = map(str,xrange(100000)) random.shuffle(keys) timer_end('build_big') timer_start('write_big') for k in keys: tree[k] = k timer_end('write_big') self.keys, self.tree = keys, tree def testGet(self): timer_start('read_big') for k in self.keys: self.assertEqual(self.tree[k],k) timer_end('read_big') def testFullPack(self): timer_start('delete_full') for k in self.keys: del self.tree[k] timer_end('delete_full') self.tree.pack() for k in self.keys: self.assertEqual(self.tree[k],None) sample = random.sample(self.keys,len(self.keys)/10) random.shuffle(sample) timer_start('refill_post_pack/10') for k in sample: self.tree[k] = k timer_end('refill_post_pack/10',10) for k in sample: self.assertEqual(self.tree[k],k) del self.tree[k] self.tree.pack() for k in self.keys: self.assertEqual(self.tree[k],None) self.tree.write_to_file('test.tst') def testDelete(self): sample = random.sample(self.keys,len(self.keys)/10) random.shuffle(sample) timer_start('delete_big/10') for k in sample: del self.tree[k] timer_end('delete_big/10',10) random.shuffle(sample) timer_start('refill_pre_pack/10') for k in sample: self.tree[k] = k timer_end('refill_pre_pack/10',10) self.testGet() random.shuffle(sample) timer_start('delete_big/10') for k in sample: del self.tree[k] timer_end('delete_big/10',10) self.tree.pack() random.shuffle(sample) timer_start('refill_post_pack/10') for k in sample: self.tree[k] = k timer_end('refill_post_pack/10',10) self.testGet() timer_start('delete_big/10') for k in self.keys[:len(self.keys)/10]: del self.tree[k] timer_end('delete_big/10',10) timer_start('pack/10') self.tree.pack() timer_end('pack/10',10) timer_start('check_delete_big') for k in self.keys[:len(self.keys)/10]: self.assertEqual(self.tree[k],None) for k in self.keys[len(self.keys)/10+1:]: self.assertEqual(self.tree[k],k) timer_end('check_delete_big') def testUpdate(self): timer_start('build_big/10') old_keys = self.keys[:len(self.keys)/10] new_keys = map(lambda x:str(int(x) + 1),old_keys) timer_end('build_big/10',10) timer_start('update_big/10') for k,kp in izip(old_keys,new_keys): self.assertEqual(self.tree.put(k,kp),k) timer_end('update_big/10',10) timer_start('check_update_big') for k,kp in izip(old_keys,new_keys): self.assertEqual(self.tree[k],kp) timer_end('check_update_big') class TestScan(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['Nicolas']='Nicolas' self.tree['olaf']='olaf' self.tree['lazlo']='lazlo' self.tree['Nicolas-Antoinette']='Nicolas-Antoinette' self.tree['Antoinette']='Antoinette' self.tree['Antoine']='Antoine' self.tree['astride']='astride' self.tree['VICTOIRE']='VICTOIRE' self.tree['IAN']='IAN' self.tree['x']='x' self.tree['V']='V' self.tree['ROBERT']='ROBERT' self.tree['A N']='A N' self.tree['olaaf']='olaaf' self.tree['laslo']='laslo' def testScanMikeThornton(self): t = TST() t['ccc'] = 1 self.assertEqual(t.scan('cc',TupleListAction()),[('cc',-2,None)]) self.assertEqual(t.scan('ccd',TupleListAction()),[('ccd',-3,None)]) - - def testScanKeithDavidson1(self): - t = TST() - t['333'] = 'ccc' - # self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) - self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) - - def testScanKeithDavidson2(self): - t = TST() - t['333'] = 'ccc' - self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) - self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) - - - def testScanKeithDavidson3(self): - t = TST() - t['333'] = 'ccc' - self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) - self.assertEqual(t.scan('.3.',TupleListAction()),[('.3.',-3,None)]) - self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) - self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) - self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) - - def testScanKeithDavidson4(self): - t = TST() - t['3333'] = 'ccc' - # self.assertEqual(t.scan('.333.',TupleListAction()),[('.333.',-5,None)]) - self.assertEqual(t.scan('.333333.',TupleListAction()),[('.',-1,None),('3333',4,'ccc'),('33.',-3,None)]) - - def testScanKeithDavidson5(self): - t = TST() - t['3333'] = 'ccc' - self.assertEqual(t.scan('.333.',TupleListAction()),[('.333.',-5,None)]) - self.assertEqual(t.scan('.333333.',TupleListAction()),[('.',-1,None),('3333',4,'ccc'),('33.',-3,None)]) - - def testScanKeithDavidson6(self): - t = TST() - t['333'] = 'ccc' - self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) - self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('333',3,'ccc'),('.',-1,None)]) - - def testScanKeithDavidson7(self): - t = TST() - t['333'] = 'ccc' - self.assertEqual(t.scan('.3.',TupleListAction()),[('.3.',-3,None)]) - self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) - self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) def testScan0_1(self): self.assertEqual(self.tree.scan('Nicolas',TupleListAction()),[('Nicolas', 7, 'Nicolas'),]) def testScan0_2(self): self.assertEqual(self.tree.scan(' Nicolas',TupleListAction()),[(' ',-1,None),('Nicolas', 7, 'Nicolas'),]) def testScan0_3(self): self.assertEqual(self.tree.scan('Nicolas ',TupleListAction()),[('Nicolas', 7, 'Nicolas'),(' ',-1,None),]) def testScan0_4(self): self.assertEqual(self.tree.scan(' Nicolas ',TupleListAction()),[(' ',-1,None),('Nicolas', 7, 'Nicolas'),(' ',-1,None),]) def testScan0_5(self): self.assertEqual(self.tree.scan(' ',TupleListAction()),[(' ',-1,None),]) def testScan0_6(self): self.assertEqual(self.tree.scan('la',TupleListAction()),[('la', -2, None)]) def testScan0_7(self): self.assertEqual(self.tree.scan('lazl',TupleListAction()),[('lazl', -4, None)]) def testScan1(self): timer_start("scan") for i in xrange(10000): self.assertEqual(self.tree.scan('lazlo',TupleListAction()),[('lazlo', 5, 'lazlo')]) self.assertEqual(self.tree.scan('Nicolazlo',TupleListAction()),[('Nico', -4, None), ('lazlo', 5, 'lazlo')]) timer_end("scan") def testScan24(self): self.assertEqual(self.tree.scan('A NicoNicoNicolasNicoNico',TupleListAction()),[('A N', 3, 'A N'), ('icoNico', -7, None), ('Nicolas', 7, 'Nicolas'), ('NicoNico', -8, None)]) def testScan1_1(self): self.assertEqual(self.tree.scan('hippocampe',TupleListAction()),[('hippocampe', -10, None)]) def testScan2(self): self.assertEqual(self.tree.scan('NicolaNicolaNicolaNicolaNicola',TupleListAction()),[('NicolaNicolaNicolaNicolaNicola', -30, None)]) def testScan3(self): self.assertEqual(self.tree.scan('Nicolasstupide',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('stupide', -7, None)]) def testScan4(self): self.assertEqual(self.tree.scan('Nicolast',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('t', -1, None)]) def testScan5(self): self.assertEqual(self.tree.scan('xxxNicolas',TupleListAction()),[('x', 1, 'x'), ('x', 1, 'x'), ('x', 1, 'x'), ('Nicolas', 7, 'Nicolas')]) def testScan6(self): self.assertEqual(self.tree.scan('xxx Nicolas',TupleListAction()),[('x', 1, 'x'), ('x', 1, 'x'), ('x', 1, 'x'), (' ', -1, None), ('Nicolas', 7, 'Nicolas')]) def testScan7(self): self.assertEqual(self.tree.scan('Antoinette Antoinette',TupleListAction()),[('Antoinette', 10, 'Antoinette'), (' ', -1, None), ('Antoinette', 10, 'Antoinette')]) def testScan8(self): self.assertEqual(self.tree.scan('Nicolas-Antoinette',TupleListAction()),[('Nicolas-Antoinette', 18, 'Nicolas-Antoinette')]) def testScan9(self): self.assertEqual(self.tree.scan('Nicolas-Antoine',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) def testScan9_1(self): self.assertEqual(self.tree.scan('Nicolas-Antoine-Antoine',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) def testScan9_2(self): self.assertEqual(self.tree.scan('Nicolas-Antoine-Antoine-',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None)]) def testScan10(self): self.assertEqual(self.tree.scan('Nicolas-Antoinet',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('t', -1, None)]) def testScanWithStopChars1(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolas',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas')]) def testScanWithStopChars2(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolasstupide',' -',TupleListAction()),[('Nicolasstupide', -14, None)]) def testScanWithStopChars25(self): timer_start("scan_stop_chars") for i in xrange(10000): self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) timer_end("scan_stop_chars") def testScanWithStopChars3(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolast',' -',TupleListAction()),[('Nicolast', -8, None)]) def testScanWithStopChars4(self): self.assertEqual(self.tree.scan_with_stop_chars('xxxNicolas',' -',TupleListAction()),[('xxxNicolas', -10, None)]) def testScanWithStopChars5(self): self.assertEqual(self.tree.scan_with_stop_chars('xxx Nicolas',' -',TupleListAction()),[('xxx ', -4, None),('Nicolas', 7, 'Nicolas')]) def testScanWithStopChars6(self): self.assertEqual(self.tree.scan_with_stop_chars('xxxAntoine Nicolas',' -',TupleListAction()),[('xxxAntoine ', -11, None),('Nicolas', 7, 'Nicolas')]) def testScanWithStopChars8(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoinette',' -',TupleListAction()),[('Nicolas-Antoinette', 18, 'Nicolas-Antoinette')]) def testScanWithStopChars9(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoine',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) def testScanWithStopChars10(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoinet',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-Antoinet', -9, None)]) def testScanVicieux(self): self.assertEqual(self.tree.scan_with_stop_chars('xxxAntoine A Nicolas',' -',TupleListAction()),[('xxxAntoine A ', -13, None),('Nicolas', 7, 'Nicolas')]) def testScanVicieux2(self): self.assertEqual(self.tree.scan_with_stop_chars('Antoinette Antoinette',' -',TupleListAction()),[('Antoinette', 10, 'Antoinette'), (' ', -1, None), ('Antoinette', 10, 'Antoinette')]) def testScanVicieux3(self): self.assertEqual(self.tree.scan_with_stop_chars('nastride lazlo',' -',TupleListAction()),[('nastride ', -9, None), ('lazlo', 5, 'lazlo')]) self.assertEqual(self.tree.scan_with_stop_chars('VIAN ROBERT',' -',TupleListAction()),[('VIAN ', -5, None), ('ROBERT', 6, 'ROBERT')]) + def testScanKeithDavidson1(self): + t = TST() + t['333'] = 'ccc' + # self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) + self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) + + def testScanKeithDavidson2(self): + t = TST() + t['333'] = 'ccc' + self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) + self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) + + def testScanKeithDavidson2_1(self): + t = TST() + t['333'] = 'ccc' + self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) + self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) + + def testScanKeithDavidson3(self): + t = TST() + t['333'] = 'ccc' + self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) + self.assertEqual(t.scan('.3.',TupleListAction()),[('.3.',-3,None)]) + self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) + self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) + self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) + + def testScanKeithDavidson4(self): + t = TST() + t['3333'] = 'ccc' + # self.assertEqual(t.scan('.333.',TupleListAction()),[('.333.',-5,None)]) + self.assertEqual(t.scan('.333333.',TupleListAction()),[('.',-1,None),('3333',4,'ccc'),('33.',-3,None)]) + + def testScanKeithDavidson5(self): + t = TST() + t['3333'] = 'ccc' + self.assertEqual(t.scan('.333.',TupleListAction()),[('.333.',-5,None)]) + self.assertEqual(t.scan('.333333.',TupleListAction()),[('.',-1,None),('3333',4,'ccc'),('33.',-3,None)]) + + def testScanKeithDavidson6(self): + t = TST() + t['333'] = 'ccc' + self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) + self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) + + def testScanKeithDavidson7(self): + t = TST() + t['333'] = 'ccc' + self.assertEqual(t.scan('.3.',TupleListAction()),[('.3.',-3,None)]) + self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) + self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) + +class TestNewScan(unittest.TestCase): + def setUp(self): + self.tree = TST() + self.tree['333'] = 'A' + self.tree['334'] = 'B' + self.tree['3333'] = 'C' + self.tree['33378'] = 'D' + + def testA(self): + self.assertEqual(self.tree.scan('3',TupleListAction()),[('3',-1,None)]) + self.assertEqual(self.tree.scan('33',TupleListAction()),[('33',-2,None)]) + self.assertEqual(self.tree.scan('3333',TupleListAction()),[('3333',4,'C')]) + + def testB(self): + self.assertEqual(self.tree.scan('',TupleListAction()),[]) + self.assertEqual(self.tree.scan('coucou',TupleListAction()),[('coucou',-6,None)]) + + def testC(self): + self.assertEqual(self.tree.scan('3337',TupleListAction()),[('333',3,'A'),('7',-1,None)]) + self.assertEqual(self.tree.scan('23337',TupleListAction()),[('2',-1,None),('333',3,'A'),('7',-1,None)]) + + def testD(self): + self.assertEqual(self.tree.scan('333',TupleListAction()),[('333',3,'A')]) + self.assertEqual(self.tree.scan('3333',TupleListAction()),[('3333',4,'C')]) + self.assertEqual(self.tree.scan('33378',TupleListAction()),[('33378',5,'D')]) + self.assertEqual(self.tree.scan('0333',TupleListAction()),[('0',-1,None),('333',3,'A')]) + self.assertEqual(self.tree.scan('335333',TupleListAction()),[('335',-3,None),('333',3,'A')]) + + def testE(self): + self.assertEqual(self.tree.scan('34',TupleListAction()),[('34',-2,None)]) + self.assertEqual(self.tree.scan('335',TupleListAction()),[('335',-3,None)]) + self.assertEqual(self.tree.scan('2335',TupleListAction()),[('2335',-4,None)]) + self.assertEqual(self.tree.scan('33332335',TupleListAction()),[('3333',4,'C'),('2335',-4,None)]) + if __name__ == '__main__': print "Testing pytst %s"%TST_VERSION comment = ' '.join(sys.argv[1:]) suite = unittest.TestSuite(( unittest.makeSuite(TestCollectors), unittest.makeSuite(TestBasics), unittest.makeSuite(TestHighCapacity), unittest.makeSuite(TestScan), + unittest.makeSuite(TestNewScan), unittest.makeSuite(TestIterators), unittest.makeSuite(TestMatch), unittest.makeSuite(TestCallableAction), unittest.makeSuite(TestCallableFilter), - )) + )) for i in xrange(3): unittest.TextTestRunner().run(suite) print_timers(comment) diff --git a/scan algorithm.graphml b/scan algorithm.graphml index 6c963cf..a03fad3 100644 --- a/scan algorithm.graphml +++ b/scan algorithm.graphml @@ -1,571 +1,553 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd"> <!--Created by yFiles for Java 2.7--> <key for="graphml" id="d0" yfiles.type="resources"/> <key attr.name="url" attr.type="string" for="node" id="d1"/> <key attr.name="description" attr.type="string" for="node" id="d2"/> <key for="node" id="d3" yfiles.type="nodegraphics"/> <key attr.name="url" attr.type="string" for="edge" id="d4"/> <key attr.name="description" attr.type="string" for="edge" id="d5"/> <key for="edge" id="d6" yfiles.type="edgegraphics"/> <graph edgedefault="directed" id="G"> <node id="n0"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="112.20703125" width="70.001953125" x="463.11688058035713" y="0.0"/> + <y:Geometry height="132.20703125" width="90.001953125" x="381.1379123263889" y="0.0"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="92.20703125" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="50.001953125" x="10.0" y="10.0">START : + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="92.20703125" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="50.001953125" x="20.0" y="20.0">START : NM = 0 MS = -1 BM = -1 n = root i = 0</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n1"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="84.703125" x="466.3539930555556" y="172.20703125"/> + <y:Geometry height="73.40234375" width="104.703125" x="386.8750248015873" y="192.20703125"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.703125" x="10.0" y="15.6494140625">check input</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.703125" x="20.0" y="20.0">(A) +check input</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n2"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="50.0" x="571.0428571428571" y="307.609375"/> + <y:Geometry height="73.40234375" width="60.681640625" x="511.5635447668651" y="356.6611328125"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="20.681640625" x="14.6591796875" y="15.6494140625">i++</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="20.681640625" x="20.0" y="20.0">(C) +i++</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n3"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="84.673828125" x="466.3686414930556" y="307.609375"/> + <y:Geometry height="73.40234375" width="104.673828125" x="386.8896732390873" y="356.6611328125"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.673828125" x="10.0" y="15.6494140625">emit 0,NM,i</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.673828125" x="20.0" y="20.0">(D) +emit 0,NM,i</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n4"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="99.71484375" x="308.9163876488095" y="409.31040736607144"/> + <y:Geometry height="73.40234375" width="119.71484375" x="226.57749875992062" y="487.41392299107133"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="79.71484375" x="10.0" y="15.6494140625">check n-&gt;data</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="79.71484375" x="20.0" y="20.0">(E) +check n-&gt;data</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n5"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="84.703125" x="302.18335813492064" y="776.712620907738"/> + <y:Geometry height="73.40234375" width="104.703125" x="224.84446924603174" y="915.672581845238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.703125" x="10.0" y="15.6494140625">check input</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.703125" x="20.0" y="20.0">(H) +check input</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n6"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="50.0" x="400.88373015873015" y="930.413792782738"/> + <y:Geometry height="73.40234375" width="60.681640625" x="343.5448939732143" y="1092.776097470238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="20.681640625" x="14.6591796875" y="15.6494140625">i++</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="20.681640625" x="20.0" y="20.0">(L) +i++</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n7"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="50.0" x="413.7015873015873" y="1228.620824032738"/> + <y:Geometry height="58.701171875" width="69.3359375" x="387.2244915674603" y="1452.385472470238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="29.3359375" x="10.33203125" y="15.6494140625">END</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="29.3359375" x="20.0" y="20.0">END</y:NodeLabel> <y:Shape type="ellipse"/> </y:ShapeNode> </data> </node> <node id="n8"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="68.103515625" width="100.0078125" x="388.6976810515873" y="1101.465550595238"/> + <y:Geometry height="102.8046875" width="120.0078125" x="491.14014136904757" y="14.701171875"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="48.103515625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="80.0078125" x="10.0" y="10.0">emit 0,NM,MS -emit 1,MS,BM -emit 0,BM,i</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="48.103515625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="80.0078125" x="20.0" y="27.3505859375">(O) +emit 0,NM,MS +emit 1,MS,BM</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n9"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="58.341796875" x="270.6806888640873" y="543.0115792410714"/> + <y:Geometry height="73.40234375" width="78.341796875" x="183.3417999751984" y="644.5174386160713"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="38.341796875" x="10.0" y="15.6494140625">BM = i</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="38.341796875" x="20.0" y="20.0">(F) +BM = i</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n10"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="89.3671875" x="277.50966021825394" y="643.011449032738"/> + <y:Geometry height="73.40234375" width="109.3671875" x="195.17077132936507" y="767.919652157738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="69.3671875" x="10.0" y="15.6494140625">move next ?</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="69.3671875" x="20.0" y="20.0">(G) +move next ?</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n11"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="53.40234375" width="100.0078125" x="20.000062003968253" y="1108.816136532738"/> + <y:Geometry height="88.103515625" width="120.0078125" x="164.01593501984127" y="1284.879613095238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="80.0078125" x="10.0" y="10.0">emit 0,NM,MS + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="48.103515625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="80.0078125" x="20.0" y="20.0">(J) +emit 0,NM,MS emit 1,MS,BM</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n12"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="53.40234375" width="58.341796875" x="304.6743396577381" y="305.908203125"/> + <y:Geometry height="88.103515625" width="78.341796875" x="217.33545076884923" y="349.310546875"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="38.341796875" x="10.0" y="10.0">MS = i + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="48.103515625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="38.341796875" x="20.0" y="20.0">(B) +MS = i i++</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n13"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="72.697265625" x="160.00811321924604" y="930.413792782738"/> + <y:Geometry height="73.40234375" width="92.697265625" x="116.59938306051586" y="1092.776097470238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="52.697265625" x="10.0" y="15.6494140625">BM&gt;=0 ?</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="52.697265625" x="20.0" y="20.0">(I) +BM&gt;=0 ?</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n14"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="82.8046875" width="104.015625" x="160.008060515873" y="1094.114964657738"/> + <y:Geometry height="117.505859375" width="124.015625" x="20.000124007936506" y="1270.178441220238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="62.8046875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="84.015625" x="10.0" y="10.0">BACKTRACK : + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="77.505859375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="84.015625" x="20.0" y="20.0">(K) +BACKTRACK : i=MS+1 MS = -1 n = root</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n15"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="72.697265625" x="308.18628782242064" y="930.413792782738"/> + <y:Geometry height="73.40234375" width="92.697265625" x="230.84739893353174" y="1092.776097470238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="52.697265625" x="10.0" y="15.6494140625">BM&gt;=0 ?</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="52.697265625" x="20.0" y="20.0">(M) +BM&gt;=0 ?</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n16"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="82.8046875" width="67.669921875" x="36.16900731646825" y="1212.218480282738"/> + <y:Geometry height="117.505859375" width="87.669921875" x="180.18488033234127" y="1422.983128720238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="62.8046875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="47.669921875" x="10.0" y="10.0">i=BM + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="77.505859375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="47.669921875" x="20.0" y="20.0">(J) +i=BM NM=BM MS=-1 n=root</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n17"> - <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="84.673828125" x="284.02380022321427" y="1110.517308407738"/> + <y:Geometry height="73.40234375" width="104.673828125" x="314.55237165178573" y="1292.230199032738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.673828125" x="10.0" y="15.6494140625">emit 0,NM,i</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.673828125" x="20.0" y="20.0">(N) +emit 0,NM,i</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <edge id="e0" source="n1" target="n2"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="28.234374999999943" sy="8.34375" tx="0.0" ty="-25.0"> - <y:Point x="536.9399305555555" y="247.20703125"/> - <y:Point x="596.0426990327381" y="247.20703125"/> + <y:Path sx="34.90104166666674" sy="12.232421875" tx="0.0" ty="-36.701171875"> + <y:Point x="474.127628968254" y="290.609375"/> + <y:Point x="541.904206969246" y="290.609375"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="54.044921875" x="3.057918405769101" y="73.232421875">not found</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7975265623853919" textColor="#000000" visible="true" width="54.044921875" x="11.73170633340618" y="68.53323364257812">not found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e1" source="n2" target="n1"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="25.0" tx="31.763671874999943" ty="-6.28125"> - <y:Point x="596.0428571428571" y="382.609375"/> - <y:Point x="641.0428571428571" y="382.609375"/> - <y:Point x="641.0428571428571" y="147.20703125"/> - <y:Point x="540.4692274305555" y="147.20703125"/> + <y:Path sx="0.0" sy="36.701171875" tx="39.263671875" ty="-9.169921875"> + <y:Point x="541.9043650793651" y="455.0634765625"/> + <y:Point x="592.245238095238" y="455.0634765625"/> + <y:Point x="592.245238095238" y="167.20703125"/> + <y:Point x="478.4902591765873" y="167.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e2" source="n1" target="n3"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="25.0" tx="0.0" ty="-25.0"/> + <y:Path sx="0.0" sy="36.701171875" tx="0.0" ty="-36.701171875"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="53.376953125" x="-55.37696397569442" y="56.576171875">end input</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5" textColor="#000000" visible="true" width="53.376953125" x="-55.376958840990824" y="36.17529296875">end input</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e3" source="n0" target="n1"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="56.103515625" tx="-10.587910747225294" ty="-18.71875000003226"/> + <y:Path sx="0.0" sy="66.103515625" tx="-13.087919957398071" ty="-27.544921875046924"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e4" source="n5" target="n6"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="28.234375" sy="8.34375" tx="0.0" ty="-25.0"> - <y:Point x="372.76929563492064" y="851.712620907738"/> - <y:Point x="425.8836960565476" y="851.712620907738"/> + <y:Path sx="34.901041666666686" sy="12.232421875" tx="0.0" ty="-36.701171875"> + <y:Point x="312.0970734126984" y="1014.074925595238"/> + <y:Point x="373.88568018353175" y="1014.074925595238"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7489413469672621" textColor="#000000" visible="true" width="34.029296875" x="17.085123094553182" y="67.09372442336303">found</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7637317424852962" textColor="#000000" visible="true" width="34.029296875" x="25.759317914896712" y="74.85794561476928">found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e5" source="n3" target="n7"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="25.0" tx="16.666666666666686" ty="-18.65625"> - <y:Point x="508.7055555555556" y="1184.569066220238"/> - <y:Point x="455.368253968254" y="1184.569066220238"/> - </y:Path> + <y:Path sx="0.0" sy="36.701171875" tx="17.333983830096372" ty="-25.4443359375"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e6" source="n5" target="n15"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="25.0" tx="0.0" ty="-25.0"/> - <y:LineStyle color="#000000" type="line" width="1.0"/> - <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.6666666666666666" textColor="#000000" visible="true" width="53.376953125" x="-55.37694459945436" y="53.29164109002966">end input</y:EdgeLabel> - <y:BendStyle smoothed="false"/> - </y:PolyLineEdge> - </data> - </edge> - <edge id="e7" source="n8" target="n7"> - <data key="d6"> - <y:PolyLineEdge> - <y:Path sx="0.0" sy="34.0517578125" tx="0.0" ty="-25.0"/> + <y:Path sx="0.0" sy="36.701171875" tx="0.0" ty="-36.701171875"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.6666666666666666" textColor="#000000" visible="true" width="53.376953125" x="-55.376966300843264" y="53.29164109002977">end input</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e8" source="n6" target="n4"> + <edge id="e7" source="n6" target="n4"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="25.0" tx="24.9287109375" ty="-12.46875"> - <y:Point x="425.88373015873015" y="1005.413792782738"/> - <y:Point x="470.88373015873015" y="1005.413792782738"/> - <y:Point x="470.88373015873015" y="384.31040736607144"/> - <y:Point x="383.7025204613095" y="384.31040736607144"/> + <y:Path sx="0.0" sy="36.701171875" tx="29.9287109375" ty="-18.357421875"> + <y:Point x="373.8857142857143" y="1191.178441220238"/> + <y:Point x="424.2265873015873" y="1191.178441220238"/> + <y:Point x="424.2265873015873" y="462.4139229910714"/> + <y:Point x="316.3636315724206" y="462.4139229910714"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e9" source="n4" target="n9"> + <edge id="e8" source="n4" target="n9"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="-24.9287109375" sy="12.53125" tx="0.0" ty="-25.0"> - <y:Point x="333.8450985863095" y="484.31040736607144"/> - <y:Point x="299.85162450396825" y="484.31040736607144"/> + <y:Path sx="-29.9287109375" sy="18.357421875" tx="0.0" ty="-36.701171875"> + <y:Point x="256.5062096974206" y="585.8162667410713"/> + <y:Point x="222.51273561507938" y="585.8162667410713"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="54.6953125" x="-90.68881155504289" y="67.34376307896207">not NULL</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="54.6953125" x="-90.68880273885367" y="73.21873256138383">not NULL</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e10" source="n4" target="n10"> + <edge id="e9" source="n4" target="n10"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="24.928708893592216" sy="12.46875000000017" tx="22.341796875" ty="-12.53125"> - <y:Point x="383.7025421626984" y="592.3621651785714"/> - <y:Point x="344.53505084325394" y="592.3621651785714"/> + <y:Path sx="29.9287081874013" sy="18.357421875000227" tx="27.341796874999943" ty="-18.357421875"> + <y:Point x="316.3636532738095" y="705.5691964285713"/> + <y:Point x="277.19616195436504" y="705.5691964285713"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.48451821447048476" textColor="#000000" visible="true" width="34.6796875" x="-36.67966656641505" y="105.20117885044647">NULL</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.49567073137073236" textColor="#000000" visible="true" width="34.6796875" x="-36.67965699479407" y="124.2410307384672">NULL</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e11" source="n9" target="n10"> + <edge id="e10" source="n9" target="n10"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="25.0" tx="-22.34182934578763" ty="-12.531250000042405"/> + <y:Path sx="0.0" sy="36.701171875" tx="-27.341844645306708" ty="-18.357421875062187"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e12" source="n5" target="n13"> + <edge id="e11" source="n5" target="n13"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="-28.234375" sy="8.34375" tx="18.17431640625" ty="-12.53125"> - <y:Point x="316.30054563492064" y="851.712620907738"/> - <y:Point x="247.22761966765873" y="851.712620907738"/> - <y:Point x="247.22761966765873" y="905.413792782738"/> - <y:Point x="214.53106243799604" y="905.413792782738"/> + <y:Path sx="-34.901041666666686" sy="12.232421875" tx="23.17431640625" ty="-18.357421875"> + <y:Point x="242.29499007936505" y="1014.074925595238"/> + <y:Point x="208.81888950892858" y="1014.074925595238"/> + <y:Point x="208.81888950892858" y="1067.776097470238"/> + <y:Point x="186.12233227926586" y="1067.776097470238"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7405651785001877" textColor="#000000" visible="true" width="54.044921875" x="-125.11783931671627" y="75.65622442336303">not found</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7276478307488919" textColor="#000000" visible="true" width="54.044921875" x="-89.52101527622767" y="83.42044561476928">not found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e13" source="n10" target="n13"> + <edge id="e12" source="n10" target="n13"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="-22.341796875" sy="12.46875" tx="-18.174322866977974" ty="-12.531250000001592"> - <y:Point x="299.85145709325394" y="718.011449032738"/> - <y:Point x="178.18253968253967" y="718.011449032738"/> + <y:Path sx="-27.341796875" sy="18.357421875" tx="-23.17432532134086" ty="-18.357421875002046"> + <y:Point x="222.51256820436507" y="866.321995907738"/> + <y:Point x="139.77380952380952" y="866.321995907738"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.668647850036439" textColor="#000000" visible="true" width="17.34765625" x="-141.01663976851714" y="119.63956860739086">no</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5872751774254694" textColor="#000000" visible="true" width="17.34765625" x="-102.08646776776918" y="122.99489629836307">no</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e14" source="n1" target="n12"> + <edge id="e13" source="n1" target="n12"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="-28.234375" sy="8.34375" tx="0.0" ty="-26.701171875"> - <y:Point x="480.4711805555556" y="247.20703125"/> - <y:Point x="333.8452039930556" y="247.20703125"/> + <y:Path sx="-34.90104166666674" sy="12.232421875" tx="0.0" ty="-44.0517578125"> + <y:Point x="404.3255456349206" y="290.609375"/> + <y:Point x="256.5063151041667" y="290.609375"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="34.029296875" x="-182.65526693244715" y="71.53125">found</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="34.029296875" x="-183.84849542094543" y="79.29544067382812">found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e15" source="n12" target="n4"> + <edge id="e14" source="n12" target="n4"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="26.701171875" tx="-24.92874572763617" ty="-12.531250000048544"/> + <y:Path sx="0.0" sy="44.0517578125" tx="-29.928762119981116" ty="-18.35742187507151"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e16" source="n11" target="n16"> + <edge id="e15" source="n11" target="n16"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="26.701171875" tx="0.0" ty="-41.40234375"/> + <y:Path sx="0.0" sy="44.0517578125" tx="0.0" ty="-58.7529296875"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e17" source="n10" target="n5"> + <edge id="e16" source="n10" target="n5"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="22.34181636903031" sy="12.468750000015234" tx="0.0" ty="-25.0"/> + <y:Path sx="27.34182899995352" sy="18.357421875028308" tx="0.0" ty="-36.701171875"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="22.673828125" x="-24.673956436557432" y="67.35928838820678">yes</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="22.673828125" x="-24.673976157073014" y="63.86813848586303">yes</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e18" source="n13" target="n11"> + <edge id="e17" source="n13" target="n11"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="-18.17431640625" sy="12.46875" tx="0.0" ty="-26.701171875"> - <y:Point x="178.18242962549604" y="1005.413792782738"/> - <y:Point x="177.6821521577381" y="1005.413792782738"/> - <y:Point x="177.6821521577381" y="1074.114964657738"/> - <y:Point x="70.00396825396825" y="1074.114964657738"/> + <y:Path sx="23.174336131201812" sy="18.357421875010232" tx="-30.001953125" ty="-44.0517578125"> + <y:Point x="186.12223152281746" y="1259.879613095238"/> + <y:Point x="194.01788814484127" y="1259.879613095238"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.2323348891468741" textColor="#000000" visible="true" width="22.673828125" x="-25.174110049293148" y="62.49460332961303">yes</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5204039228973768" textColor="#000000" visible="true" width="22.673828125" x="-24.67391760275683" y="71.05205775669629">yes</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e19" source="n13" target="n14"> + <edge id="e18" source="n13" target="n14"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="18.17431640625" sy="12.46875" tx="0.0" ty="-41.40234375"> - <y:Point x="214.53106243799604" y="1005.413792782738"/> - <y:Point x="212.0158916170635" y="1005.413792782738"/> + <y:Path sx="-23.17431640625" sy="18.357421875" tx="0.0" ty="-58.7529296875"> + <y:Point x="139.77369946676586" y="1191.178441220238"/> + <y:Point x="82.00795510912698" y="1191.178441220238"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.729239758318533" textColor="#000000" visible="true" width="17.34765625" x="-21.862843889897192" y="77.74460332961303">no</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7565598105185114" textColor="#000000" visible="true" width="17.34765625" x="-77.11340846827596" y="68.93063848586303">no</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e20" source="n15" target="n17"> + <edge id="e19" source="n15" target="n17"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="-18.174327006673252" sy="12.468750000004661" tx="0.0" ty="-25.0"/> + <y:Path sx="23.17431640625" sy="18.357421875" tx="0.0" ty="-36.701171875"> + <y:Point x="300.37034815228174" y="1206.178441220238"/> + <y:Point x="366.8893043154762" y="1206.178441220238"/> + </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5" textColor="#000000" visible="true" width="17.34765625" x="-19.34760060577139" y="68.19760625930053">no</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7058037221240121" textColor="#000000" visible="true" width="17.34765625" x="47.17127842739666" y="78.08558640252977">no</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e21" source="n17" target="n7"> + <edge id="e20" source="n17" target="n7"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="25.0" tx="-16.666666666666686" ty="-18.65625"> - <y:Point x="326.36071428571427" y="1185.517308407738"/> - <y:Point x="422.03492063492064" y="1185.517308407738"/> + <y:Path sx="0.0" sy="36.701171875" tx="-17.333984375" ty="-25.4443359375"> + <y:Point x="366.88928571428573" y="1390.632542782738"/> + <y:Point x="404.5584759424603" y="1390.632542782738"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e22" source="n15" target="n8"> + <edge id="e21" source="n15" target="n11"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="18.17431640625" sy="12.46875" tx="0.0" ty="-34.0517578125"> - <y:Point x="362.70923704117064" y="1020.413792782738"/> - <y:Point x="438.7015966021825" y="1020.413792782738"/> - </y:Path> + <y:Path sx="-23.174328623199756" sy="18.357421875003865" tx="30.001953125" ty="-44.0517578125"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7988559163212264" textColor="#000000" visible="true" width="22.673828125" x="51.31853476183261" y="79.11838262648803">yes</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.75" textColor="#000000" visible="true" width="22.673828125" x="-24.673764204843565" y="88.28122442336303">yes</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e23" source="n14" target="n1"> + <edge id="e22" source="n14" target="n1"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="41.40234375" tx="-31.763671875" ty="-6.21875"> - <y:Point x="212.015873015873" y="1201.919652157738"/> - <y:Point x="140.0079365079365" y="1201.919652157738"/> - <y:Point x="140.0079365079365" y="147.20703125"/> - <y:Point x="476.9418836805556" y="147.20703125"/> + <y:Path sx="0.0" sy="58.7529296875" tx="-39.263671875" ty="-9.169921875"> + <y:Point x="82.0079365079365" y="1412.684300595238"/> + <y:Point x="0.0" y="1412.684300595238"/> + <y:Point x="0.0" y="167.20703125"/> + <y:Point x="399.9629154265873" y="167.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> - <edge id="e24" source="n16" target="n1"> + <edge id="e23" source="n16" target="n1"> <data key="d6"> <y:PolyLineEdge> - <y:Path sx="0.0" sy="41.40234375" tx="10.587890624999943" ty="-18.78125"> - <y:Point x="70.00396825396825" y="1320.023167782738"/> - <y:Point x="656.0428571428571" y="1320.023167782738"/> - <y:Point x="656.0428571428571" y="132.20703125"/> - <y:Point x="519.2934461805555" y="132.20703125"/> + <y:Path sx="0.0" sy="58.7529296875" tx="13.087890625" ty="-27.544921875"> + <y:Point x="224.01984126984127" y="1565.488988095238"/> + <y:Point x="607.245238095238" y="1565.488988095238"/> + <y:Point x="607.245238095238" y="152.20703125"/> + <y:Point x="452.3144779265873" y="152.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> </graph> <data key="d0"> <y:Resources/> </data> </graphml>
nlehuen/pytst
b7ab4a4ea15a4673bc2412752212a7c319d8f4ec
Little nudge on the graph of the scan algorithm.
diff --git a/scan algorithm.graphml b/scan algorithm.graphml index 45f3539..6c963cf 100644 --- a/scan algorithm.graphml +++ b/scan algorithm.graphml @@ -1,571 +1,571 @@ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd"> <!--Created by yFiles for Java 2.7--> <key for="graphml" id="d0" yfiles.type="resources"/> <key attr.name="url" attr.type="string" for="node" id="d1"/> <key attr.name="description" attr.type="string" for="node" id="d2"/> <key for="node" id="d3" yfiles.type="nodegraphics"/> <key attr.name="url" attr.type="string" for="edge" id="d4"/> <key attr.name="description" attr.type="string" for="edge" id="d5"/> <key for="edge" id="d6" yfiles.type="edgegraphics"/> <graph edgedefault="directed" id="G"> <node id="n0"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="112.20703125" width="70.001953125" x="463.11688058035713" y="0.0"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="92.20703125" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="50.001953125" x="10.0" y="10.0">START : NM = 0 MS = -1 BM = -1 n = root i = 0</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n1"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="50.0" width="84.703125" x="466.3539930555556" y="172.20703125"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.703125" x="10.0" y="15.6494140625">check input</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n2"> <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="50.0" x="566.0388888888889" y="307.609375"/> + <y:Geometry height="50.0" width="50.0" x="571.0428571428571" y="307.609375"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="20.681640625" x="14.6591796875" y="15.6494140625">i++</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n3"> <data key="d2"/> <data key="d3"> <y:ShapeNode> - <y:Geometry height="50.0" width="74.666015625" x="471.3725477430556" y="307.609375"/> + <y:Geometry height="50.0" width="84.673828125" x="466.3686414930556" y="307.609375"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> - <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="54.666015625" x="10.0" y="15.6494140625">emit NM,i</y:NodeLabel> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.673828125" x="10.0" y="15.6494140625">emit 0,NM,i</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n4"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="50.0" width="99.71484375" x="308.9163876488095" y="409.31040736607144"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="79.71484375" x="10.0" y="15.6494140625">check n-&gt;data</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n5"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="50.0" width="84.703125" x="302.18335813492064" y="776.712620907738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.703125" x="10.0" y="15.6494140625">check input</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n6"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="50.0" width="50.0" x="400.88373015873015" y="930.413792782738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="20.681640625" x="14.6591796875" y="15.6494140625">i++</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n7"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="50.0" width="50.0" x="413.7015873015873" y="1228.620824032738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="29.3359375" x="10.33203125" y="15.6494140625">END</y:NodeLabel> <y:Shape type="ellipse"/> </y:ShapeNode> </data> </node> <node id="n8"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="68.103515625" width="100.0078125" x="388.6976810515873" y="1101.465550595238"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="48.103515625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="80.0078125" x="10.0" y="10.0">emit 0,NM,MS emit 1,MS,BM emit 0,BM,i</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n9"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="50.0" width="58.341796875" x="270.6806888640873" y="543.0115792410714"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="38.341796875" x="10.0" y="15.6494140625">BM = i</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n10"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="50.0" width="89.3671875" x="277.50966021825394" y="643.011449032738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="69.3671875" x="10.0" y="15.6494140625">move next ?</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n11"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="53.40234375" width="100.0078125" x="20.000062003968253" y="1108.816136532738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="80.0078125" x="10.0" y="10.0">emit 0,NM,MS emit 1,MS,BM</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n12"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="53.40234375" width="58.341796875" x="304.6743396577381" y="305.908203125"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="38.341796875" x="10.0" y="10.0">MS = i i++</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n13"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="50.0" width="72.697265625" x="160.00811321924604" y="930.413792782738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="52.697265625" x="10.0" y="15.6494140625">BM&gt;=0 ?</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n14"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="82.8046875" width="104.015625" x="160.008060515873" y="1094.114964657738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="62.8046875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="84.015625" x="10.0" y="10.0">BACKTRACK : i=MS+1 MS = -1 n = root</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n15"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="50.0" width="72.697265625" x="308.18628782242064" y="930.413792782738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="52.697265625" x="10.0" y="15.6494140625">BM&gt;=0 ?</y:NodeLabel> <y:Shape type="diamond"/> </y:ShapeNode> </data> </node> <node id="n16"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="82.8046875" width="67.669921875" x="36.16900731646825" y="1212.218480282738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="62.8046875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="47.669921875" x="10.0" y="10.0">i=BM NM=BM MS=-1 n=root</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <node id="n17"> <data key="d2"/> <data key="d3"> <y:ShapeNode> <y:Geometry height="50.0" width="84.673828125" x="284.02380022321427" y="1110.517308407738"/> <y:Fill color="#FFCC00" transparent="false"/> <y:BorderStyle color="#000000" type="line" width="1.0"/> <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.673828125" x="10.0" y="15.6494140625">emit 0,NM,i</y:NodeLabel> <y:Shape type="parallelogram"/> </y:ShapeNode> </data> </node> <edge id="e0" source="n1" target="n2"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="28.234374999999943" sy="8.34375" tx="0.0" ty="-25.0"> <y:Point x="536.9399305555555" y="247.20703125"/> - <y:Point x="591.0390562996032" y="247.20703125"/> + <y:Point x="596.0426990327381" y="247.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="63.37890625" x="-11.27993070498178" y="73.232421875">c not found</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="54.044921875" x="3.057918405769101" y="73.232421875">not found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e1" source="n2" target="n1"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="25.0" tx="31.763671874999943" ty="-6.28125"> - <y:Point x="591.0388888888889" y="382.609375"/> - <y:Point x="636.0388888888889" y="382.609375"/> - <y:Point x="636.0388888888889" y="147.20703125"/> + <y:Point x="596.0428571428571" y="382.609375"/> + <y:Point x="641.0428571428571" y="382.609375"/> + <y:Point x="641.0428571428571" y="147.20703125"/> <y:Point x="540.4692274305555" y="147.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e2" source="n1" target="n3"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="25.0" tx="0.0" ty="-25.0"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="53.376953125" x="-55.37696397569442" y="56.576171875">end input</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e3" source="n0" target="n1"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="56.103515625" tx="-10.587910747225294" ty="-18.71875000003226"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e4" source="n5" target="n6"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="28.234375" sy="8.34375" tx="0.0" ty="-25.0"> <y:Point x="372.76929563492064" y="851.712620907738"/> - <y:Point x="425.88362475198414" y="851.712620907738"/> + <y:Point x="425.8836960565476" y="851.712620907738"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7489412177746315" textColor="#000000" visible="true" width="43.36328125" x="7.751090461785452" y="67.09372442336303">found c</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7489413469672621" textColor="#000000" visible="true" width="34.029296875" x="17.085123094553182" y="67.09372442336303">found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e5" source="n3" target="n7"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="25.0" tx="16.666666666666686" ty="-18.65625"> <y:Point x="508.7055555555556" y="1184.569066220238"/> <y:Point x="455.368253968254" y="1184.569066220238"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e6" source="n5" target="n15"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="25.0" tx="0.0" ty="-25.0"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.6666666666666666" textColor="#000000" visible="true" width="53.376953125" x="-55.37694459945436" y="53.29164109002966">end input</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e7" source="n8" target="n7"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="34.0517578125" tx="0.0" ty="-25.0"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e8" source="n6" target="n4"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="25.0" tx="24.9287109375" ty="-12.46875"> <y:Point x="425.88373015873015" y="1005.413792782738"/> <y:Point x="470.88373015873015" y="1005.413792782738"/> <y:Point x="470.88373015873015" y="384.31040736607144"/> <y:Point x="383.7025204613095" y="384.31040736607144"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e9" source="n4" target="n9"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="-24.9287109375" sy="12.53125" tx="0.0" ty="-25.0"> <y:Point x="333.8450985863095" y="484.31040736607144"/> <y:Point x="299.85162450396825" y="484.31040736607144"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="54.6953125" x="-90.68881155504289" y="67.34376307896207">not NULL</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e10" source="n4" target="n10"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="24.928708893592216" sy="12.46875000000017" tx="22.341796875" ty="-12.53125"> <y:Point x="383.7025421626984" y="592.3621651785714"/> <y:Point x="344.53505084325394" y="592.3621651785714"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.48451821447048476" textColor="#000000" visible="true" width="34.6796875" x="-36.67966656641505" y="105.20117885044647">NULL</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e11" source="n9" target="n10"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="25.0" tx="-22.34182934578763" ty="-12.531250000042405"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e12" source="n5" target="n13"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="-28.234375" sy="8.34375" tx="18.17431640625" ty="-12.53125"> <y:Point x="316.30054563492064" y="851.712620907738"/> - <y:Point x="256.56167534722226" y="851.712620907738"/> - <y:Point x="256.56167534722226" y="905.413792782738"/> + <y:Point x="247.22761966765873" y="851.712620907738"/> + <y:Point x="247.22761966765873" y="905.413792782738"/> <y:Point x="214.53106243799604" y="905.413792782738"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.6907092709029321" textColor="#000000" visible="true" width="63.37890625" x="-125.11776801215274" y="75.65622442336303">not found c</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7405651785001877" textColor="#000000" visible="true" width="54.044921875" x="-125.11783931671627" y="75.65622442336303">not found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e13" source="n10" target="n13"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="-22.341796875" sy="12.46875" tx="-18.174322866977974" ty="-12.531250000001592"> <y:Point x="299.85145709325394" y="718.011449032738"/> <y:Point x="178.18253968253967" y="718.011449032738"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.668647850036439" textColor="#000000" visible="true" width="17.34765625" x="-141.01663976851714" y="119.63956860739086">no</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e14" source="n1" target="n12"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="-28.234375" sy="8.34375" tx="0.0" ty="-26.701171875"> <y:Point x="480.4711805555556" y="247.20703125"/> - <y:Point x="333.8451326884921" y="247.20703125"/> + <y:Point x="333.8452039930556" y="247.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> - <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="43.36328125" x="-191.98928632272094" y="71.53125">c found</y:EdgeLabel> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="34.029296875" x="-182.65526693244715" y="71.53125">found</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e15" source="n12" target="n4"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="26.701171875" tx="-24.92874572763617" ty="-12.531250000048544"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e16" source="n11" target="n16"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="26.701171875" tx="0.0" ty="-41.40234375"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e17" source="n10" target="n5"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="22.34181636903031" sy="12.468750000015234" tx="0.0" ty="-25.0"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="22.673828125" x="-24.673956436557432" y="67.35928838820678">yes</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e18" source="n13" target="n11"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="-18.17431640625" sy="12.46875" tx="0.0" ty="-26.701171875"> <y:Point x="178.18242962549604" y="1005.413792782738"/> <y:Point x="177.6821521577381" y="1005.413792782738"/> <y:Point x="177.6821521577381" y="1074.114964657738"/> <y:Point x="70.00396825396825" y="1074.114964657738"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.2323348891468741" textColor="#000000" visible="true" width="22.673828125" x="-25.174110049293148" y="62.49460332961303">yes</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e19" source="n13" target="n14"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="18.17431640625" sy="12.46875" tx="0.0" ty="-41.40234375"> <y:Point x="214.53106243799604" y="1005.413792782738"/> <y:Point x="212.0158916170635" y="1005.413792782738"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.729239758318533" textColor="#000000" visible="true" width="17.34765625" x="-21.862843889897192" y="77.74460332961303">no</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e20" source="n15" target="n17"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="-18.174327006673252" sy="12.468750000004661" tx="0.0" ty="-25.0"/> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5" textColor="#000000" visible="true" width="17.34765625" x="-19.34760060577139" y="68.19760625930053">no</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e21" source="n17" target="n7"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="25.0" tx="-16.666666666666686" ty="-18.65625"> <y:Point x="326.36071428571427" y="1185.517308407738"/> <y:Point x="422.03492063492064" y="1185.517308407738"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e22" source="n15" target="n8"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="18.17431640625" sy="12.46875" tx="0.0" ty="-34.0517578125"> <y:Point x="362.70923704117064" y="1020.413792782738"/> <y:Point x="438.7015966021825" y="1020.413792782738"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7988559163212264" textColor="#000000" visible="true" width="22.673828125" x="51.31853476183261" y="79.11838262648803">yes</y:EdgeLabel> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e23" source="n14" target="n1"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="41.40234375" tx="-31.763671875" ty="-6.21875"> <y:Point x="212.015873015873" y="1201.919652157738"/> <y:Point x="140.0079365079365" y="1201.919652157738"/> <y:Point x="140.0079365079365" y="147.20703125"/> <y:Point x="476.9418836805556" y="147.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> <edge id="e24" source="n16" target="n1"> <data key="d6"> <y:PolyLineEdge> <y:Path sx="0.0" sy="41.40234375" tx="10.587890624999943" ty="-18.78125"> <y:Point x="70.00396825396825" y="1320.023167782738"/> - <y:Point x="651.0388888888889" y="1320.023167782738"/> - <y:Point x="651.0388888888889" y="132.20703125"/> + <y:Point x="656.0428571428571" y="1320.023167782738"/> + <y:Point x="656.0428571428571" y="132.20703125"/> <y:Point x="519.2934461805555" y="132.20703125"/> </y:Path> <y:LineStyle color="#000000" type="line" width="1.0"/> <y:Arrows source="none" target="standard"/> <y:BendStyle smoothed="false"/> </y:PolyLineEdge> </data> </edge> </graph> <data key="d0"> <y:Resources/> </data> </graphml>
nlehuen/pytst
8dc3ac2aacd3820f41222e3cd82347259fb7dd56
Added a diagram for the new scan algorithm.
diff --git a/scan algorithm.graphml b/scan algorithm.graphml new file mode 100644 index 0000000..45f3539 --- /dev/null +++ b/scan algorithm.graphml @@ -0,0 +1,571 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd"> + <!--Created by yFiles for Java 2.7--> + <key for="graphml" id="d0" yfiles.type="resources"/> + <key attr.name="url" attr.type="string" for="node" id="d1"/> + <key attr.name="description" attr.type="string" for="node" id="d2"/> + <key for="node" id="d3" yfiles.type="nodegraphics"/> + <key attr.name="url" attr.type="string" for="edge" id="d4"/> + <key attr.name="description" attr.type="string" for="edge" id="d5"/> + <key for="edge" id="d6" yfiles.type="edgegraphics"/> + <graph edgedefault="directed" id="G"> + <node id="n0"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="112.20703125" width="70.001953125" x="463.11688058035713" y="0.0"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="92.20703125" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="50.001953125" x="10.0" y="10.0">START : +NM = 0 +MS = -1 +BM = -1 +n = root +i = 0</y:NodeLabel> + <y:Shape type="parallelogram"/> + </y:ShapeNode> + </data> + </node> + <node id="n1"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="50.0" width="84.703125" x="466.3539930555556" y="172.20703125"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.703125" x="10.0" y="15.6494140625">check input</y:NodeLabel> + <y:Shape type="diamond"/> + </y:ShapeNode> + </data> + </node> + <node id="n2"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="50.0" width="50.0" x="566.0388888888889" y="307.609375"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="20.681640625" x="14.6591796875" y="15.6494140625">i++</y:NodeLabel> + <y:Shape type="parallelogram"/> + </y:ShapeNode> + </data> + </node> + <node id="n3"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="50.0" width="74.666015625" x="471.3725477430556" y="307.609375"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="54.666015625" x="10.0" y="15.6494140625">emit NM,i</y:NodeLabel> + <y:Shape type="parallelogram"/> + </y:ShapeNode> + </data> + </node> + <node id="n4"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="50.0" width="99.71484375" x="308.9163876488095" y="409.31040736607144"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="79.71484375" x="10.0" y="15.6494140625">check n-&gt;data</y:NodeLabel> + <y:Shape type="diamond"/> + </y:ShapeNode> + </data> + </node> + <node id="n5"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="50.0" width="84.703125" x="302.18335813492064" y="776.712620907738"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.703125" x="10.0" y="15.6494140625">check input</y:NodeLabel> + <y:Shape type="diamond"/> + </y:ShapeNode> + </data> + </node> + <node id="n6"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="50.0" width="50.0" x="400.88373015873015" y="930.413792782738"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="20.681640625" x="14.6591796875" y="15.6494140625">i++</y:NodeLabel> + <y:Shape type="parallelogram"/> + </y:ShapeNode> + </data> + </node> + <node id="n7"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="50.0" width="50.0" x="413.7015873015873" y="1228.620824032738"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="29.3359375" x="10.33203125" y="15.6494140625">END</y:NodeLabel> + <y:Shape type="ellipse"/> + </y:ShapeNode> + </data> + </node> + <node id="n8"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="68.103515625" width="100.0078125" x="388.6976810515873" y="1101.465550595238"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="48.103515625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="80.0078125" x="10.0" y="10.0">emit 0,NM,MS +emit 1,MS,BM +emit 0,BM,i</y:NodeLabel> + <y:Shape type="parallelogram"/> + </y:ShapeNode> + </data> + </node> + <node id="n9"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="50.0" width="58.341796875" x="270.6806888640873" y="543.0115792410714"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="38.341796875" x="10.0" y="15.6494140625">BM = i</y:NodeLabel> + <y:Shape type="parallelogram"/> + </y:ShapeNode> + </data> + </node> + <node id="n10"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="50.0" width="89.3671875" x="277.50966021825394" y="643.011449032738"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="69.3671875" x="10.0" y="15.6494140625">move next ?</y:NodeLabel> + <y:Shape type="diamond"/> + </y:ShapeNode> + </data> + </node> + <node id="n11"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="53.40234375" width="100.0078125" x="20.000062003968253" y="1108.816136532738"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="80.0078125" x="10.0" y="10.0">emit 0,NM,MS +emit 1,MS,BM</y:NodeLabel> + <y:Shape type="parallelogram"/> + </y:ShapeNode> + </data> + </node> + <node id="n12"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="53.40234375" width="58.341796875" x="304.6743396577381" y="305.908203125"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="33.40234375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="38.341796875" x="10.0" y="10.0">MS = i +i++</y:NodeLabel> + <y:Shape type="parallelogram"/> + </y:ShapeNode> + </data> + </node> + <node id="n13"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="50.0" width="72.697265625" x="160.00811321924604" y="930.413792782738"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="52.697265625" x="10.0" y="15.6494140625">BM&gt;=0 ?</y:NodeLabel> + <y:Shape type="diamond"/> + </y:ShapeNode> + </data> + </node> + <node id="n14"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="82.8046875" width="104.015625" x="160.008060515873" y="1094.114964657738"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="62.8046875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="84.015625" x="10.0" y="10.0">BACKTRACK : +i=MS+1 +MS = -1 +n = root</y:NodeLabel> + <y:Shape type="parallelogram"/> + </y:ShapeNode> + </data> + </node> + <node id="n15"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="50.0" width="72.697265625" x="308.18628782242064" y="930.413792782738"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="52.697265625" x="10.0" y="15.6494140625">BM&gt;=0 ?</y:NodeLabel> + <y:Shape type="diamond"/> + </y:ShapeNode> + </data> + </node> + <node id="n16"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="82.8046875" width="67.669921875" x="36.16900731646825" y="1212.218480282738"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="62.8046875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="47.669921875" x="10.0" y="10.0">i=BM +NM=BM +MS=-1 +n=root</y:NodeLabel> + <y:Shape type="parallelogram"/> + </y:ShapeNode> + </data> + </node> + <node id="n17"> + <data key="d2"/> + <data key="d3"> + <y:ShapeNode> + <y:Geometry height="50.0" width="84.673828125" x="284.02380022321427" y="1110.517308407738"/> + <y:Fill color="#FFCC00" transparent="false"/> + <y:BorderStyle color="#000000" type="line" width="1.0"/> + <y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="64.673828125" x="10.0" y="15.6494140625">emit 0,NM,i</y:NodeLabel> + <y:Shape type="parallelogram"/> + </y:ShapeNode> + </data> + </node> + <edge id="e0" source="n1" target="n2"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="28.234374999999943" sy="8.34375" tx="0.0" ty="-25.0"> + <y:Point x="536.9399305555555" y="247.20703125"/> + <y:Point x="591.0390562996032" y="247.20703125"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="63.37890625" x="-11.27993070498178" y="73.232421875">c not found</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e1" source="n2" target="n1"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="0.0" sy="25.0" tx="31.763671874999943" ty="-6.28125"> + <y:Point x="591.0388888888889" y="382.609375"/> + <y:Point x="636.0388888888889" y="382.609375"/> + <y:Point x="636.0388888888889" y="147.20703125"/> + <y:Point x="540.4692274305555" y="147.20703125"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e2" source="n1" target="n3"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="0.0" sy="25.0" tx="0.0" ty="-25.0"/> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="53.376953125" x="-55.37696397569442" y="56.576171875">end input</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e3" source="n0" target="n1"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="0.0" sy="56.103515625" tx="-10.587910747225294" ty="-18.71875000003226"/> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e4" source="n5" target="n6"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="28.234375" sy="8.34375" tx="0.0" ty="-25.0"> + <y:Point x="372.76929563492064" y="851.712620907738"/> + <y:Point x="425.88362475198414" y="851.712620907738"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7489412177746315" textColor="#000000" visible="true" width="43.36328125" x="7.751090461785452" y="67.09372442336303">found c</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e5" source="n3" target="n7"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="0.0" sy="25.0" tx="16.666666666666686" ty="-18.65625"> + <y:Point x="508.7055555555556" y="1184.569066220238"/> + <y:Point x="455.368253968254" y="1184.569066220238"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e6" source="n5" target="n15"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="0.0" sy="25.0" tx="0.0" ty="-25.0"/> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.6666666666666666" textColor="#000000" visible="true" width="53.376953125" x="-55.37694459945436" y="53.29164109002966">end input</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e7" source="n8" target="n7"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="0.0" sy="34.0517578125" tx="0.0" ty="-25.0"/> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e8" source="n6" target="n4"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="0.0" sy="25.0" tx="24.9287109375" ty="-12.46875"> + <y:Point x="425.88373015873015" y="1005.413792782738"/> + <y:Point x="470.88373015873015" y="1005.413792782738"/> + <y:Point x="470.88373015873015" y="384.31040736607144"/> + <y:Point x="383.7025204613095" y="384.31040736607144"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e9" source="n4" target="n9"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="-24.9287109375" sy="12.53125" tx="0.0" ty="-25.0"> + <y:Point x="333.8450985863095" y="484.31040736607144"/> + <y:Point x="299.85162450396825" y="484.31040736607144"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="54.6953125" x="-90.68881155504289" y="67.34376307896207">not NULL</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e10" source="n4" target="n10"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="24.928708893592216" sy="12.46875000000017" tx="22.341796875" ty="-12.53125"> + <y:Point x="383.7025421626984" y="592.3621651785714"/> + <y:Point x="344.53505084325394" y="592.3621651785714"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.48451821447048476" textColor="#000000" visible="true" width="34.6796875" x="-36.67966656641505" y="105.20117885044647">NULL</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e11" source="n9" target="n10"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="0.0" sy="25.0" tx="-22.34182934578763" ty="-12.531250000042405"/> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e12" source="n5" target="n13"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="-28.234375" sy="8.34375" tx="18.17431640625" ty="-12.53125"> + <y:Point x="316.30054563492064" y="851.712620907738"/> + <y:Point x="256.56167534722226" y="851.712620907738"/> + <y:Point x="256.56167534722226" y="905.413792782738"/> + <y:Point x="214.53106243799604" y="905.413792782738"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.6907092709029321" textColor="#000000" visible="true" width="63.37890625" x="-125.11776801215274" y="75.65622442336303">not found c</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e13" source="n10" target="n13"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="-22.341796875" sy="12.46875" tx="-18.174322866977974" ty="-12.531250000001592"> + <y:Point x="299.85145709325394" y="718.011449032738"/> + <y:Point x="178.18253968253967" y="718.011449032738"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.668647850036439" textColor="#000000" visible="true" width="17.34765625" x="-141.01663976851714" y="119.63956860739086">no</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e14" source="n1" target="n12"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="-28.234375" sy="8.34375" tx="0.0" ty="-26.701171875"> + <y:Point x="480.4711805555556" y="247.20703125"/> + <y:Point x="333.8451326884921" y="247.20703125"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="43.36328125" x="-191.98928632272094" y="71.53125">c found</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e15" source="n12" target="n4"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="0.0" sy="26.701171875" tx="-24.92874572763617" ty="-12.531250000048544"/> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e16" source="n11" target="n16"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="0.0" sy="26.701171875" tx="0.0" ty="-41.40234375"/> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e17" source="n10" target="n5"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="22.34181636903031" sy="12.468750000015234" tx="0.0" ty="-25.0"/> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="1.0" textColor="#000000" visible="true" width="22.673828125" x="-24.673956436557432" y="67.35928838820678">yes</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e18" source="n13" target="n11"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="-18.17431640625" sy="12.46875" tx="0.0" ty="-26.701171875"> + <y:Point x="178.18242962549604" y="1005.413792782738"/> + <y:Point x="177.6821521577381" y="1005.413792782738"/> + <y:Point x="177.6821521577381" y="1074.114964657738"/> + <y:Point x="70.00396825396825" y="1074.114964657738"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.2323348891468741" textColor="#000000" visible="true" width="22.673828125" x="-25.174110049293148" y="62.49460332961303">yes</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e19" source="n13" target="n14"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="18.17431640625" sy="12.46875" tx="0.0" ty="-41.40234375"> + <y:Point x="214.53106243799604" y="1005.413792782738"/> + <y:Point x="212.0158916170635" y="1005.413792782738"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.729239758318533" textColor="#000000" visible="true" width="17.34765625" x="-21.862843889897192" y="77.74460332961303">no</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e20" source="n15" target="n17"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="-18.174327006673252" sy="12.468750000004661" tx="0.0" ty="-25.0"/> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.5" textColor="#000000" visible="true" width="17.34765625" x="-19.34760060577139" y="68.19760625930053">no</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e21" source="n17" target="n7"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="0.0" sy="25.0" tx="-16.666666666666686" ty="-18.65625"> + <y:Point x="326.36071428571427" y="1185.517308407738"/> + <y:Point x="422.03492063492064" y="1185.517308407738"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e22" source="n15" target="n8"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="18.17431640625" sy="12.46875" tx="0.0" ty="-34.0517578125"> + <y:Point x="362.70923704117064" y="1020.413792782738"/> + <y:Point x="438.7015966021825" y="1020.413792782738"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="side_slider" preferredPlacement="right" ratio="0.7988559163212264" textColor="#000000" visible="true" width="22.673828125" x="51.31853476183261" y="79.11838262648803">yes</y:EdgeLabel> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e23" source="n14" target="n1"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="0.0" sy="41.40234375" tx="-31.763671875" ty="-6.21875"> + <y:Point x="212.015873015873" y="1201.919652157738"/> + <y:Point x="140.0079365079365" y="1201.919652157738"/> + <y:Point x="140.0079365079365" y="147.20703125"/> + <y:Point x="476.9418836805556" y="147.20703125"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + <edge id="e24" source="n16" target="n1"> + <data key="d6"> + <y:PolyLineEdge> + <y:Path sx="0.0" sy="41.40234375" tx="10.587890624999943" ty="-18.78125"> + <y:Point x="70.00396825396825" y="1320.023167782738"/> + <y:Point x="651.0388888888889" y="1320.023167782738"/> + <y:Point x="651.0388888888889" y="132.20703125"/> + <y:Point x="519.2934461805555" y="132.20703125"/> + </y:Path> + <y:LineStyle color="#000000" type="line" width="1.0"/> + <y:Arrows source="none" target="standard"/> + <y:BendStyle smoothed="false"/> + </y:PolyLineEdge> + </data> + </edge> + </graph> + <data key="d0"> + <y:Resources/> + </data> +</graphml>
nlehuen/pytst
24cdeb7eea97587b31db1aa894e8a470394b2284
- reactivated scanner - migrated project files to Visual Studio 2008. - changed version number to 1.18RC
diff --git a/include/tst.h b/include/tst.h index 7ec107b..9b0fef3 100644 --- a/include/tst.h +++ b/include/tst.h @@ -1,546 +1,546 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __TST__H_INCLUDED__ #define __TST__H_INCLUDED__ -const char* const TST_VERSION = "1.17"; +const char* const TST_VERSION = "1.18RC"; #include "debug.h" #include <iostream> #ifdef __PYTHON__BUILD__ #include "Python.h" #define tst_malloc PyMem_Malloc #define tst_realloc PyMem_Realloc #define tst_free PyMem_Free // Pour ajouter/supprimer les fonctions de scanning. - // #define SCANNER + #define SCANNER #else #include "stdlib.h" #define tst_malloc malloc #define tst_realloc realloc #define tst_free free // Pour ajouter/supprimer les fonctions de scanning. // #define SCANNER #endif template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst; #include "fundamentals.h" #include "memory_storage.h" #include "iterators.h" template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst { public: friend class lexical_iterator<charT,valueT,storageT,serializerT,stringT>; friend class match_iterator<charT,valueT,storageT,serializerT,stringT>; typedef charT character_type; typedef valueT value_type; typedef storageT storage_type; typedef serializerT serializer_type; tst(); virtual ~tst() { delete storage; } void pack() { storage->pack(root); } valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,const stringT & string) const; valueT close_match(const stringT & string,int maximum_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT prefix_match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT get(const stringT & string) const; valueT get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory); valueT put(const stringT & string,valueT data); void remove(const stringT & string); bool contains(const stringT & string) const; void write(std::ostream &file) const; void read(std::istream &file); lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator() const { stringT key; return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,key,root); } lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; find_node(&current_index,&best_node,string); return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,string.substr(0,string.size()-1),current_index); } match_iterator<charT,valueT,storageT,serializerT,stringT> close_match_iterator(const stringT & string,int distance) const { return match_iterator<charT,valueT,storageT,serializerT,stringT>(this,string,distance,root); } int get_number_of_nodes() const { return storage->size(); } valueT get_default_value() const { return default_value; } #ifdef SCANNER valueT scan(const stringT & string,tst_action<charT,valueT,stringT>* to_perform); valueT scan_with_stop_chars(const stringT & string,const stringT& stop_chars,tst_action<charT,valueT,stringT>* to_perform) const; #endif protected: void set_storage(storageT* new_storage) { delete storage; storage = new_storage; } private: storageT* storage; valueT default_value; int root; void walk_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void close_match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,const size_t position, const int distance, const int remaining_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_joker_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_star_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; int build_node(node_info<charT,valueT>* current_node,const stringT & string,size_t current_position); void remove_node(int* current_index,const stringT & string,const size_t position); tst_node<charT,valueT>* find_node(int* current_index,int* best_node, const stringT & string) const; void balance_node(node_info<charT,valueT>* bal); void ll(node_info<charT,valueT>* bal); void rr(node_info<charT,valueT>* bal); void lr(node_info<charT,valueT>* bal); void rl(node_info<charT,valueT>* bal); void compute_height_and_balance(node_info<charT,valueT>* current_node_info) const; void write_node(std::ostream& file,serializerT* writer,int index) const; int read_node(std::istream& file,serializerT* reader,int depth); #ifdef SCANNER void compute_backtrack(tst_node<charT,valueT> *current_node,const stringT & string,int si_match_start,int si_match_end); #endif }; template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst<charT,valueT,storageT,serializerT,stringT>::tst() : storage(new storage_type(16)), default_value() { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } /*************************** high-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return current_node->data; } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> bool tst<charT,valueT,storageT,serializerT,stringT>::contains(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return true; } else { return false; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::put(const stringT & string,valueT data) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; return storage->get(node_index)->store(data); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; tst_node<charT,valueT>* current_node=storage->get(node_index); valueT data = current_node->data; if(data==default_value) { data=factory->perform(string,0,current_node->data); current_node->store(data); return data; } else { return data; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove(const stringT & string) { remove_node(&root,string,0); if(root==UNDEFINED_INDEX) { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } } /**************************** low-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst_node<charT,valueT>* tst<charT,valueT,storageT,serializerT,stringT>::find_node(int* current_index,int* best_node,const stringT & string) const { tst_node<charT,valueT>* current_node; int diff; size_t pos=0; while(*current_index!=UNDEFINED_INDEX) { current_node=storage->get(*current_index); if(current_node->c==0) { *current_index=UNDEFINED_INDEX; return 0; } else { diff=string[pos]-(current_node->c); } if(diff==0) { if(current_node->data!=default_value) { *best_node=*current_index; } ++pos; if(pos<string.size()) { *current_index = current_node->next; } else { return current_node; } } else if(diff>0) { *current_index=current_node->right; } else { *current_index=current_node->left; } } return 0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> int tst<charT,valueT,storageT,serializerT,stringT>::build_node(node_info<charT,valueT>* current_node_info,const stringT & string,size_t current_position) { int diff,result; if(current_node_info->node->c==0) { current_node_info->node->c=string[current_position]; #ifdef SCANNER current_node_info->node->position=current_position; #endif diff=0; } else { diff=string[current_position]-(current_node_info->node->c); } current_node_info->height=-1; current_node_info->balance_performed=0; if(diff==0) { ++current_position; compute_height_and_balance(current_node_info); // TODO : est-ce bien necessaire ? if(current_position<string.size()) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->next; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->next = next_node_info.index; return result; } else { return current_node_info->index; } } else if(diff>0) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->right; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->right = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->left==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = next_node_info.height; current_node_info->left_balance = 0; current_node_info->right_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->left; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = next_node_info.height-other_node_info.height; current_node_info->left_balance = other_node_info.balance; current_node_info->right_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } else { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->left; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->left = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->right==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = -next_node_info.height; current_node_info->right_balance = 0; current_node_info->left_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->right; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = other_node_info.height-next_node_info.height; current_node_info->right_balance = other_node_info.balance; current_node_info->left_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove_node(int* current_index,const stringT & string,const size_t current_position) { tst_node<charT,valueT>* current_node = storage->get(*current_index); int diff,*next_index; if(current_node->c==0) { return; } else { diff=string[current_position]-(current_node->c); } if(diff==0) { if(current_position+1<string.size()) { next_index = &(current_node->next); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position+1); } } else { current_node->store(default_value); } } else if(diff>0) { next_index = &(current_node->right); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } else { next_index = &(current_node->left); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } current_node=storage->get(*current_index); if( current_node->data==default_value && current_node->next==UNDEFINED_INDEX && current_node->right==UNDEFINED_INDEX && current_node->left==UNDEFINED_INDEX) { storage->delete_node(*current_index); *current_index=UNDEFINED_INDEX; } else { node_info<charT,valueT> current_node_info; current_node_info.index=*current_index; current_node_info.node=current_node; current_node_info.height=-1; balance_node(&current_node_info); *current_index = current_node_info.index; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::balance_node(node_info<charT,valueT>* bal) { if(bal->height==-1) { compute_height_and_balance(bal); } bal->balance_performed=0; if(bal->balance>1) { if(bal->right_balance>0) { rr(bal); } else { rl(bal); } bal->balance_performed=1; } else if(bal->balance<-1) { if(bal->left_balance<0) { ll(bal); } else { lr(bal); } bal->balance_performed=1; } assert(abs(bal->balance)<2); assert(abs(bal->right_balance)<2); assert(abs(bal->left_balance)<2); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::ll(node_info<charT,valueT>* bal) { int left_index=bal->node->left; tst_node<charT,valueT>* left_node=storage->get(left_index); int left_right_index=left_node->right; bal->node->left=left_right_index; left_node->right=bal->index; bal->index=left_index; bal->node=storage->get(left_index); bal->height=bal->height-1; bal->balance=0; bal->right_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rr(node_info<charT,valueT>* bal) { int right_index=bal->node->right; tst_node<charT,valueT>* right_node=storage->get(right_index); int right_left_index=right_node->left; bal->node->right=right_left_index; right_node->left=bal->index; bal->index=right_index; bal->node=storage->get(right_index); bal->height=bal->height-1; bal->balance=0; bal->left_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::lr(node_info<charT,valueT>* bal) { node_info<charT,valueT> left; left.index = bal->node->left; left.node = storage->get(left.index); rr(&left); bal->node->left=left.index; ll(bal); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rl(node_info<charT,valueT>* bal) { node_info<charT,valueT> right; right.index = bal->node->right; right.node = storage->get(right.index); ll(&right); bal->node->right=right.index; rr(bal); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::compute_height_and_balance(node_info<charT,valueT>* current_node_info) const { int left = current_node_info->node->left; int right = current_node_info->node->right; if(right!=UNDEFINED_INDEX) { node_info<charT,valueT> right_balance; right_balance.index=right; right_balance.node=storage->get(right); compute_height_and_balance(&right_balance); if(left!=UNDEFINED_INDEX) { diff --git a/python/pythonTST.sln b/python/pythonTST.sln index 446475e..b0eaa73 100644 --- a/python/pythonTST.sln +++ b/python/pythonTST.sln @@ -1,27 +1,25 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pythonTST", "pythonTST.vcproj", "{A5208316-015E-4611-B812-6E2F7CCD33A2}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfiguration) = preSolution - Debug = Debug - Debug CRM = Debug CRM - Release = Release - Release CRM = Release CRM - EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {A5208316-015E-4611-B812-6E2F7CCD33A2}.Debug.ActiveCfg = Debug|Win32 - {A5208316-015E-4611-B812-6E2F7CCD33A2}.Debug.Build.0 = Debug|Win32 - {A5208316-015E-4611-B812-6E2F7CCD33A2}.Debug CRM.ActiveCfg = Debug CRM|Win32 - {A5208316-015E-4611-B812-6E2F7CCD33A2}.Debug CRM.Build.0 = Debug CRM|Win32 - {A5208316-015E-4611-B812-6E2F7CCD33A2}.Release.ActiveCfg = Release|Win32 - {A5208316-015E-4611-B812-6E2F7CCD33A2}.Release.Build.0 = Release|Win32 - {A5208316-015E-4611-B812-6E2F7CCD33A2}.Release CRM.ActiveCfg = Release CRM|Win32 - {A5208316-015E-4611-B812-6E2F7CCD33A2}.Release CRM.Build.0 = Release CRM|Win32 - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pythonTST", "pythonTST.vcproj", "{A5208316-015E-4611-B812-6E2F7CCD33A2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug CRM|Win32 = Debug CRM|Win32 + Debug|Win32 = Debug|Win32 + Release CRM|Win32 = Release CRM|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A5208316-015E-4611-B812-6E2F7CCD33A2}.Debug CRM|Win32.ActiveCfg = Debug CRM|Win32 + {A5208316-015E-4611-B812-6E2F7CCD33A2}.Debug CRM|Win32.Build.0 = Debug CRM|Win32 + {A5208316-015E-4611-B812-6E2F7CCD33A2}.Debug|Win32.ActiveCfg = Debug|Win32 + {A5208316-015E-4611-B812-6E2F7CCD33A2}.Debug|Win32.Build.0 = Debug|Win32 + {A5208316-015E-4611-B812-6E2F7CCD33A2}.Release CRM|Win32.ActiveCfg = Release CRM|Win32 + {A5208316-015E-4611-B812-6E2F7CCD33A2}.Release CRM|Win32.Build.0 = Release CRM|Win32 + {A5208316-015E-4611-B812-6E2F7CCD33A2}.Release|Win32.ActiveCfg = Release|Win32 + {A5208316-015E-4611-B812-6E2F7CCD33A2}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/python/pythonTST.vcproj b/python/pythonTST.vcproj index 9c877e9..d2a02e6 100644 --- a/python/pythonTST.vcproj +++ b/python/pythonTST.vcproj @@ -1,319 +1,457 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioProject - ProjectType="Visual C++" - Version="7.10" - Name="pythonTST" - ProjectGUID="{A5208316-015E-4611-B812-6E2F7CCD33A2}" - Keyword="Win32Proj"> - <Platforms> - <Platform - Name="Win32"/> - </Platforms> - <Configurations> - <Configuration - Name="Debug|Win32" - OutputDirectory="Debug" - IntermediateDirectory="Debug" - ConfigurationType="2" - UseOfMFC="0" - CharacterSet="2"> - <Tool - Name="VCCLCompilerTool" - Optimization="0" - AdditionalIncludeDirectories="D:\projets\python-svn\PC;D:\projets\python-svn\Include;..\include" - PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS;SCANNER" - MinimalRebuild="FALSE" - BasicRuntimeChecks="3" - RuntimeLibrary="1" - BufferSecurityCheck="TRUE" - RuntimeTypeInfo="TRUE" - UsePrecompiledHeader="0" - DebugInformationFormat="3"/> - <Tool - Name="VCCustomBuildTool"/> - <Tool - Name="VCLinkerTool" - OutputFile="$(OutDir)/_tst_d.pyd" - LinkIncremental="1" - AdditionalLibraryDirectories="&quot;D:\projets\python-svn\PCbuild&quot;" - GenerateDebugInformation="TRUE" - ProgramDatabaseFile="$(OutDir)/_tst_d.pdb" - GenerateMapFile="TRUE" - MapExports="TRUE" - MapLines="TRUE" - SubSystem="2" - ImportLibrary="$(OutDir)/pyd.lib" - TargetMachine="1"/> - <Tool - Name="VCMIDLTool"/> - <Tool - Name="VCPostBuildEventTool"/> - <Tool - Name="VCPreBuildEventTool"/> - <Tool - Name="VCPreLinkEventTool"/> - <Tool - Name="VCResourceCompilerTool"/> - <Tool - Name="VCWebServiceProxyGeneratorTool"/> - <Tool - Name="VCXMLDataGeneratorTool"/> - <Tool - Name="VCWebDeploymentTool"/> - <Tool - Name="VCManagedWrapperGeneratorTool"/> - <Tool - Name="VCAuxiliaryManagedWrapperGeneratorTool"/> - </Configuration> - <Configuration - Name="Release|Win32" - OutputDirectory="Release" - IntermediateDirectory="Release" - ConfigurationType="2" - CharacterSet="2" - WholeProgramOptimization="TRUE"> - <Tool - Name="VCCLCompilerTool" - Optimization="3" - GlobalOptimizations="TRUE" - InlineFunctionExpansion="2" - EnableIntrinsicFunctions="TRUE" - FavorSizeOrSpeed="1" - AdditionalIncludeDirectories="E:\Python24\include;..\include" - PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" - RuntimeLibrary="0" - StructMemberAlignment="1" - UsePrecompiledHeader="0" - WarningLevel="3" - Detect64BitPortabilityProblems="TRUE" - DebugInformationFormat="3"/> - <Tool - Name="VCCustomBuildTool"/> - <Tool - Name="VCLinkerTool" - OutputFile="$(OutDir)/_tst.pyd" - LinkIncremental="1" - AdditionalLibraryDirectories="E:\Python24\libs" - GenerateDebugInformation="TRUE" - SubSystem="2" - OptimizeReferences="2" - EnableCOMDATFolding="2" - ImportLibrary="$(OutDir)/pyd.lib" - TargetMachine="1"/> - <Tool - Name="VCMIDLTool"/> - <Tool - Name="VCPostBuildEventTool"/> - <Tool - Name="VCPreBuildEventTool"/> - <Tool - Name="VCPreLinkEventTool"/> - <Tool - Name="VCResourceCompilerTool"/> - <Tool - Name="VCWebServiceProxyGeneratorTool"/> - <Tool - Name="VCXMLDataGeneratorTool"/> - <Tool - Name="VCWebDeploymentTool"/> - <Tool - Name="VCManagedWrapperGeneratorTool"/> - <Tool - Name="VCAuxiliaryManagedWrapperGeneratorTool"/> - </Configuration> - <Configuration - Name="Debug CRM|Win32" - OutputDirectory="$(ConfigurationName)" - IntermediateDirectory="$(ConfigurationName)" - ConfigurationType="2" - UseOfMFC="0" - CharacterSet="2"> - <Tool - Name="VCCLCompilerTool" - Optimization="0" - AdditionalIncludeDirectories="&quot;D:\projets\python-cvs\dist\src\include&quot;;&quot;D:\projets\python-cvs\dist\src\PC&quot;;..\include" - PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" - MinimalRebuild="FALSE" - BasicRuntimeChecks="3" - RuntimeLibrary="1" - BufferSecurityCheck="TRUE" - RuntimeTypeInfo="TRUE" - UsePrecompiledHeader="0" - DebugInformationFormat="3"/> - <Tool - Name="VCCustomBuildTool"/> - <Tool - Name="VCLinkerTool" - OutputFile="$(OutDir)/_tst_d.pyd" - LinkIncremental="1" - AdditionalLibraryDirectories="&quot;D:\projets\python-cvs\dist\src\PCbuild&quot;" - GenerateDebugInformation="TRUE" - ProgramDatabaseFile="$(OutDir)/_tst_d.pdb" - GenerateMapFile="TRUE" - MapExports="TRUE" - MapLines="TRUE" - SubSystem="2" - ImportLibrary="$(OutDir)/pyd.lib" - TargetMachine="1"/> - <Tool - Name="VCMIDLTool"/> - <Tool - Name="VCPostBuildEventTool"/> - <Tool - Name="VCPreBuildEventTool"/> - <Tool - Name="VCPreLinkEventTool"/> - <Tool - Name="VCResourceCompilerTool"/> - <Tool - Name="VCWebServiceProxyGeneratorTool"/> - <Tool - Name="VCXMLDataGeneratorTool"/> - <Tool - Name="VCWebDeploymentTool"/> - <Tool - Name="VCManagedWrapperGeneratorTool"/> - <Tool - Name="VCAuxiliaryManagedWrapperGeneratorTool"/> - </Configuration> - <Configuration - Name="Release CRM|Win32" - OutputDirectory="$(ConfigurationName)" - IntermediateDirectory="$(ConfigurationName)" - ConfigurationType="2" - CharacterSet="2" - WholeProgramOptimization="TRUE"> - <Tool - Name="VCCLCompilerTool" - Optimization="3" - GlobalOptimizations="TRUE" - InlineFunctionExpansion="2" - EnableIntrinsicFunctions="TRUE" - FavorSizeOrSpeed="1" - AdditionalIncludeDirectories="C:\Python24\include;..\include" - PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" - RuntimeLibrary="0" - StructMemberAlignment="1" - UsePrecompiledHeader="0" - WarningLevel="3" - Detect64BitPortabilityProblems="TRUE" - DebugInformationFormat="3"/> - <Tool - Name="VCCustomBuildTool"/> - <Tool - Name="VCLinkerTool" - OutputFile="$(OutDir)/_tst.pyd" - LinkIncremental="1" - AdditionalLibraryDirectories="C:\Python24\libs" - GenerateDebugInformation="TRUE" - SubSystem="2" - OptimizeReferences="2" - EnableCOMDATFolding="2" - ImportLibrary="$(OutDir)/pyd.lib" - TargetMachine="1"/> - <Tool - Name="VCMIDLTool"/> - <Tool - Name="VCPostBuildEventTool"/> - <Tool - Name="VCPreBuildEventTool"/> - <Tool - Name="VCPreLinkEventTool"/> - <Tool - Name="VCResourceCompilerTool"/> - <Tool - Name="VCWebServiceProxyGeneratorTool"/> - <Tool - Name="VCXMLDataGeneratorTool"/> - <Tool - Name="VCWebDeploymentTool"/> - <Tool - Name="VCManagedWrapperGeneratorTool"/> - <Tool - Name="VCAuxiliaryManagedWrapperGeneratorTool"/> - </Configuration> - </Configurations> - <References> - </References> - <Files> - <Filter - Name="Source Files" - Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" - UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> - <File - RelativePath=".\bug.py"> - </File> - <File - RelativePath=".\setup.py"> - </File> - <File - RelativePath=".\tst.i"> - <FileConfiguration - Name="Debug|Win32"> - <Tool - Name="VCCustomBuildTool" - CommandLine="E:\swigwin-1.3.29\swig -c++ -O -DSCANNER -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)" - AdditionalDependencies="..\include\tst.h;pythonTST.h" - Outputs="tst_wrap.cxx"/> - </FileConfiguration> - <FileConfiguration - Name="Release|Win32"> - <Tool - Name="VCCustomBuildTool" - CommandLine="E:\SWIG-1.3.28\swig -O -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath) -" - AdditionalDependencies="..\tst.h;pythonTST.h" - Outputs="tst_wrap.cxx"/> - </FileConfiguration> - <FileConfiguration - Name="Debug CRM|Win32"> - <Tool - Name="VCCustomBuildTool" - CommandLine="C:\SWIG-1.3.24\swig -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath) -" - AdditionalDependencies="..\include\tst.h;pythonTST.h" - Outputs="tst_wrap.cxx"/> - </FileConfiguration> - <FileConfiguration - Name="Release CRM|Win32"> - <Tool - Name="VCCustomBuildTool" - CommandLine="C:\SWIG-1.3.24\swig -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath) -" - AdditionalDependencies="..\tst.h;pythonTST.h" - Outputs="tst_wrap.cxx"/> - </FileConfiguration> - </File> - <File - RelativePath=".\tst.py"> - </File> - <File - RelativePath=".\tst_wrap.cxx"> - </File> - </Filter> - <Filter - Name="Header Files" - Filter="h;hpp;hxx;hm;inl;inc;xsd" - UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"> - <File - RelativePath="..\include\debug.h"> - </File> - <File - RelativePath=".\PythonReference.h"> - </File> - <File - RelativePath=".\pythonTST.h"> - </File> - <File - RelativePath="..\include\tst.h"> - </File> - </Filter> - <Filter - Name="Resource Files" - Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx" - UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"> - </Filter> - </Files> - <Globals> - </Globals> -</VisualStudioProject> +<?xml version="1.0" encoding="Windows-1252"?> +<VisualStudioProject + ProjectType="Visual C++" + Version="9,00" + Name="pythonTST" + ProjectGUID="{A5208316-015E-4611-B812-6E2F7CCD33A2}" + RootNamespace="pythonTST" + Keyword="Win32Proj" + TargetFrameworkVersion="131072" + > + <Platforms> + <Platform + Name="Win32" + /> + </Platforms> + <ToolFiles> + </ToolFiles> + <Configurations> + <Configuration + Name="Debug|Win32" + OutputDirectory="Debug" + IntermediateDirectory="Debug" + ConfigurationType="2" + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + UseOfMFC="0" + CharacterSet="2" + > + <Tool + Name="VCPreBuildEventTool" + /> + <Tool + Name="VCCustomBuildTool" + /> + <Tool + Name="VCXMLDataGeneratorTool" + /> + <Tool + Name="VCWebServiceProxyGeneratorTool" + /> + <Tool + Name="VCMIDLTool" + /> + <Tool + Name="VCCLCompilerTool" + Optimization="0" + AdditionalIncludeDirectories="D:\projets\python-svn\PC;D:\projets\python-svn\Include;..\include" + PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS;SCANNER" + MinimalRebuild="false" + BasicRuntimeChecks="3" + RuntimeLibrary="1" + BufferSecurityCheck="true" + RuntimeTypeInfo="true" + UsePrecompiledHeader="0" + DebugInformationFormat="3" + /> + <Tool + Name="VCManagedResourceCompilerTool" + /> + <Tool + Name="VCResourceCompilerTool" + /> + <Tool + Name="VCPreLinkEventTool" + /> + <Tool + Name="VCLinkerTool" + OutputFile="$(OutDir)/_tst_d.pyd" + LinkIncremental="1" + AdditionalLibraryDirectories="&quot;D:\projets\python-svn\PCbuild&quot;" + GenerateDebugInformation="true" + ProgramDatabaseFile="$(OutDir)/_tst_d.pdb" + GenerateMapFile="true" + MapExports="true" + SubSystem="2" + RandomizedBaseAddress="1" + DataExecutionPrevention="0" + ImportLibrary="$(OutDir)/pyd.lib" + TargetMachine="1" + /> + <Tool + Name="VCALinkTool" + /> + <Tool + Name="VCManifestTool" + /> + <Tool + Name="VCXDCMakeTool" + /> + <Tool + Name="VCBscMakeTool" + /> + <Tool + Name="VCFxCopTool" + /> + <Tool + Name="VCAppVerifierTool" + /> + <Tool + Name="VCPostBuildEventTool" + /> + </Configuration> + <Configuration + Name="Release|Win32" + OutputDirectory="Release" + IntermediateDirectory="Release" + ConfigurationType="2" + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + WholeProgramOptimization="1" + > + <Tool + Name="VCPreBuildEventTool" + /> + <Tool + Name="VCCustomBuildTool" + /> + <Tool + Name="VCXMLDataGeneratorTool" + /> + <Tool + Name="VCWebServiceProxyGeneratorTool" + /> + <Tool + Name="VCMIDLTool" + /> + <Tool + Name="VCCLCompilerTool" + Optimization="3" + InlineFunctionExpansion="2" + EnableIntrinsicFunctions="true" + FavorSizeOrSpeed="1" + AdditionalIncludeDirectories="E:\Python24\include;..\include" + PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" + RuntimeLibrary="0" + StructMemberAlignment="1" + UsePrecompiledHeader="0" + WarningLevel="3" + Detect64BitPortabilityProblems="true" + DebugInformationFormat="3" + /> + <Tool + Name="VCManagedResourceCompilerTool" + /> + <Tool + Name="VCResourceCompilerTool" + /> + <Tool + Name="VCPreLinkEventTool" + /> + <Tool + Name="VCLinkerTool" + OutputFile="$(OutDir)/_tst.pyd" + LinkIncremental="1" + AdditionalLibraryDirectories="E:\Python24\libs" + GenerateDebugInformation="true" + SubSystem="2" + OptimizeReferences="2" + EnableCOMDATFolding="2" + RandomizedBaseAddress="1" + DataExecutionPrevention="0" + ImportLibrary="$(OutDir)/pyd.lib" + TargetMachine="1" + /> + <Tool + Name="VCALinkTool" + /> + <Tool + Name="VCManifestTool" + /> + <Tool + Name="VCXDCMakeTool" + /> + <Tool + Name="VCBscMakeTool" + /> + <Tool + Name="VCFxCopTool" + /> + <Tool + Name="VCAppVerifierTool" + /> + <Tool + Name="VCPostBuildEventTool" + /> + </Configuration> + <Configuration + Name="Debug CRM|Win32" + OutputDirectory="$(ConfigurationName)" + IntermediateDirectory="$(ConfigurationName)" + ConfigurationType="2" + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + UseOfMFC="0" + CharacterSet="2" + > + <Tool + Name="VCPreBuildEventTool" + /> + <Tool + Name="VCCustomBuildTool" + CommandLine="" + AdditionalDependencies="" + Outputs="" + /> + <Tool + Name="VCXMLDataGeneratorTool" + /> + <Tool + Name="VCWebServiceProxyGeneratorTool" + /> + <Tool + Name="VCMIDLTool" + /> + <Tool + Name="VCCLCompilerTool" + Optimization="0" + AdditionalIncludeDirectories="&quot;E:\projets\Python-2.6.4\include&quot;;&quot;E:\projets\Python-2.6.4\PC&quot;;..\include" + PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" + MinimalRebuild="false" + BasicRuntimeChecks="3" + RuntimeLibrary="1" + BufferSecurityCheck="true" + RuntimeTypeInfo="true" + UsePrecompiledHeader="0" + DebugInformationFormat="3" + /> + <Tool + Name="VCManagedResourceCompilerTool" + /> + <Tool + Name="VCResourceCompilerTool" + /> + <Tool + Name="VCPreLinkEventTool" + /> + <Tool + Name="VCLinkerTool" + OutputFile="$(OutDir)/_tst_d.pyd" + LinkIncremental="1" + AdditionalLibraryDirectories="&quot;E:\projets\Python-2.6.4\PCbuild&quot;" + GenerateDebugInformation="true" + ProgramDatabaseFile="$(OutDir)/_tst_d.pdb" + GenerateMapFile="true" + MapExports="true" + SubSystem="2" + RandomizedBaseAddress="1" + DataExecutionPrevention="0" + ImportLibrary="$(OutDir)/pyd.lib" + TargetMachine="1" + /> + <Tool + Name="VCALinkTool" + /> + <Tool + Name="VCManifestTool" + /> + <Tool + Name="VCXDCMakeTool" + /> + <Tool + Name="VCBscMakeTool" + /> + <Tool + Name="VCFxCopTool" + /> + <Tool + Name="VCAppVerifierTool" + /> + <Tool + Name="VCPostBuildEventTool" + /> + </Configuration> + <Configuration + Name="Release CRM|Win32" + OutputDirectory="$(ConfigurationName)" + IntermediateDirectory="$(ConfigurationName)" + ConfigurationType="2" + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + WholeProgramOptimization="1" + > + <Tool + Name="VCPreBuildEventTool" + /> + <Tool + Name="VCCustomBuildTool" + /> + <Tool + Name="VCXMLDataGeneratorTool" + /> + <Tool + Name="VCWebServiceProxyGeneratorTool" + /> + <Tool + Name="VCMIDLTool" + /> + <Tool + Name="VCCLCompilerTool" + Optimization="3" + InlineFunctionExpansion="2" + EnableIntrinsicFunctions="true" + FavorSizeOrSpeed="1" + AdditionalIncludeDirectories="C:\Python24\include;..\include" + PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;PYD_EXPORTS" + RuntimeLibrary="0" + StructMemberAlignment="1" + UsePrecompiledHeader="0" + WarningLevel="3" + Detect64BitPortabilityProblems="true" + DebugInformationFormat="3" + /> + <Tool + Name="VCManagedResourceCompilerTool" + /> + <Tool + Name="VCResourceCompilerTool" + /> + <Tool + Name="VCPreLinkEventTool" + /> + <Tool + Name="VCLinkerTool" + OutputFile="$(OutDir)/_tst.pyd" + LinkIncremental="1" + AdditionalLibraryDirectories="C:\Python24\libs" + GenerateDebugInformation="true" + SubSystem="2" + OptimizeReferences="2" + EnableCOMDATFolding="2" + RandomizedBaseAddress="1" + DataExecutionPrevention="0" + ImportLibrary="$(OutDir)/pyd.lib" + TargetMachine="1" + /> + <Tool + Name="VCALinkTool" + /> + <Tool + Name="VCManifestTool" + /> + <Tool + Name="VCXDCMakeTool" + /> + <Tool + Name="VCBscMakeTool" + /> + <Tool + Name="VCFxCopTool" + /> + <Tool + Name="VCAppVerifierTool" + /> + <Tool + Name="VCPostBuildEventTool" + /> + </Configuration> + </Configurations> + <References> + </References> + <Files> + <Filter + Name="Source Files" + Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" + UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}" + > + <File + RelativePath=".\bug.py" + > + </File> + <File + RelativePath=".\setup.py" + > + </File> + <File + RelativePath=".\tst.i" + > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCustomBuildTool" + CommandLine="E:\swigwin-1.3.40\swig -c++ -O -DSCANNER -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" + AdditionalDependencies="..\include\tst.h;pythonTST.h" + Outputs="tst_wrap.cxx" + /> + </FileConfiguration> + <FileConfiguration + Name="Release|Win32" + > + <Tool + Name="VCCustomBuildTool" + CommandLine="E:\swigwin-1.3.40\swig -O -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" + AdditionalDependencies="..\tst.h;pythonTST.h" + Outputs="tst_wrap.cxx" + /> + </FileConfiguration> + <FileConfiguration + Name="Debug CRM|Win32" + > + <Tool + Name="VCCustomBuildTool" + CommandLine="E:\swigwin-1.3.40\swig -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" + AdditionalDependencies="..\include\tst.h;pythonTST.h" + Outputs="tst_wrap.cxx" + /> + </FileConfiguration> + <FileConfiguration + Name="Release CRM|Win32" + > + <Tool + Name="VCCustomBuildTool" + CommandLine="E:\swigwin-1.3.40\swig -c++ -python -I..\include -o $(InputName)_wrap.cxx $(InputPath)&#x0D;&#x0A;" + AdditionalDependencies="..\tst.h;pythonTST.h" + Outputs="tst_wrap.cxx" + /> + </FileConfiguration> + </File> + <File + RelativePath=".\tst.py" + > + </File> + <File + RelativePath=".\tst_wrap.cxx" + > + </File> + </Filter> + <Filter + Name="Header Files" + Filter="h;hpp;hxx;hm;inl;inc;xsd" + UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" + > + <File + RelativePath="..\include\debug.h" + > + </File> + <File + RelativePath=".\PythonReference.h" + > + </File> + <File + RelativePath=".\pythonTST.h" + > + </File> + <File + RelativePath="..\include\tst.h" + > + </File> + </Filter> + <Filter + Name="Resource Files" + Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx" + UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}" + > + </Filter> + </Files> + <Globals> + </Globals> +</VisualStudioProject> diff --git a/python/setup.py b/python/setup.py index fa07548..da4bf76 100644 --- a/python/setup.py +++ b/python/setup.py @@ -1,49 +1,49 @@ - # $Id$ - # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> - # - # This library is free software; you can redistribute it and/or - # modify it under the terms of the GNU Lesser General Public - # License as published by the Free Software Foundation; either - # version 2.1 of the License, or (at your option) any later version. - # - # This library is distributed in the hope that it will be useful, - # but WITHOUT ANY WARRANTY; without even the implied warranty of - # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - # Lesser General Public License for more details. - # - # You should have received a copy of the GNU Lesser General Public - # License along with this library; if not, write to the Free Software - # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -from distutils.core import setup, Extension -import sys - -extra_compile_args = [] - -setup( - name = "pytst", - version = "1.17", - author = "Nicolas Lehuen", - author_email = "nicolas@lehuen.com", - url = "http://github.com/nlehuen/pytst", - description = "An implementation of a Ternary Search Tree (TST) in C++ with Python bindings", - py_modules = ["tst"], - ext_modules = [ - Extension( - "_tst", - ["tst_wrap.cxx"], - include_dirs=['../include'], - extra_compile_args = extra_compile_args, - define_macros=[('SCANNER', None),], - ) - ], - download_url = "http://github.com/nlehuen/pytst/downloads", - classifiers = [ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', - 'Programming Language :: C++', - 'Programming Language :: Python', - 'Topic :: Software Development :: Libraries :: Python Modules', - 'Topic :: Scientific/Engineering :: Information Analysis', - ] -) + # $Id$ + # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> + # + # This library is free software; you can redistribute it and/or + # modify it under the terms of the GNU Lesser General Public + # License as published by the Free Software Foundation; either + # version 2.1 of the License, or (at your option) any later version. + # + # This library is distributed in the hope that it will be useful, + # but WITHOUT ANY WARRANTY; without even the implied warranty of + # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + # Lesser General Public License for more details. + # + # You should have received a copy of the GNU Lesser General Public + # License along with this library; if not, write to the Free Software + # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +from distutils.core import setup, Extension +import sys + +extra_compile_args = [] + +setup( + name = "pytst", + version = "1.18RC", + author = "Nicolas Lehuen", + author_email = "nicolas@lehuen.com", + url = "http://github.com/nlehuen/pytst", + description = "An implementation of a Ternary Search Tree (TST) in C++ with Python bindings", + py_modules = ["tst"], + ext_modules = [ + Extension( + "_tst", + ["tst_wrap.cxx"], + include_dirs=['../include'], + extra_compile_args = extra_compile_args, + define_macros=[('SCANNER', None),], + ) + ], + download_url = "http://github.com/nlehuen/pytst/downloads", + classifiers = [ + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', + 'Programming Language :: C++', + 'Programming Language :: Python', + 'Topic :: Software Development :: Libraries :: Python Modules', + 'Topic :: Scientific/Engineering :: Information Analysis', + ] +) diff --git a/python/tst.py b/python/tst.py index 569f8fc..3bd1789 100644 --- a/python/tst.py +++ b/python/tst.py @@ -1,569 +1,585 @@ # This file was automatically generated by SWIG (http://www.swig.org). # Version 1.3.40 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. # This file is compatible with both classic and new-style classes. from sys import version_info if version_info >= (2,6,0): def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module('_tst', [dirname(__file__)]) except ImportError: import _tst return _tst if fp is not None: try: _mod = imp.load_module('_tst', fp, pathname, description) finally: fp.close() return _mod _tst = swig_import_helper() del swig_import_helper else: import _tst del version_info try: _swig_property = property except NameError: pass # Python < 2.2 doesn't have 'property'. def _swig_setattr_nondynamic(self,class_type,name,value,static=1): if (name == "thisown"): return self.this.own(value) if (name == "this"): if type(value).__name__ == 'SwigPyObject': self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name,None) if method: return method(self,value) if (not static) or hasattr(self,name): self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self,class_type,name,value): return _swig_setattr_nondynamic(self,class_type,name,value,0) def _swig_getattr(self,class_type,name): if (name == "thisown"): return self.this.own() method = class_type.__swig_getmethods__.get(name,None) if method: return method(self) raise AttributeError(name) def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) try: _object = object _newclass = 1 except AttributeError: class _object : pass _newclass = 0 class TSTException(_object): """Proxy of C++ TSTException class""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, TSTException, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, TSTException, name) __repr__ = _swig_repr def __init__(self, *args): """__init__(self, char _message) -> TSTException""" this = _tst.new_TSTException(*args) try: self.this.append(this) except: self.this = this def what(self): """what(self) -> char""" return _tst.TSTException_what(self) __swig_destroy__ = _tst.delete_TSTException __del__ = lambda self : None; TSTException_swigregister = _tst.TSTException_swigregister TSTException_swigregister(TSTException) cvar = _tst.cvar TST_VERSION = cvar.TST_VERSION UNDEFINED_INDEX = cvar.UNDEFINED_INDEX class _TST(_object): """Proxy of C++ tst<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,string_type)> class""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, _TST, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, _TST, name) __repr__ = _swig_repr def __init__(self): """__init__(self) -> _TST""" this = _tst.new__TST() try: self.this.append(this) except: self.this = this __swig_destroy__ = _tst.delete__TST __del__ = lambda self : None; def pack(self): """pack(self)""" return _tst._TST_pack(self) def walk(self, *args): """ walk(self, _Filter filter, _Action to_perform) -> PythonReference walk(self, _Filter filter, _Action to_perform, string_type string) -> PythonReference """ return _tst._TST_walk(self, *args) def close_match(self, *args): """ close_match(self, string_type string, int maximum_distance, _Filter filter, _Action to_perform) -> PythonReference """ return _tst._TST_close_match(self, *args) def prefix_match(self, *args): """prefix_match(self, string_type string, _Filter filter, _Action to_perform) -> PythonReference""" return _tst._TST_prefix_match(self, *args) def match(self, *args): """match(self, string_type string, _Filter filter, _Action to_perform) -> PythonReference""" return _tst._TST_match(self, *args) def get(self, *args): """get(self, string_type string) -> PythonReference""" return _tst._TST_get(self, *args) def get_or_build(self, *args): """get_or_build(self, string_type string, _Filter factory) -> PythonReference""" return _tst._TST_get_or_build(self, *args) def put(self, *args): """put(self, string_type string, PythonReference data) -> PythonReference""" return _tst._TST_put(self, *args) def remove(self, *args): """remove(self, string_type string)""" return _tst._TST_remove(self, *args) def contains(self, *args): """contains(self, string_type string) -> bool""" return _tst._TST_contains(self, *args) def write(self, *args): """write(self, std::ostream file)""" return _tst._TST_write(self, *args) def read(self, *args): """read(self, std::istream file)""" return _tst._TST_read(self, *args) def iterator(self, *args): """ iterator(self) -> _lexical_iterator_type iterator(self, string_type string) -> _lexical_iterator_type """ return _tst._TST_iterator(self, *args) def close_match_iterator(self, *args): """close_match_iterator(self, string_type string, int distance) -> _close_match_iterator_type""" return _tst._TST_close_match_iterator(self, *args) def get_number_of_nodes(self): """get_number_of_nodes(self) -> int""" return _tst._TST_get_number_of_nodes(self) def get_default_value(self): """get_default_value(self) -> PythonReference""" return _tst._TST_get_default_value(self) + def scan(self, *args): + """scan(self, string_type string, _Action to_perform) -> PythonReference""" + return _tst._TST_scan(self, *args) + + def scan_with_stop_chars(self, *args): + """scan_with_stop_chars(self, string_type string, string_type stop_chars, _Action to_perform) -> PythonReference""" + return _tst._TST_scan_with_stop_chars(self, *args) + _TST_swigregister = _tst._TST_swigregister _TST_swigregister(_TST) class _Action(_object): """Proxy of C++ tst_action<(char,PythonReference,string_type)> class""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, _Action, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, _Action, name) def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract") __repr__ = _swig_repr __swig_destroy__ = _tst.delete__Action __del__ = lambda self : None; def perform(self, *args): """perform(self, string_type string, int remaining_distance, PythonReference data)""" return _tst._Action_perform(self, *args) def result(self): """result(self) -> PythonReference""" return _tst._Action_result(self) _Action_swigregister = _tst._Action_swigregister _Action_swigregister(_Action) class _Filter(_object): """Proxy of C++ tst_filter<(char,PythonReference,string_type)> class""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, _Filter, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, _Filter, name) def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract") __repr__ = _swig_repr __swig_destroy__ = _tst.delete__Filter __del__ = lambda self : None; def perform(self, *args): """perform(self, string_type string, int remaining_distance, PythonReference data) -> PythonReference""" return _tst._Filter_perform(self, *args) _Filter_swigregister = _tst._Filter_swigregister _Filter_swigregister(_Filter) class CallableAction(_Action): """Proxy of C++ CallableAction class""" __swig_setmethods__ = {} for _s in [_Action]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{})) __setattr__ = lambda self, name, value: _swig_setattr(self, CallableAction, name, value) __swig_getmethods__ = {} for _s in [_Action]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{})) __getattr__ = lambda self, name: _swig_getattr(self, CallableAction, name) __repr__ = _swig_repr def __init__(self, *args): """__init__(self, PythonReference perform, PythonReference result) -> CallableAction""" this = _tst.new_CallableAction(*args) try: self.this.append(this) except: self.this = this __swig_destroy__ = _tst.delete_CallableAction __del__ = lambda self : None; def perform(self, *args): """perform(self, string_type string, int remaining_distance, PythonReference data)""" return _tst.CallableAction_perform(self, *args) def result(self): """result(self) -> PythonReference""" return _tst.CallableAction_result(self) CallableAction_swigregister = _tst.CallableAction_swigregister CallableAction_swigregister(CallableAction) class CallableFilter(_Filter): """Proxy of C++ CallableFilter class""" __swig_setmethods__ = {} for _s in [_Filter]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{})) __setattr__ = lambda self, name, value: _swig_setattr(self, CallableFilter, name, value) __swig_getmethods__ = {} for _s in [_Filter]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{})) __getattr__ = lambda self, name: _swig_getattr(self, CallableFilter, name) __repr__ = _swig_repr def __init__(self, *args): """__init__(self, PythonReference _callable) -> CallableFilter""" this = _tst.new_CallableFilter(*args) try: self.this.append(this) except: self.this = this __swig_destroy__ = _tst.delete_CallableFilter __del__ = lambda self : None; def perform(self, *args): """perform(self, string_type string, int remaining_distance, PythonReference data) -> PythonReference""" return _tst.CallableFilter_perform(self, *args) CallableFilter_swigregister = _tst.CallableFilter_swigregister CallableFilter_swigregister(CallableFilter) class DictAction(_Action): """Proxy of C++ DictAction class""" __swig_setmethods__ = {} for _s in [_Action]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{})) __setattr__ = lambda self, name, value: _swig_setattr(self, DictAction, name, value) __swig_getmethods__ = {} for _s in [_Action]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{})) __getattr__ = lambda self, name: _swig_getattr(self, DictAction, name) __repr__ = _swig_repr def __init__(self): """__init__(self) -> DictAction""" this = _tst.new_DictAction() try: self.this.append(this) except: self.this = this __swig_destroy__ = _tst.delete_DictAction __del__ = lambda self : None; def perform(self, *args): """perform(self, string_type string, int remaining_distance, PythonReference data)""" return _tst.DictAction_perform(self, *args) def result(self): """result(self) -> PythonReference""" return _tst.DictAction_result(self) DictAction_swigregister = _tst.DictAction_swigregister DictAction_swigregister(DictAction) class ListAction(_Action): """Proxy of C++ ListAction class""" __swig_setmethods__ = {} for _s in [_Action]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{})) __setattr__ = lambda self, name, value: _swig_setattr(self, ListAction, name, value) __swig_getmethods__ = {} for _s in [_Action]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{})) __getattr__ = lambda self, name: _swig_getattr(self, ListAction, name) __repr__ = _swig_repr def __init__(self): """__init__(self) -> ListAction""" this = _tst.new_ListAction() try: self.this.append(this) except: self.this = this __swig_destroy__ = _tst.delete_ListAction __del__ = lambda self : None; def perform(self, *args): """perform(self, string_type string, int remaining_distance, PythonReference data)""" return _tst.ListAction_perform(self, *args) def result(self): """result(self) -> PythonReference""" return _tst.ListAction_result(self) ListAction_swigregister = _tst.ListAction_swigregister ListAction_swigregister(ListAction) class TupleListAction(_Action): """Proxy of C++ TupleListAction class""" __swig_setmethods__ = {} for _s in [_Action]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{})) __setattr__ = lambda self, name, value: _swig_setattr(self, TupleListAction, name, value) __swig_getmethods__ = {} for _s in [_Action]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{})) __getattr__ = lambda self, name: _swig_getattr(self, TupleListAction, name) __repr__ = _swig_repr def __init__(self): """__init__(self) -> TupleListAction""" this = _tst.new_TupleListAction() try: self.this.append(this) except: self.this = this __swig_destroy__ = _tst.delete_TupleListAction __del__ = lambda self : None; def perform(self, *args): """perform(self, string_type string, int remaining_distance, PythonReference data)""" return _tst.TupleListAction_perform(self, *args) def result(self): """result(self) -> PythonReference""" return _tst.TupleListAction_result(self) TupleListAction_swigregister = _tst.TupleListAction_swigregister TupleListAction_swigregister(TupleListAction) class ObjectSerializer(_object): """Proxy of C++ ObjectSerializer class""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, ObjectSerializer, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, ObjectSerializer, name) __repr__ = _swig_repr def __init__(self): """__init__(self) -> ObjectSerializer""" this = _tst.new_ObjectSerializer() try: self.this.append(this) except: self.this = this def write(self, *args): """write(self, std::ostream file, PythonReference data)""" return _tst.ObjectSerializer_write(self, *args) def read(self, *args): """read(self, std::istream file) -> PythonReference""" return _tst.ObjectSerializer_read(self, *args) __swig_destroy__ = _tst.delete_ObjectSerializer __del__ = lambda self : None; ObjectSerializer_swigregister = _tst.ObjectSerializer_swigregister ObjectSerializer_swigregister(ObjectSerializer) class TST(_TST): """Proxy of C++ TST class""" __swig_setmethods__ = {} for _s in [_TST]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{})) __setattr__ = lambda self, name, value: _swig_setattr(self, TST, name, value) __swig_getmethods__ = {} for _s in [_TST]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{})) __getattr__ = lambda self, name: _swig_getattr(self, TST, name) __repr__ = _swig_repr def __init__(self): """__init__(self) -> TST""" this = _tst.new_TST() try: self.this.append(this) except: self.this = this __swig_destroy__ = _tst.delete_TST __del__ = lambda self : None; def write_to_file(self, *args): """write_to_file(self, PythonReference file) -> PythonReference""" return _tst.TST_write_to_file(self, *args) def read_from_file(self, *args): """read_from_file(self, PythonReference file) -> PythonReference""" return _tst.TST_read_from_file(self, *args) def __getitem__(self, *args): """__getitem__(self, string_type string) -> PythonReference""" return _tst.TST___getitem__(self, *args) def __setitem__(self, *args): """__setitem__(self, string_type string, PythonReference data) -> PythonReference""" return _tst.TST___setitem__(self, *args) def __delitem__(self, *args): """__delitem__(self, string_type string)""" return _tst.TST___delitem__(self, *args) def __contains__(self, *args): """__contains__(self, string_type string) -> PythonReference""" return _tst.TST___contains__(self, *args) def __iter__(self): """__iter__(self) -> TSTLexicalIterator""" return _tst.TST___iter__(self) def iterator(self, *args): """ iterator(self) -> TSTLexicalIterator iterator(self, string_type string) -> TSTLexicalIterator """ return _tst.TST_iterator(self, *args) def close_match_iterator(self, *args): """close_match_iterator(self, string_type string, int distance) -> TSTCloseMatchIterator""" return _tst.TST_close_match_iterator(self, *args) def put(self, *args): """put(self, string_type string, PythonReference data) -> PythonReference""" return _tst.TST_put(self, *args) def get(self, *args): """get(self, string_type string) -> PythonReference""" return _tst.TST_get(self, *args) def pack(self): """pack(self)""" return _tst.TST_pack(self) def walk(self, *args): """ walk(self, _Filter filter, _Action to_perform) -> PythonReference walk(self, _Filter filter, _Action to_perform, string_type string) -> PythonReference """ return _tst.TST_walk(self, *args) def close_match(self, *args): """ close_match(self, string_type string, int maximum_distance, _Filter filter, _Action to_perform) -> PythonReference """ return _tst.TST_close_match(self, *args) def match(self, *args): """match(self, string_type string, _Filter filter, _Action to_perform) -> PythonReference""" return _tst.TST_match(self, *args) + def scan(self, *args): + """scan(self, string_type string, _Action to_perform) -> PythonReference""" + return _tst.TST_scan(self, *args) + + def scan_with_stop_chars(self, *args): + """scan_with_stop_chars(self, string_type string, string_type stop_chars, _Action to_perform) -> PythonReference""" + return _tst.TST_scan_with_stop_chars(self, *args) + TST_swigregister = _tst.TST_swigregister TST_swigregister(TST) class _lexical_iterator_type(_object): """Proxy of C++ lexical_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,string_type)> class""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, _lexical_iterator_type, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, _lexical_iterator_type, name) __repr__ = _swig_repr state_left = _tst._lexical_iterator_type_state_left state_current = _tst._lexical_iterator_type_state_current state_right = _tst._lexical_iterator_type_state_right state_end = _tst._lexical_iterator_type_state_end def __init__(self, *args): """ __init__(self, tst<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)> t, qad_string<(char)> key, int root) -> _lexical_iterator_type """ this = _tst.new__lexical_iterator_type(*args) try: self.this.append(this) except: self.this = this def next(self): """next(self) -> lexical_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)>::value_type""" return _tst._lexical_iterator_type_next(self) __swig_destroy__ = _tst.delete__lexical_iterator_type __del__ = lambda self : None; _lexical_iterator_type_swigregister = _tst._lexical_iterator_type_swigregister _lexical_iterator_type_swigregister(_lexical_iterator_type) class _close_match_iterator_type(_object): """Proxy of C++ match_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,string_type)> class""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, _close_match_iterator_type, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, _close_match_iterator_type, name) __repr__ = _swig_repr state_left = _tst._close_match_iterator_type_state_left state_current = _tst._close_match_iterator_type_state_current state_skip_input = _tst._close_match_iterator_type_state_skip_input state_skip_base = _tst._close_match_iterator_type_state_skip_base state_right = _tst._close_match_iterator_type_state_right state_end = _tst._close_match_iterator_type_state_end def __init__(self, *args): """ __init__(self, tst<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)> t, qad_string<(char)> string, int distance, int root) -> _close_match_iterator_type """ this = _tst.new__close_match_iterator_type(*args) try: self.this.append(this) except: self.this = this def next(self): """next(self) -> match_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)>::value_type""" return _tst._close_match_iterator_type_next(self) __swig_destroy__ = _tst.delete__close_match_iterator_type __del__ = lambda self : None; _close_match_iterator_type_swigregister = _tst._close_match_iterator_type_swigregister _close_match_iterator_type_swigregister(_close_match_iterator_type) class TSTLexicalIterator(_object): """Proxy of C++ TSTIterator<(lexical_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,string_type)>)> class""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, TSTLexicalIterator, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, TSTLexicalIterator, name) def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr def __iter__(self): """__iter__(self) -> TSTLexicalIterator""" return _tst.TSTLexicalIterator___iter__(self) def next(self): """next(self) -> PyObject""" return _tst.TSTLexicalIterator_next(self) __swig_destroy__ = _tst.delete_TSTLexicalIterator __del__ = lambda self : None; TSTLexicalIterator_swigregister = _tst.TSTLexicalIterator_swigregister TSTLexicalIterator_swigregister(TSTLexicalIterator) class TSTCloseMatchIterator(_object): """Proxy of C++ TSTIterator<(match_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,string_type)>)> class""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, TSTCloseMatchIterator, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, TSTCloseMatchIterator, name) def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr def __iter__(self): """__iter__(self) -> TSTCloseMatchIterator""" return _tst.TSTCloseMatchIterator___iter__(self) def next(self): """next(self) -> PyObject""" return _tst.TSTCloseMatchIterator_next(self) __swig_destroy__ = _tst.delete_TSTCloseMatchIterator __del__ = lambda self : None; TSTCloseMatchIterator_swigregister = _tst.TSTCloseMatchIterator_swigregister TSTCloseMatchIterator_swigregister(TSTCloseMatchIterator) diff --git a/python/tst_wrap.cxx b/python/tst_wrap.cxx index 866fed8..48b4677 100644 --- a/python/tst_wrap.cxx +++ b/python/tst_wrap.cxx @@ -3857,1024 +3857,1160 @@ fail: SWIGINTERN PyObject *_wrap__TST_put(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; PythonReference arg3 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PythonReference result; if (!PyArg_ParseTuple(args,(char *)"OOO:_TST_put",&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_put" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; Py_ssize_t size; PyString_AsStringAndSize(obj1,&buffer,&size); arg2 = new string_type(buffer,size); } { arg3 = PythonReference(obj2); } { try { result = (arg1)->put((string_type const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_remove(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:_TST_remove",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_remove" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; Py_ssize_t size; PyString_AsStringAndSize(obj1,&buffer,&size); arg2 = new string_type(buffer,size); } { try { (arg1)->remove((string_type const &)*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_contains(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; bool result; if (!PyArg_ParseTuple(args,(char *)"OO:_TST_contains",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_contains" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; Py_ssize_t size; PyString_AsStringAndSize(obj1,&buffer,&size); arg2 = new string_type(buffer,size); } { try { result = (bool)((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->contains((string_type const &)*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_From_bool(static_cast< bool >(result)); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_write(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; std::ostream *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:_TST_write",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_write" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2, SWIGTYPE_p_std__ostream, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "_TST_write" "', argument " "2"" of type '" "std::ostream &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "_TST_write" "', argument " "2"" of type '" "std::ostream &""'"); } arg2 = reinterpret_cast< std::ostream * >(argp2); { try { ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->write(*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_read(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; std::istream *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:_TST_read",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_read" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2, SWIGTYPE_p_std__istream, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "_TST_read" "', argument " "2"" of type '" "std::istream &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "_TST_read" "', argument " "2"" of type '" "std::istream &""'"); } arg2 = reinterpret_cast< std::istream * >(argp2); { try { (arg1)->read(*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_iterator__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; SwigValueWrapper< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > result; if (!PyArg_ParseTuple(args,(char *)"O:_TST_iterator",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_iterator" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->iterator(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >(static_cast< const lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >& >(result))), SWIGTYPE_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_iterator__SWIG_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; SwigValueWrapper< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > result; if (!PyArg_ParseTuple(args,(char *)"OO:_TST_iterator",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_iterator" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; Py_ssize_t size; PyString_AsStringAndSize(obj1,&buffer,&size); arg2 = new string_type(buffer,size); } { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->iterator((string_type const &)*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >(static_cast< const lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >& >(result))), SWIGTYPE_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_OWN | 0 ); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_iterator(PyObject *self, PyObject *args) { int argc; PyObject *argv[3]; int ii; if (!PyTuple_Check(args)) SWIG_fail; argc = (int)PyObject_Length(args); for (ii = 0; (ii < argc) && (ii < 2); ii++) { argv[ii] = PyTuple_GET_ITEM(args,ii); } if (argc == 1) { int _v; void *vptr = 0; int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0); _v = SWIG_CheckState(res); if (_v) { return _wrap__TST_iterator__SWIG_0(self, args); } } if (argc == 2) { int _v; void *vptr = 0; int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0); _v = SWIG_CheckState(res); if (_v) { int res = SWIG_ConvertPtr(argv[1], 0, SWIGTYPE_p_qad_stringT_char_t, 0); _v = SWIG_CheckState(res); if (_v) { return _wrap__TST_iterator__SWIG_1(self, args); } } } fail: SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function '_TST_iterator'.\n" " Possible C/C++ prototypes are:\n" " iterator(tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)\n" " iterator(tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *,string_type const &)\n"); return NULL; } SWIGINTERN PyObject *_wrap__TST_close_match_iterator(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; int arg3 ; void *argp1 = 0 ; int res1 = 0 ; int val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; SwigValueWrapper< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > result; if (!PyArg_ParseTuple(args,(char *)"OOO:_TST_close_match_iterator",&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_close_match_iterator" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; Py_ssize_t size; PyString_AsStringAndSize(obj1,&buffer,&size); arg2 = new string_type(buffer,size); } ecode3 = SWIG_AsVal_int(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "_TST_close_match_iterator" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->close_match_iterator((string_type const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >(static_cast< const match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >& >(result))), SWIGTYPE_p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_OWN | 0 ); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_get_number_of_nodes(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; int result; if (!PyArg_ParseTuple(args,(char *)"O:_TST_get_number_of_nodes",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_get_number_of_nodes" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { result = (int)((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->get_number_of_nodes(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_From_int(static_cast< int >(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_get_default_value(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; PythonReference result; if (!PyArg_ParseTuple(args,(char *)"O:_TST_get_default_value",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_get_default_value" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->get_default_value(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } return resultobj; fail: return NULL; } +SWIGINTERN PyObject *_wrap__TST_scan(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; + string_type *arg2 = 0 ; + tst_action< char,PythonReference,string_type > *arg3 = (tst_action< char,PythonReference,string_type > *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp3 = 0 ; + int res3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PythonReference result; + + if (!PyArg_ParseTuple(args,(char *)"OOO:_TST_scan",&obj0,&obj1,&obj2)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_scan" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); + } + arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); + { + char* buffer; + Py_ssize_t size; + PyString_AsStringAndSize(obj1,&buffer,&size); + arg2 = new string_type(buffer,size); + } + res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "_TST_scan" "', argument " "3"" of type '" "tst_action< char,PythonReference,string_type > *""'"); + } + arg3 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp3); + { + try { + result = (arg1)->scan((string_type const &)*arg2,arg3); + } + catch (TSTException &e) { + PyErr_SetString(PyExc_RuntimeError,e.what()); + SWIG_fail; + } + catch (PythonException &e) { + if(!PyErr_Occurred()) { + PyErr_SetString(PyExc_RuntimeError,e.what()); + } + SWIG_fail; + } + } + { + resultobj = (&result)->lend(); + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap__TST_scan_with_stop_chars(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; + string_type *arg2 = 0 ; + string_type *arg3 = 0 ; + tst_action< char,PythonReference,string_type > *arg4 = (tst_action< char,PythonReference,string_type > *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp4 = 0 ; + int res4 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PythonReference result; + + if (!PyArg_ParseTuple(args,(char *)"OOOO:_TST_scan_with_stop_chars",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_scan_with_stop_chars" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); + } + arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); + { + char* buffer; + Py_ssize_t size; + PyString_AsStringAndSize(obj1,&buffer,&size); + arg2 = new string_type(buffer,size); + } + { + char* buffer; + Py_ssize_t size; + PyString_AsStringAndSize(obj2,&buffer,&size); + arg3 = new string_type(buffer,size); + } + res4 = SWIG_ConvertPtr(obj3, &argp4,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); + if (!SWIG_IsOK(res4)) { + SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "_TST_scan_with_stop_chars" "', argument " "4"" of type '" "tst_action< char,PythonReference,string_type > *""'"); + } + arg4 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp4); + { + try { + result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->scan_with_stop_chars((string_type const &)*arg2,(string_type const &)*arg3,arg4); + } + catch (TSTException &e) { + PyErr_SetString(PyExc_RuntimeError,e.what()); + SWIG_fail; + } + catch (PythonException &e) { + if(!PyErr_Occurred()) { + PyErr_SetString(PyExc_RuntimeError,e.what()); + } + SWIG_fail; + } + } + { + resultobj = (&result)->lend(); + } + { + delete arg2; + } + { + delete arg3; + } + return resultobj; +fail: + { + delete arg2; + } + { + delete arg3; + } + return NULL; +} + + SWIGINTERN PyObject *_TST_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_delete__Action(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst_action< char,PythonReference,string_type > *arg1 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete__Action",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete__Action" "', argument " "1"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg1 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__Action_perform(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst_action< char,PythonReference,string_type > *arg1 = (tst_action< char,PythonReference,string_type > *) 0 ; string_type *arg2 = 0 ; int arg3 ; PythonReference arg4 ; void *argp1 = 0 ; int res1 = 0 ; int val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OOOO:_Action_perform",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_Action_perform" "', argument " "1"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg1 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp1); { char* buffer; Py_ssize_t size; PyString_AsStringAndSize(obj1,&buffer,&size); arg2 = new string_type(buffer,size); } ecode3 = SWIG_AsVal_int(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "_Action_perform" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); { arg4 = PythonReference(obj3); } { try { (arg1)->perform((string_type const &)*arg2,arg3,arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__Action_result(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst_action< char,PythonReference,string_type > *arg1 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; PythonReference result; if (!PyArg_ParseTuple(args,(char *)"O:_Action_result",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_Action_result" "', argument " "1"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg1 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp1); { try { result = (arg1)->result(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_Action_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_delete__Filter(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst_filter< char,PythonReference,string_type > *arg1 = (tst_filter< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete__Filter",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete__Filter" "', argument " "1"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg1 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__Filter_perform(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst_filter< char,PythonReference,string_type > *arg1 = (tst_filter< char,PythonReference,string_type > *) 0 ; string_type *arg2 = 0 ; int arg3 ; PythonReference arg4 ; void *argp1 = 0 ; int res1 = 0 ; int val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; PythonReference result; if (!PyArg_ParseTuple(args,(char *)"OOOO:_Filter_perform",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_Filter_perform" "', argument " "1"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg1 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp1); { char* buffer; Py_ssize_t size; PyString_AsStringAndSize(obj1,&buffer,&size); arg2 = new string_type(buffer,size); } ecode3 = SWIG_AsVal_int(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "_Filter_perform" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); { arg4 = PythonReference(obj3); } { try { result = (arg1)->perform((string_type const &)*arg2,arg3,arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_Filter_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_new_CallableAction(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; PythonReference arg1 ; PythonReference arg2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; CallableAction *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:new_CallableAction",&obj0,&obj1)) SWIG_fail; { arg1 = PythonReference(obj0); } { arg2 = PythonReference(obj1); } { try { result = (CallableAction *)new CallableAction(arg1,arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_CallableAction, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_CallableAction(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; CallableAction *arg1 = (CallableAction *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete_CallableAction",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_CallableAction, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_CallableAction" "', argument " "1"" of type '" "CallableAction *""'"); } arg1 = reinterpret_cast< CallableAction * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_CallableAction_perform(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; CallableAction *arg1 = (CallableAction *) 0 ; string_type *arg2 = 0 ; int arg3 ; PythonReference arg4 ; void *argp1 = 0 ; int res1 = 0 ; int val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OOOO:CallableAction_perform",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_CallableAction, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "CallableAction_perform" "', argument " "1"" of type '" "CallableAction *""'"); } arg1 = reinterpret_cast< CallableAction * >(argp1); { char* buffer; Py_ssize_t size; PyString_AsStringAndSize(obj1,&buffer,&size); arg2 = new string_type(buffer,size); } ecode3 = SWIG_AsVal_int(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "CallableAction_perform" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); { arg4 = PythonReference(obj3); } { try { (arg1)->perform((string_type const &)*arg2,arg3,arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_CallableAction_result(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; CallableAction *arg1 = (CallableAction *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; PythonReference result; if (!PyArg_ParseTuple(args,(char *)"O:CallableAction_result",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_CallableAction, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "CallableAction_result" "', argument " "1"" of type '" "CallableAction *""'"); } arg1 = reinterpret_cast< CallableAction * >(argp1); { try { result = (arg1)->result(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *CallableAction_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_CallableAction, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_new_CallableFilter(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; PythonReference arg1 ; PyObject * obj0 = 0 ; CallableFilter *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:new_CallableFilter",&obj0)) SWIG_fail; { arg1 = PythonReference(obj0); } { try { result = (CallableFilter *)new CallableFilter(arg1); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_CallableFilter, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_CallableFilter(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; CallableFilter *arg1 = (CallableFilter *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete_CallableFilter",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_CallableFilter, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_CallableFilter" "', argument " "1"" of type '" "CallableFilter *""'"); } arg1 = reinterpret_cast< CallableFilter * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_CallableFilter_perform(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; CallableFilter *arg1 = (CallableFilter *) 0 ; string_type *arg2 = 0 ; int arg3 ; PythonReference arg4 ; void *argp1 = 0 ; @@ -6178,1655 +6314,1801 @@ SWIGINTERN PyObject *_wrap_TST_close_match_iterator(PyObject *SWIGUNUSEDPARM(sel SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "TST_close_match_iterator" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); { try { result = (arg1)->close_match_iterator((string_type const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new TSTCloseMatchIterator(static_cast< const TSTCloseMatchIterator& >(result))), SWIGTYPE_p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_POINTER_OWN | 0 ); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST_put(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; PythonReference arg3 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PythonReference result; if (!PyArg_ParseTuple(args,(char *)"OOO:TST_put",&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_put" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; Py_ssize_t size; PyString_AsStringAndSize(obj1,&buffer,&size); arg2 = new string_type(buffer,size); } { arg3 = PythonReference(obj2); } { try { result = (arg1)->put((string_type const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PythonReference result; if (!PyArg_ParseTuple(args,(char *)"OO:TST_get",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_get" "', argument " "1"" of type '" "TST const *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; Py_ssize_t size; PyString_AsStringAndSize(obj1,&buffer,&size); arg2 = new string_type(buffer,size); } { try { result = ((TST const *)arg1)->get((string_type const &)*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST_pack(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:TST_pack",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_pack" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { try { (arg1)->pack(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_TST_walk_SWIG_0_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; tst_filter< char,PythonReference,string_type > *arg2 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg3 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PythonReference result; if (!PyArg_ParseTuple(args,(char *)"OOO:TST_walk",&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_walk" "', argument " "1"" of type '" "TST const *""'"); } arg1 = reinterpret_cast< TST * >(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "TST_walk" "', argument " "2"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg2 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp2); res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "TST_walk" "', argument " "3"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp3); { try { result = ((TST const *)arg1)->walk(arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_TST_walk_SWIG_0_1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; tst_filter< char,PythonReference,string_type > *arg2 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg3 = (tst_action< char,PythonReference,string_type > *) 0 ; string_type *arg4 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; PythonReference result; if (!PyArg_ParseTuple(args,(char *)"OOOO:TST_walk",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_walk" "', argument " "1"" of type '" "TST const *""'"); } arg1 = reinterpret_cast< TST * >(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "TST_walk" "', argument " "2"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg2 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp2); res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "TST_walk" "', argument " "3"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp3); { char* buffer; Py_ssize_t size; PyString_AsStringAndSize(obj3,&buffer,&size); arg4 = new string_type(buffer,size); } { try { result = ((TST const *)arg1)->walk(arg2,arg3,(string_type const &)*arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg4; } return resultobj; fail: { delete arg4; } return NULL; } SWIGINTERN PyObject *_wrap_TST_walk(PyObject *self, PyObject *args) { int argc; PyObject *argv[5]; int ii; if (!PyTuple_Check(args)) SWIG_fail; argc = (int)PyObject_Length(args); for (ii = 0; (ii < argc) && (ii < 4); ii++) { argv[ii] = PyTuple_GET_ITEM(args,ii); } if (argc == 3) { int _v; void *vptr = 0; int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_TST, 0); _v = SWIG_CheckState(res); if (_v) { void *vptr = 0; int res = SWIG_ConvertPtr(argv[1], &vptr, SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0); _v = SWIG_CheckState(res); if (_v) { void *vptr = 0; int res = SWIG_ConvertPtr(argv[2], &vptr, SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0); _v = SWIG_CheckState(res); if (_v) { return _wrap_TST_walk_SWIG_0_0(self, args); } } } } if (argc == 4) { int _v; void *vptr = 0; int res = SWIG_ConvertPtr(argv[0], &vptr, SWIGTYPE_p_TST, 0); _v = SWIG_CheckState(res); if (_v) { void *vptr = 0; int res = SWIG_ConvertPtr(argv[1], &vptr, SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0); _v = SWIG_CheckState(res); if (_v) { void *vptr = 0; int res = SWIG_ConvertPtr(argv[2], &vptr, SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0); _v = SWIG_CheckState(res); if (_v) { int res = SWIG_ConvertPtr(argv[3], 0, SWIGTYPE_p_qad_stringT_char_t, 0); _v = SWIG_CheckState(res); if (_v) { return _wrap_TST_walk_SWIG_0_1(self, args); } } } } } fail: SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'TST_walk'.\n" " Possible C/C++ prototypes are:\n" " walk(TST const *,tst_filter< char,PythonReference,string_type > *,tst_action< char,PythonReference,string_type > *)\n" " walk(TST const *,tst_filter< char,PythonReference,string_type > *,tst_action< char,PythonReference,string_type > *,string_type const &)\n"); return NULL; } SWIGINTERN PyObject *_wrap_TST_close_match(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; int arg3 ; tst_filter< char,PythonReference,string_type > *arg4 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg5 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int val3 ; int ecode3 = 0 ; void *argp4 = 0 ; int res4 = 0 ; void *argp5 = 0 ; int res5 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; PyObject * obj4 = 0 ; PythonReference result; if (!PyArg_ParseTuple(args,(char *)"OOOOO:TST_close_match",&obj0,&obj1,&obj2,&obj3,&obj4)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_close_match" "', argument " "1"" of type '" "TST const *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; Py_ssize_t size; PyString_AsStringAndSize(obj1,&buffer,&size); arg2 = new string_type(buffer,size); } ecode3 = SWIG_AsVal_int(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "TST_close_match" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); res4 = SWIG_ConvertPtr(obj3, &argp4,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "TST_close_match" "', argument " "4"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg4 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp4); res5 = SWIG_ConvertPtr(obj4, &argp5,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res5)) { SWIG_exception_fail(SWIG_ArgError(res5), "in method '" "TST_close_match" "', argument " "5"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg5 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp5); { try { result = ((TST const *)arg1)->close_match((string_type const &)*arg2,arg3,arg4,arg5); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST_match(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; tst_filter< char,PythonReference,string_type > *arg3 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg4 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp3 = 0 ; int res3 = 0 ; void *argp4 = 0 ; int res4 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; PythonReference result; if (!PyArg_ParseTuple(args,(char *)"OOOO:TST_match",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_match" "', argument " "1"" of type '" "TST const *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; Py_ssize_t size; PyString_AsStringAndSize(obj1,&buffer,&size); arg2 = new string_type(buffer,size); } res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "TST_match" "', argument " "3"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp3); res4 = SWIG_ConvertPtr(obj3, &argp4,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "TST_match" "', argument " "4"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg4 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp4); { try { result = ((TST const *)arg1)->match((string_type const &)*arg2,arg3,arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } +SWIGINTERN PyObject *_wrap_TST_scan(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + TST *arg1 = (TST *) 0 ; + string_type *arg2 = 0 ; + tst_action< char,PythonReference,string_type > *arg3 = (tst_action< char,PythonReference,string_type > *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp3 = 0 ; + int res3 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PythonReference result; + + if (!PyArg_ParseTuple(args,(char *)"OOO:TST_scan",&obj0,&obj1,&obj2)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TST, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_scan" "', argument " "1"" of type '" "TST *""'"); + } + arg1 = reinterpret_cast< TST * >(argp1); + { + char* buffer; + Py_ssize_t size; + PyString_AsStringAndSize(obj1,&buffer,&size); + arg2 = new string_type(buffer,size); + } + res3 = SWIG_ConvertPtr(obj2, &argp3,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); + if (!SWIG_IsOK(res3)) { + SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "TST_scan" "', argument " "3"" of type '" "tst_action< char,PythonReference,string_type > *""'"); + } + arg3 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp3); + { + try { + result = (arg1)->scan((string_type const &)*arg2,arg3); + } + catch (TSTException &e) { + PyErr_SetString(PyExc_RuntimeError,e.what()); + SWIG_fail; + } + catch (PythonException &e) { + if(!PyErr_Occurred()) { + PyErr_SetString(PyExc_RuntimeError,e.what()); + } + SWIG_fail; + } + } + { + resultobj = (&result)->lend(); + } + { + delete arg2; + } + return resultobj; +fail: + { + delete arg2; + } + return NULL; +} + + +SWIGINTERN PyObject *_wrap_TST_scan_with_stop_chars(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { + PyObject *resultobj = 0; + TST *arg1 = (TST *) 0 ; + string_type *arg2 = 0 ; + string_type *arg3 = 0 ; + tst_action< char,PythonReference,string_type > *arg4 = (tst_action< char,PythonReference,string_type > *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + void *argp4 = 0 ; + int res4 = 0 ; + PyObject * obj0 = 0 ; + PyObject * obj1 = 0 ; + PyObject * obj2 = 0 ; + PyObject * obj3 = 0 ; + PythonReference result; + + if (!PyArg_ParseTuple(args,(char *)"OOOO:TST_scan_with_stop_chars",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TST, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_scan_with_stop_chars" "', argument " "1"" of type '" "TST const *""'"); + } + arg1 = reinterpret_cast< TST * >(argp1); + { + char* buffer; + Py_ssize_t size; + PyString_AsStringAndSize(obj1,&buffer,&size); + arg2 = new string_type(buffer,size); + } + { + char* buffer; + Py_ssize_t size; + PyString_AsStringAndSize(obj2,&buffer,&size); + arg3 = new string_type(buffer,size); + } + res4 = SWIG_ConvertPtr(obj3, &argp4,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); + if (!SWIG_IsOK(res4)) { + SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "TST_scan_with_stop_chars" "', argument " "4"" of type '" "tst_action< char,PythonReference,string_type > *""'"); + } + arg4 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp4); + { + try { + result = ((TST const *)arg1)->scan_with_stop_chars((string_type const &)*arg2,(string_type const &)*arg3,arg4); + } + catch (TSTException &e) { + PyErr_SetString(PyExc_RuntimeError,e.what()); + SWIG_fail; + } + catch (PythonException &e) { + if(!PyErr_Occurred()) { + PyErr_SetString(PyExc_RuntimeError,e.what()); + } + SWIG_fail; + } + } + { + resultobj = (&result)->lend(); + } + { + delete arg2; + } + { + delete arg3; + } + return resultobj; +fail: + { + delete arg2; + } + { + delete arg3; + } + return NULL; +} + + SWIGINTERN PyObject *TST_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_TST, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_new__lexical_iterator_type(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *) 0 ; qad_string< char > *arg2 = 0 ; int arg3 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; int val3 ; int ecode3 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"OOO:new__lexical_iterator_type",&obj0,&obj1,&obj2)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new__lexical_iterator_type" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > * >(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2, SWIGTYPE_p_qad_stringT_char_t, 0 | 0); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "new__lexical_iterator_type" "', argument " "2"" of type '" "qad_string< char > const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new__lexical_iterator_type" "', argument " "2"" of type '" "qad_string< char > const &""'"); } arg2 = reinterpret_cast< qad_string< char > * >(argp2); ecode3 = SWIG_AsVal_int(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "new__lexical_iterator_type" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); { try { result = (lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *)new lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > const *)arg1,(qad_string< char > const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__lexical_iterator_type_next(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type result; if (!PyArg_ParseTuple(args,(char *)"O:_lexical_iterator_type_next",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_lexical_iterator_type_next" "', argument " "1"" of type '" "lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { result = (arg1)->next(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type(static_cast< const lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type& >(result))), SWIGTYPE_p_std__pairT_qad_stringT_char_t_PythonReference_p_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete__lexical_iterator_type(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete__lexical_iterator_type",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete__lexical_iterator_type" "', argument " "1"" of type '" "lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_lexical_iterator_type_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_new__close_match_iterator_type(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *) 0 ; qad_string< char > *arg2 = 0 ; int arg3 ; int arg4 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; int val3 ; int ecode3 = 0 ; int val4 ; int ecode4 = 0 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"OOOO:new__close_match_iterator_type",&obj0,&obj1,&obj2,&obj3)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new__close_match_iterator_type" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > * >(argp1); res2 = SWIG_ConvertPtr(obj1, &argp2, SWIGTYPE_p_qad_stringT_char_t, 0 | 0); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "new__close_match_iterator_type" "', argument " "2"" of type '" "qad_string< char > const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new__close_match_iterator_type" "', argument " "2"" of type '" "qad_string< char > const &""'"); } arg2 = reinterpret_cast< qad_string< char > * >(argp2); ecode3 = SWIG_AsVal_int(obj2, &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "new__close_match_iterator_type" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); ecode4 = SWIG_AsVal_int(obj3, &val4); if (!SWIG_IsOK(ecode4)) { SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "new__close_match_iterator_type" "', argument " "4"" of type '" "int""'"); } arg4 = static_cast< int >(val4); { try { result = (match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *)new match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > const *)arg1,(qad_string< char > const &)*arg2,arg3,arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__close_match_iterator_type_next(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type result; if (!PyArg_ParseTuple(args,(char *)"O:_close_match_iterator_type_next",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_close_match_iterator_type_next" "', argument " "1"" of type '" "match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { result = (arg1)->next(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type(static_cast< const match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type& >(result))), SWIGTYPE_p_std__pairT_qad_stringT_char_t_PythonReference_p_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete__close_match_iterator_type(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete__close_match_iterator_type",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete__close_match_iterator_type" "', argument " "1"" of type '" "match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_close_match_iterator_type_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_TSTLexicalIterator___iter__(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *arg1 = (TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; SwigValueWrapper< TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > > result; if (!PyArg_ParseTuple(args,(char *)"O:TSTLexicalIterator___iter__",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TSTLexicalIterator___iter__" "', argument " "1"" of type '" "TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *""'"); } arg1 = reinterpret_cast< TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > * >(argp1); { try { result = (arg1)->__iter__(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > >(static_cast< const TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > >& >(result))), SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_TSTLexicalIterator_next(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *arg1 = (TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; PyObject *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:TSTLexicalIterator_next",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TSTLexicalIterator_next" "', argument " "1"" of type '" "TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *""'"); } arg1 = reinterpret_cast< TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > * >(argp1); { try { result = (PyObject *)(arg1)->next(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = result; return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_TSTLexicalIterator(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *arg1 = (TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete_TSTLexicalIterator",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_TSTLexicalIterator" "', argument " "1"" of type '" "TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *""'"); } arg1 = reinterpret_cast< TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *TSTLexicalIterator_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_TSTCloseMatchIterator___iter__(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *arg1 = (TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; SwigValueWrapper< TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > > result; if (!PyArg_ParseTuple(args,(char *)"O:TSTCloseMatchIterator___iter__",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TSTCloseMatchIterator___iter__" "', argument " "1"" of type '" "TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *""'"); } arg1 = reinterpret_cast< TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > * >(argp1); { try { result = (arg1)->__iter__(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > >(static_cast< const TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > >& >(result))), SWIGTYPE_p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_TSTCloseMatchIterator_next(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *arg1 = (TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; PyObject *result = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:TSTCloseMatchIterator_next",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TSTCloseMatchIterator_next" "', argument " "1"" of type '" "TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *""'"); } arg1 = reinterpret_cast< TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > * >(argp1); { try { result = (PyObject *)(arg1)->next(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = result; return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_TSTCloseMatchIterator(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *arg1 = (TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:delete_TSTCloseMatchIterator",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_TSTCloseMatchIterator" "', argument " "1"" of type '" "TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *""'"); } arg1 = reinterpret_cast< TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *TSTCloseMatchIterator_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!PyArg_ParseTuple(args,(char*)"O:swigregister", &obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } static PyMethodDef SwigMethods[] = { { (char *)"SWIG_PyInstanceMethod_New", (PyCFunction)SWIG_PyInstanceMethod_New, METH_O, NULL}, { (char *)"new_TSTException", _wrap_new_TSTException, METH_VARARGS, (char *)"new_TSTException(char _message) -> TSTException"}, { (char *)"TSTException_what", _wrap_TSTException_what, METH_VARARGS, (char *)"TSTException_what(TSTException self) -> char"}, { (char *)"delete_TSTException", _wrap_delete_TSTException, METH_VARARGS, (char *)"delete_TSTException(TSTException self)"}, { (char *)"TSTException_swigregister", TSTException_swigregister, METH_VARARGS, NULL}, { (char *)"new__TST", _wrap_new__TST, METH_VARARGS, (char *)"new__TST() -> _TST"}, { (char *)"delete__TST", _wrap_delete__TST, METH_VARARGS, (char *)"delete__TST(_TST self)"}, { (char *)"_TST_pack", _wrap__TST_pack, METH_VARARGS, (char *)"_TST_pack(_TST self)"}, { (char *)"_TST_walk", _wrap__TST_walk, METH_VARARGS, (char *)"\n" "walk(_Filter filter, _Action to_perform) -> PythonReference\n" "_TST_walk(_TST self, _Filter filter, _Action to_perform, string_type string) -> PythonReference\n" ""}, { (char *)"_TST_close_match", _wrap__TST_close_match, METH_VARARGS, (char *)"\n" "_TST_close_match(_TST self, string_type string, int maximum_distance, \n" " _Filter filter, _Action to_perform) -> PythonReference\n" ""}, { (char *)"_TST_prefix_match", _wrap__TST_prefix_match, METH_VARARGS, (char *)"_TST_prefix_match(_TST self, string_type string, _Filter filter, _Action to_perform) -> PythonReference"}, { (char *)"_TST_match", _wrap__TST_match, METH_VARARGS, (char *)"_TST_match(_TST self, string_type string, _Filter filter, _Action to_perform) -> PythonReference"}, { (char *)"_TST_get", _wrap__TST_get, METH_VARARGS, (char *)"_TST_get(_TST self, string_type string) -> PythonReference"}, { (char *)"_TST_get_or_build", _wrap__TST_get_or_build, METH_VARARGS, (char *)"_TST_get_or_build(_TST self, string_type string, _Filter factory) -> PythonReference"}, { (char *)"_TST_put", _wrap__TST_put, METH_VARARGS, (char *)"_TST_put(_TST self, string_type string, PythonReference data) -> PythonReference"}, { (char *)"_TST_remove", _wrap__TST_remove, METH_VARARGS, (char *)"_TST_remove(_TST self, string_type string)"}, { (char *)"_TST_contains", _wrap__TST_contains, METH_VARARGS, (char *)"_TST_contains(_TST self, string_type string) -> bool"}, { (char *)"_TST_write", _wrap__TST_write, METH_VARARGS, (char *)"_TST_write(_TST self, std::ostream file)"}, { (char *)"_TST_read", _wrap__TST_read, METH_VARARGS, (char *)"_TST_read(_TST self, std::istream file)"}, { (char *)"_TST_iterator", _wrap__TST_iterator, METH_VARARGS, (char *)"\n" "iterator() -> _lexical_iterator_type\n" "_TST_iterator(_TST self, string_type string) -> _lexical_iterator_type\n" ""}, { (char *)"_TST_close_match_iterator", _wrap__TST_close_match_iterator, METH_VARARGS, (char *)"_TST_close_match_iterator(_TST self, string_type string, int distance) -> _close_match_iterator_type"}, { (char *)"_TST_get_number_of_nodes", _wrap__TST_get_number_of_nodes, METH_VARARGS, (char *)"_TST_get_number_of_nodes(_TST self) -> int"}, { (char *)"_TST_get_default_value", _wrap__TST_get_default_value, METH_VARARGS, (char *)"_TST_get_default_value(_TST self) -> PythonReference"}, + { (char *)"_TST_scan", _wrap__TST_scan, METH_VARARGS, (char *)"_TST_scan(_TST self, string_type string, _Action to_perform) -> PythonReference"}, + { (char *)"_TST_scan_with_stop_chars", _wrap__TST_scan_with_stop_chars, METH_VARARGS, (char *)"\n" + "_TST_scan_with_stop_chars(_TST self, string_type string, string_type stop_chars, \n" + " _Action to_perform) -> PythonReference\n" + ""}, { (char *)"_TST_swigregister", _TST_swigregister, METH_VARARGS, NULL}, { (char *)"delete__Action", _wrap_delete__Action, METH_VARARGS, (char *)"delete__Action(_Action self)"}, { (char *)"_Action_perform", _wrap__Action_perform, METH_VARARGS, (char *)"\n" "_Action_perform(_Action self, string_type string, int remaining_distance, \n" " PythonReference data)\n" ""}, { (char *)"_Action_result", _wrap__Action_result, METH_VARARGS, (char *)"_Action_result(_Action self) -> PythonReference"}, { (char *)"_Action_swigregister", _Action_swigregister, METH_VARARGS, NULL}, { (char *)"delete__Filter", _wrap_delete__Filter, METH_VARARGS, (char *)"delete__Filter(_Filter self)"}, { (char *)"_Filter_perform", _wrap__Filter_perform, METH_VARARGS, (char *)"\n" "_Filter_perform(_Filter self, string_type string, int remaining_distance, \n" " PythonReference data) -> PythonReference\n" ""}, { (char *)"_Filter_swigregister", _Filter_swigregister, METH_VARARGS, NULL}, { (char *)"new_CallableAction", _wrap_new_CallableAction, METH_VARARGS, (char *)"new_CallableAction(PythonReference perform, PythonReference result) -> CallableAction"}, { (char *)"delete_CallableAction", _wrap_delete_CallableAction, METH_VARARGS, (char *)"delete_CallableAction(CallableAction self)"}, { (char *)"CallableAction_perform", _wrap_CallableAction_perform, METH_VARARGS, (char *)"\n" "CallableAction_perform(CallableAction self, string_type string, int remaining_distance, \n" " PythonReference data)\n" ""}, { (char *)"CallableAction_result", _wrap_CallableAction_result, METH_VARARGS, (char *)"CallableAction_result(CallableAction self) -> PythonReference"}, { (char *)"CallableAction_swigregister", CallableAction_swigregister, METH_VARARGS, NULL}, { (char *)"new_CallableFilter", _wrap_new_CallableFilter, METH_VARARGS, (char *)"new_CallableFilter(PythonReference _callable) -> CallableFilter"}, { (char *)"delete_CallableFilter", _wrap_delete_CallableFilter, METH_VARARGS, (char *)"delete_CallableFilter(CallableFilter self)"}, { (char *)"CallableFilter_perform", _wrap_CallableFilter_perform, METH_VARARGS, (char *)"\n" "CallableFilter_perform(CallableFilter self, string_type string, int remaining_distance, \n" " PythonReference data) -> PythonReference\n" ""}, { (char *)"CallableFilter_swigregister", CallableFilter_swigregister, METH_VARARGS, NULL}, { (char *)"new_DictAction", _wrap_new_DictAction, METH_VARARGS, (char *)"new_DictAction() -> DictAction"}, { (char *)"delete_DictAction", _wrap_delete_DictAction, METH_VARARGS, (char *)"delete_DictAction(DictAction self)"}, { (char *)"DictAction_perform", _wrap_DictAction_perform, METH_VARARGS, (char *)"\n" "DictAction_perform(DictAction self, string_type string, int remaining_distance, \n" " PythonReference data)\n" ""}, { (char *)"DictAction_result", _wrap_DictAction_result, METH_VARARGS, (char *)"DictAction_result(DictAction self) -> PythonReference"}, { (char *)"DictAction_swigregister", DictAction_swigregister, METH_VARARGS, NULL}, { (char *)"new_ListAction", _wrap_new_ListAction, METH_VARARGS, (char *)"new_ListAction() -> ListAction"}, { (char *)"delete_ListAction", _wrap_delete_ListAction, METH_VARARGS, (char *)"delete_ListAction(ListAction self)"}, { (char *)"ListAction_perform", _wrap_ListAction_perform, METH_VARARGS, (char *)"\n" "ListAction_perform(ListAction self, string_type string, int remaining_distance, \n" " PythonReference data)\n" ""}, { (char *)"ListAction_result", _wrap_ListAction_result, METH_VARARGS, (char *)"ListAction_result(ListAction self) -> PythonReference"}, { (char *)"ListAction_swigregister", ListAction_swigregister, METH_VARARGS, NULL}, { (char *)"new_TupleListAction", _wrap_new_TupleListAction, METH_VARARGS, (char *)"new_TupleListAction() -> TupleListAction"}, { (char *)"delete_TupleListAction", _wrap_delete_TupleListAction, METH_VARARGS, (char *)"delete_TupleListAction(TupleListAction self)"}, { (char *)"TupleListAction_perform", _wrap_TupleListAction_perform, METH_VARARGS, (char *)"\n" "TupleListAction_perform(TupleListAction self, string_type string, int remaining_distance, \n" " PythonReference data)\n" ""}, { (char *)"TupleListAction_result", _wrap_TupleListAction_result, METH_VARARGS, (char *)"TupleListAction_result(TupleListAction self) -> PythonReference"}, { (char *)"TupleListAction_swigregister", TupleListAction_swigregister, METH_VARARGS, NULL}, { (char *)"new_ObjectSerializer", _wrap_new_ObjectSerializer, METH_VARARGS, (char *)"new_ObjectSerializer() -> ObjectSerializer"}, { (char *)"ObjectSerializer_write", _wrap_ObjectSerializer_write, METH_VARARGS, (char *)"ObjectSerializer_write(ObjectSerializer self, std::ostream file, PythonReference data)"}, { (char *)"ObjectSerializer_read", _wrap_ObjectSerializer_read, METH_VARARGS, (char *)"ObjectSerializer_read(ObjectSerializer self, std::istream file) -> PythonReference"}, { (char *)"delete_ObjectSerializer", _wrap_delete_ObjectSerializer, METH_VARARGS, (char *)"delete_ObjectSerializer(ObjectSerializer self)"}, { (char *)"ObjectSerializer_swigregister", ObjectSerializer_swigregister, METH_VARARGS, NULL}, { (char *)"new_TST", _wrap_new_TST, METH_VARARGS, (char *)"new_TST() -> TST"}, { (char *)"delete_TST", _wrap_delete_TST, METH_VARARGS, (char *)"delete_TST(TST self)"}, { (char *)"TST_write_to_file", _wrap_TST_write_to_file, METH_VARARGS, (char *)"TST_write_to_file(TST self, PythonReference file) -> PythonReference"}, { (char *)"TST_read_from_file", _wrap_TST_read_from_file, METH_VARARGS, (char *)"TST_read_from_file(TST self, PythonReference file) -> PythonReference"}, { (char *)"TST___getitem__", _wrap_TST___getitem__, METH_VARARGS, (char *)"TST___getitem__(TST self, string_type string) -> PythonReference"}, { (char *)"TST___setitem__", _wrap_TST___setitem__, METH_VARARGS, (char *)"TST___setitem__(TST self, string_type string, PythonReference data) -> PythonReference"}, { (char *)"TST___delitem__", _wrap_TST___delitem__, METH_VARARGS, (char *)"TST___delitem__(TST self, string_type string)"}, { (char *)"TST___contains__", _wrap_TST___contains__, METH_VARARGS, (char *)"TST___contains__(TST self, string_type string) -> PythonReference"}, { (char *)"TST___iter__", _wrap_TST___iter__, METH_VARARGS, (char *)"TST___iter__(TST self) -> TSTLexicalIterator"}, { (char *)"TST_iterator", _wrap_TST_iterator, METH_VARARGS, (char *)"\n" "iterator() -> TSTLexicalIterator\n" "TST_iterator(TST self, string_type string) -> TSTLexicalIterator\n" ""}, { (char *)"TST_close_match_iterator", _wrap_TST_close_match_iterator, METH_VARARGS, (char *)"TST_close_match_iterator(TST self, string_type string, int distance) -> TSTCloseMatchIterator"}, { (char *)"TST_put", _wrap_TST_put, METH_VARARGS, (char *)"TST_put(TST self, string_type string, PythonReference data) -> PythonReference"}, { (char *)"TST_get", _wrap_TST_get, METH_VARARGS, (char *)"TST_get(TST self, string_type string) -> PythonReference"}, { (char *)"TST_pack", _wrap_TST_pack, METH_VARARGS, (char *)"TST_pack(TST self)"}, { (char *)"TST_walk", _wrap_TST_walk, METH_VARARGS, (char *)"\n" "walk(_Filter filter, _Action to_perform) -> PythonReference\n" "TST_walk(TST self, _Filter filter, _Action to_perform, string_type string) -> PythonReference\n" ""}, { (char *)"TST_close_match", _wrap_TST_close_match, METH_VARARGS, (char *)"\n" "TST_close_match(TST self, string_type string, int maximum_distance, \n" " _Filter filter, _Action to_perform) -> PythonReference\n" ""}, { (char *)"TST_match", _wrap_TST_match, METH_VARARGS, (char *)"TST_match(TST self, string_type string, _Filter filter, _Action to_perform) -> PythonReference"}, + { (char *)"TST_scan", _wrap_TST_scan, METH_VARARGS, (char *)"TST_scan(TST self, string_type string, _Action to_perform) -> PythonReference"}, + { (char *)"TST_scan_with_stop_chars", _wrap_TST_scan_with_stop_chars, METH_VARARGS, (char *)"\n" + "TST_scan_with_stop_chars(TST self, string_type string, string_type stop_chars, \n" + " _Action to_perform) -> PythonReference\n" + ""}, { (char *)"TST_swigregister", TST_swigregister, METH_VARARGS, NULL}, { (char *)"new__lexical_iterator_type", _wrap_new__lexical_iterator_type, METH_VARARGS, (char *)"\n" "new__lexical_iterator_type(tst<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)> t, \n" " qad_string<(char)> key, \n" " int root) -> _lexical_iterator_type\n" ""}, { (char *)"_lexical_iterator_type_next", _wrap__lexical_iterator_type_next, METH_VARARGS, (char *)"_lexical_iterator_type_next(_lexical_iterator_type self) -> lexical_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)>::value_type"}, { (char *)"delete__lexical_iterator_type", _wrap_delete__lexical_iterator_type, METH_VARARGS, (char *)"delete__lexical_iterator_type(_lexical_iterator_type self)"}, { (char *)"_lexical_iterator_type_swigregister", _lexical_iterator_type_swigregister, METH_VARARGS, NULL}, { (char *)"new__close_match_iterator_type", _wrap_new__close_match_iterator_type, METH_VARARGS, (char *)"\n" "new__close_match_iterator_type(tst<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)> t, \n" " qad_string<(char)> string, \n" " int distance, \n" " int root) -> _close_match_iterator_type\n" ""}, { (char *)"_close_match_iterator_type_next", _wrap__close_match_iterator_type_next, METH_VARARGS, (char *)"_close_match_iterator_type_next(_close_match_iterator_type self) -> match_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)>::value_type"}, { (char *)"delete__close_match_iterator_type", _wrap_delete__close_match_iterator_type, METH_VARARGS, (char *)"delete__close_match_iterator_type(_close_match_iterator_type self)"}, { (char *)"_close_match_iterator_type_swigregister", _close_match_iterator_type_swigregister, METH_VARARGS, NULL}, { (char *)"TSTLexicalIterator___iter__", _wrap_TSTLexicalIterator___iter__, METH_VARARGS, (char *)"TSTLexicalIterator___iter__(TSTLexicalIterator self) -> TSTLexicalIterator"}, { (char *)"TSTLexicalIterator_next", _wrap_TSTLexicalIterator_next, METH_VARARGS, (char *)"TSTLexicalIterator_next(TSTLexicalIterator self) -> PyObject"}, { (char *)"delete_TSTLexicalIterator", _wrap_delete_TSTLexicalIterator, METH_VARARGS, (char *)"delete_TSTLexicalIterator(TSTLexicalIterator self)"}, { (char *)"TSTLexicalIterator_swigregister", TSTLexicalIterator_swigregister, METH_VARARGS, NULL}, { (char *)"TSTCloseMatchIterator___iter__", _wrap_TSTCloseMatchIterator___iter__, METH_VARARGS, (char *)"TSTCloseMatchIterator___iter__(TSTCloseMatchIterator self) -> TSTCloseMatchIterator"}, { (char *)"TSTCloseMatchIterator_next", _wrap_TSTCloseMatchIterator_next, METH_VARARGS, (char *)"TSTCloseMatchIterator_next(TSTCloseMatchIterator self) -> PyObject"}, { (char *)"delete_TSTCloseMatchIterator", _wrap_delete_TSTCloseMatchIterator, METH_VARARGS, (char *)"delete_TSTCloseMatchIterator(TSTCloseMatchIterator self)"}, { (char *)"TSTCloseMatchIterator_swigregister", TSTCloseMatchIterator_swigregister, METH_VARARGS, NULL}, { NULL, NULL, 0, NULL } }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ static void *_p_CallableFilterTo_p_tst_filterT_char_PythonReference_string_type_t(void *x, int *SWIGUNUSEDPARM(newmemory)) { return (void *)((tst_filter< char,PythonReference,string_type > *) ((CallableFilter *) x)); } static void *_p_DictActionTo_p_tst_actionT_char_PythonReference_string_type_t(void *x, int *SWIGUNUSEDPARM(newmemory)) { return (void *)((tst_action< char,PythonReference,string_type > *) ((DictAction *) x)); } static void *_p_ListActionTo_p_tst_actionT_char_PythonReference_string_type_t(void *x, int *SWIGUNUSEDPARM(newmemory)) { return (void *)((tst_action< char,PythonReference,string_type > *) ((ListAction *) x)); } static void *_p_TupleListActionTo_p_tst_actionT_char_PythonReference_string_type_t(void *x, int *SWIGUNUSEDPARM(newmemory)) { return (void *)((tst_action< char,PythonReference,string_type > *) ((TupleListAction *) x)); } static void *_p_CallableActionTo_p_tst_actionT_char_PythonReference_string_type_t(void *x, int *SWIGUNUSEDPARM(newmemory)) { return (void *)((tst_action< char,PythonReference,string_type > *) ((CallableAction *) x)); } static void *_p_TSTTo_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t(void *x, int *SWIGUNUSEDPARM(newmemory)) { return (void *)((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) ((TST *) x)); } static swig_type_info _swigt__p_CallableAction = {"_p_CallableAction", "CallableAction *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_CallableFilter = {"_p_CallableFilter", "CallableFilter *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_DictAction = {"_p_DictAction", "DictAction *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ListAction = {"_p_ListAction", "ListAction *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ObjectSerializer = {"_p_ObjectSerializer", "ObjectSerializer *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_PythonReference = {"_p_PythonReference", "PythonReference *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_TST = {"_p_TST", "TST *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_TSTException = {"_p_TSTException", "TSTException *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t = {"_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t", "TSTLexicalIterator *|TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > *|TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t = {"_p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t", "TSTCloseMatchIterator *|TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > *|TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_TupleListAction = {"_p_TupleListAction", "TupleListAction *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_character_type = {"_p_character_type", "character_type *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t = {"_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t", "lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *|lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t = {"_p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t", "match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *|match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_qad_stringT_char_t = {"_p_qad_stringT_char_t", "string_type *|qad_string< char > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_serializer_type = {"_p_serializer_type", "serializer_type *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_std__istream = {"_p_std__istream", "std::istream *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_std__ostream = {"_p_std__ostream", "std::ostream *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_std__pairT_qad_stringT_char_t_PythonReference_p_t = {"_p_std__pairT_qad_stringT_char_t_PythonReference_p_t", "match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type *|std::pair< qad_string< char >,PythonReference * > *|lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_storage_type = {"_p_storage_type", "storage_type *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t = {"_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t", "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t = {"_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t", "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_tst_actionT_char_PythonReference_string_type_t = {"_p_tst_actionT_char_PythonReference_string_type_t", "tst_action< char,PythonReference,string_type > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_tst_filterT_char_PythonReference_string_type_t = {"_p_tst_filterT_char_PythonReference_string_type_t", "tst_filter< char,PythonReference,string_type > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_value_type = {"_p_value_type", "value_type *", 0, 0, (void*)0, 0}; static swig_type_info *swig_type_initial[] = { &_swigt__p_CallableAction, &_swigt__p_CallableFilter, &_swigt__p_DictAction, &_swigt__p_ListAction, &_swigt__p_ObjectSerializer, &_swigt__p_PythonReference, &_swigt__p_TST, &_swigt__p_TSTException, &_swigt__p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, &_swigt__p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, &_swigt__p_TupleListAction, &_swigt__p_char, &_swigt__p_character_type, &_swigt__p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, &_swigt__p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, &_swigt__p_qad_stringT_char_t, &_swigt__p_serializer_type, &_swigt__p_std__istream, &_swigt__p_std__ostream, &_swigt__p_std__pairT_qad_stringT_char_t_PythonReference_p_t, &_swigt__p_storage_type, &_swigt__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, &_swigt__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, &_swigt__p_tst_actionT_char_PythonReference_string_type_t, &_swigt__p_tst_filterT_char_PythonReference_string_type_t, &_swigt__p_value_type, }; static swig_cast_info _swigc__p_CallableAction[] = { {&_swigt__p_CallableAction, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_CallableFilter[] = { {&_swigt__p_CallableFilter, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_DictAction[] = { {&_swigt__p_DictAction, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ListAction[] = { {&_swigt__p_ListAction, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ObjectSerializer[] = { {&_swigt__p_ObjectSerializer, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_PythonReference[] = { {&_swigt__p_PythonReference, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TST[] = { {&_swigt__p_TST, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TSTException[] = { {&_swigt__p_TSTException, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t[] = { {&_swigt__p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t[] = { {&_swigt__p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TupleListAction[] = { {&_swigt__p_TupleListAction, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_character_type[] = { {&_swigt__p_character_type, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t[] = { {&_swigt__p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t[] = { {&_swigt__p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_qad_stringT_char_t[] = { {&_swigt__p_qad_stringT_char_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_serializer_type[] = { {&_swigt__p_serializer_type, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_std__istream[] = { {&_swigt__p_std__istream, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_std__ostream[] = { {&_swigt__p_std__ostream, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_std__pairT_qad_stringT_char_t_PythonReference_p_t[] = { {&_swigt__p_std__pairT_qad_stringT_char_t_PythonReference_p_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_storage_type[] = { {&_swigt__p_storage_type, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t[] = { {&_swigt__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t[] = { {&_swigt__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0, 0, 0}, {&_swigt__p_TST, _p_TSTTo_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_tst_actionT_char_PythonReference_string_type_t[] = { {&_swigt__p_tst_actionT_char_PythonReference_string_type_t, 0, 0, 0}, {&_swigt__p_DictAction, _p_DictActionTo_p_tst_actionT_char_PythonReference_string_type_t, 0, 0}, {&_swigt__p_ListAction, _p_ListActionTo_p_tst_actionT_char_PythonReference_string_type_t, 0, 0}, {&_swigt__p_TupleListAction, _p_TupleListActionTo_p_tst_actionT_char_PythonReference_string_type_t, 0, 0}, {&_swigt__p_CallableAction, _p_CallableActionTo_p_tst_actionT_char_PythonReference_string_type_t, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_tst_filterT_char_PythonReference_string_type_t[] = { {&_swigt__p_CallableFilter, _p_CallableFilterTo_p_tst_filterT_char_PythonReference_string_type_t, 0, 0}, {&_swigt__p_tst_filterT_char_PythonReference_string_type_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_value_type[] = { {&_swigt__p_value_type, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { _swigc__p_CallableAction, _swigc__p_CallableFilter, _swigc__p_DictAction, _swigc__p_ListAction, _swigc__p_ObjectSerializer, _swigc__p_PythonReference, _swigc__p_TST, _swigc__p_TSTException, _swigc__p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, _swigc__p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, _swigc__p_TupleListAction, _swigc__p_char, _swigc__p_character_type, _swigc__p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, _swigc__p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, _swigc__p_qad_stringT_char_t, _swigc__p_serializer_type, _swigc__p_std__istream, _swigc__p_std__ostream, _swigc__p_std__pairT_qad_stringT_char_t_PythonReference_p_t, _swigc__p_storage_type, _swigc__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, _swigc__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, _swigc__p_tst_actionT_char_PythonReference_string_type_t, _swigc__p_tst_filterT_char_PythonReference_string_type_t, _swigc__p_value_type, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ static swig_const_info swig_const_table[] = { {0, 0, 0, 0.0, 0, 0}}; #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * Type initialization: * This problem is tough by the requirement that no dynamic * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back * to swig_type_info structures, we need some lookup code at initialization. * The idea is that swig generates all the structures that are needed. * The runtime then collects these partially filled structures. * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * * The generated swig_type_info structures are assigned staticly to an initial * array. We just loop through that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the * cast linked list. The cast data is initially stored in something like a * two-dimensional array. Each row corresponds to a type (there are the same * number of rows as there are in the swig_type_initial array). Each entry in * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that * swig_cast_info to the linked list (because the cast->type) pointer will * be correct. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* c-mode */ #endif #endif #if 0 #define SWIGRUNTIME_DEBUG #endif SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) { size_t i; swig_module_info *module_head, *iter; int found, init; clientdata = clientdata; /* check to see if the circular list has been setup, if not, set it up */ if (swig_module.next==0) { /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; init = 1; } else { init = 0; } /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (!module_head) { /* This is the first module loaded for this interpreter */ /* so set the swig module into the interpreter */ SWIG_SetModule(clientdata, &swig_module); module_head = &swig_module; } else { /* the interpreter has loaded a SWIG module, but has it loaded this one? */ found=0; iter=module_head; do { if (iter==&swig_module) { found=1; break; } iter=iter->next; } while (iter!= module_head); /* if the is found in the list, then all is done and we may leave */ if (found) return; /* otherwise we must add out module into the list */ swig_module.next = module_head->next; module_head->next = &swig_module; } /* When multiple interpeters are used, a module could have already been initialized in a different interpreter, but not yet have a pointer in this interpreter. In this case, we do not want to continue adding types... everything should be set up already */ if (init == 0) return; /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); #endif for (i = 0; i < swig_module.size; ++i) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); #endif /* if there is another module already loaded */ if (swig_module.next != &swig_module) { type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found type %s\n", type->name); #endif if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); #endif } } else { type = swig_module.type_initial[i]; } /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif cast->type = ret; ret = 0; } else { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif if (!ocast) ret = 0; } } if (!ret) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif if (type->cast) { type->cast->prev = cast; cast->next = type->cast; } type->cast = cast; } cast++; } /* Set entry in modules->types array equal to the type */ swig_module.types[i] = type; } swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } printf("---- Total casts: %d\n",j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } /* This function will propagate the clientdata field of type to * any new swig_type_info structures that have been added into the list * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ SWIGRUNTIME void SWIG_PropagateClientData(void) { size_t i; swig_cast_info *equiv; static int init_run = 0; if (init_run) return; init_run = 1; for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } equiv = equiv->next; } } } } #ifdef __cplusplus #if 0 { /* c-mode */ #endif } #endif #ifdef __cplusplus extern "C" { #endif /* Python-specific SWIG API */ #define SWIG_newvarlink() SWIG_Python_newvarlink() #define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) #define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) /* ----------------------------------------------------------------------------- * global variable support code. * ----------------------------------------------------------------------------- */ typedef struct swig_globalvar { char *name; /* Name of global variable */ PyObject *(*get_attr)(void); /* Return the current value */ int (*set_attr)(PyObject *); /* Set the value */ struct swig_globalvar *next; } swig_globalvar; typedef struct swig_varlinkobject { PyObject_HEAD swig_globalvar *vars; } swig_varlinkobject; SWIGINTERN PyObject * swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_InternFromString("<Swig global variables>"); #else return PyString_FromString("<Swig global variables>"); #endif } SWIGINTERN PyObject * swig_varlink_str(swig_varlinkobject *v) { #if PY_VERSION_HEX >= 0x03000000 PyObject *str = PyUnicode_InternFromString("("); PyObject *tail; PyObject *joined; swig_globalvar *var; for (var = v->vars; var; var=var->next) { tail = PyUnicode_FromString(var->name); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; if (var->next) { tail = PyUnicode_InternFromString(", "); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; } } tail = PyUnicode_InternFromString(")"); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; #else PyObject *str = PyString_FromString("("); swig_globalvar *var; for (var = v->vars; var; var=var->next) { PyString_ConcatAndDel(&str,PyString_FromString(var->name)); if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); } PyString_ConcatAndDel(&str,PyString_FromString(")")); #endif return str; } SWIGINTERN int swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char *tmp; PyObject *str = swig_varlink_str(v); fprintf(fp,"Swig global variables "); fprintf(fp,"%s\n", tmp = SWIG_Python_str_AsChar(str)); SWIG_Python_str_DelForPy3(tmp); Py_DECREF(str); return 0; } SWIGINTERN void swig_varlink_dealloc(swig_varlinkobject *v) { swig_globalvar *var = v->vars; while (var) { swig_globalvar *n = var->next; free(var->name); free(var); var = n; } } SWIGINTERN PyObject * swig_varlink_getattr(swig_varlinkobject *v, char *n) { PyObject *res = NULL; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->get_attr)(); break;
nlehuen/pytst
e8e72651cc89ef46824137161530c5db12120c56
Inline PythonReference methods.
diff --git a/python/PythonReference.h b/python/PythonReference.h index 1ff7d37..f1f250f 100644 --- a/python/PythonReference.h +++ b/python/PythonReference.h @@ -1,78 +1,78 @@ -#ifndef __PYTHONREFERENCE_H__ -#define __PYTHONREFERENCE_H__ - -#include "Python.h" - -class PythonException : public std::exception { -public: - PythonException(const char* _message) : message(_message) { - } - - const char* what() { - return message; - } - -private: - const char* message; -}; - - -class PythonReference { -public: - explicit PythonReference() : ref(Py_None) { - Py_INCREF(ref); - } - - explicit PythonReference(PyObject *object, int borrow=1) : ref(object) { - if(ref==0) { - throw PythonException("Cannot reference NULL"); - } - if(borrow) { - Py_INCREF(ref); - } - } - - PythonReference(const PythonReference& that) : ref(that.ref) { - Py_INCREF(ref); - } - - PythonReference& operator= (const PythonReference& that) { - PyObject* old = ref; - - if((this->ref = that.ref) != old) { - Py_INCREF(ref); - Py_DECREF(old); - } - - return *this; - } - - ~PythonReference() { - Py_DECREF(ref); - } - - int operator==(const PythonReference& that) { - return (ref==that.ref); - } - - int operator!=(const PythonReference& that) { - return (ref!=that.ref); - } - - PythonReference getattr(char* name) { - return PythonReference(PyObject_GetAttrString(get(),name)); - } - - PyObject* get() { - return ref; - } - - PyObject* lend() { - Py_INCREF(ref); - return ref; - } - -private: - PyObject* ref; -}; -#endif +#ifndef __PYTHONREFERENCE_H__ +#define __PYTHONREFERENCE_H__ + +#include "Python.h" + +class PythonException : public std::exception { +public: + PythonException(const char* _message) : message(_message) { + } + + const char* what() { + return message; + } + +private: + const char* message; +}; + + +class PythonReference { +public: + explicit PythonReference() : ref(Py_None) { + Py_INCREF(ref); + } + + explicit PythonReference(PyObject *object, int borrow=1) : ref(object) { + if(ref==0) { + throw PythonException("Cannot reference NULL"); + } + if(borrow) { + Py_INCREF(ref); + } + } + + PythonReference(const PythonReference& that) : ref(that.ref) { + Py_INCREF(ref); + } + + inline PythonReference& operator= (const PythonReference& that) { + PyObject* old = ref; + + if((this->ref = that.ref) != old) { + Py_INCREF(ref); + Py_DECREF(old); + } + + return *this; + } + + ~PythonReference() { + Py_DECREF(ref); + } + + inline int operator==(const PythonReference& that) { + return (ref==that.ref); + } + + inline int operator!=(const PythonReference& that) { + return (ref!=that.ref); + } + + inline PythonReference getattr(char* name) { + return PythonReference(PyObject_GetAttrString(get(),name)); + } + + inline PyObject* get() { + return ref; + } + + inline PyObject* lend() { + Py_INCREF(ref); + return ref; + } + +private: + PyObject* ref; +}; +#endif
nlehuen/pytst
6aff3994740d9f52bce5241c1126f4aa1ba917ed
Move & update .gitignore
diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 3076e6d..0000000 --- a/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -*.pyc -python/dist -python/test/test.tst diff --git a/python/.gitignore b/python/.gitignore new file mode 100644 index 0000000..9184d7e --- /dev/null +++ b/python/.gitignore @@ -0,0 +1,8 @@ +*.pyc +dist +test/test.tst +build +MANIFEST +Debug +Debug CRM +_ReSharper.pythonTST
nlehuen/pytst
b977066fe25db8a307fbac572c2706eac45378e2
New series of unit tests for a bug reported by Keith Davidson. No fix for it yet.
diff --git a/python/test/test.py b/python/test/test.py index dacbd5e..6c9bdeb 100644 --- a/python/test/test.py +++ b/python/test/test.py @@ -1,731 +1,777 @@ -# -*- coding: iso-8859-1 -*- - -import sys -# sys.path.insert(0,r"D:\projets\tst\python\Debug") - -import unittest -import os -import random -import string -import datetime -from time import time -from itertools import izip - -from tst import * - -random.seed(0) - -def random_string(length): - return ''.join([random.choice(string.letters) for x in xrange(length)]) - -from timer import Timer -from distance import levenshtein - -timers = {} - -def timer_start(name): - timers.setdefault(name,Timer()).start() - -def timer_end(name,normalize=1.0): - timers.setdefault(name,Timer()).stop(normalize) - -def print_timers(comment): - keys = timers.keys() - keys.sort() - - for name in keys: - print '%16s : %s'%(name,timers[name]) - - statsfilename = os.path.join(os.path.dirname(__file__),'stats.csv') - if os.path.isfile(statsfilename): - statsfile = file(statsfilename,'ab') - else: - statsfile = file(statsfilename,'wb') - header = [ - 'date', - 'version', - 'comment' - ] - for key in keys: - header.append('%s:min'%key) - header.append('%s:med'%key) - header.append('%s:avg'%key) - header.append('%s:max'%key) - - statsfile.write(';'.join(header)) - statsfile.write('\n') - - row = [ - datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S'), - TST_VERSION, - comment, - ] - for key in keys: - timer = timers[key] - row.append(('%7.4f'%timer.min).replace('.',',')) - row.append(('%7.4f'%timer.med).replace('.',',')) - row.append(('%7.4f'%timer.avg).replace('.',',')) - row.append(('%7.4f'%timer.max).replace('.',',')) - - statsfile.write(';'.join(row)) - statsfile.write('\n') - -class TestRefCount(unittest.TestCase): - def setUp(self): - self.a = 'toto' - self.rc_a = sys.getrefcount(self.a) - self.rc_None = sys.getrefcount(None) - self.tree=TST() - - def testSetup(self): - self.assertEqual(sys.getrefcount(None),self.rc_None+17) - self.assertEqual(sys.getrefcount(self.a),self.rc_a) - - def testStore(self): - self.tree[self.a]=self.a - self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) - - def testOverwrite(self): - self.tree[self.a]=self.a - a2 = self.tree.put(self.a,'coucou') - self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) - del(a2) - self.assertEqual(sys.getrefcount(self.a),self.rc_a) - - def testWalkList(self): - l=self.tree.walk(None,ListAction()) - self.assertEqual(sys.getrefcount(self.a),self.rc_a) - self.tree[self.a]=self.a - self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) - l=self.tree.walk(None,ListAction()) - self.assertEqual(sys.getrefcount(self.a),self.rc_a+2) - del(l) - self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) - - def testWalkDict(self): - self.tree[self.a]=self.a - self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) - d=self.tree.walk(None,DictAction()) - self.assertEqual(sys.getrefcount(self.a),self.rc_a+2) - del(d) - self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) - del self.tree[self.a] - self.assertEqual(sys.getrefcount(self.a),self.rc_a) - - def testRemove(self): - del(self.tree) - self.assertEqual(sys.getrefcount(None),self.rc_None) - self.assertEqual(sys.getrefcount(self.a),self.rc_a) - -class TestCollectors(unittest.TestCase): - def setUp(self): - self.tree = TST() - self.keys = dict( - a = 1, - ab = 2, - abc = 3, - b = 4 - ) - for k,v in self.keys.iteritems(): - self.tree[k] = v - - def testListAction(self): - l = self.tree.walk(None,ListAction()) - self.assertEqual(l,[1,2,3,4]) - - def testTupleListAction(self): - l = self.tree.walk(None,TupleListAction()) - self.assertEqual(l,[('a',0,1),('ab',0,2),('abc',0,3),('b',0,4)]) - - def testDictAction(self): - l = self.tree.walk(None,DictAction()) - self.assertEqual(l,dict(a=(0,1),ab=(0,2),abc=(0,3),b=(0,4))) - -def skey(): - format = '%%.%if'%random.randint(1,10) - return format%random.random() - -class TestBasics(unittest.TestCase): - def setUp(self): - self.tree = TST() - self.keys = dict([ - (skey(),random.random()) - for x in xrange(250) - ]) - for k,v in self.keys.iteritems(): - self.tree[k] = v - - def testGet(self): - for k,v in self.keys.iteritems(): - self.assertEqual(self.tree[k],v) - - def testWithRemove(self): - for k in random.sample(self.keys,len(self.keys)/8): - del self.keys[k] - del self.tree[k] - self.tree.pack() - self.testGet() - - def testWithUpdate(self): - for k in random.sample(self.keys,len(self.keys)/8): - v = self.keys[k] - nv = random.random() - self.keys[k] = nv - self.assertEqual(self.tree.put(k,nv),v) - self.testGet() - - def testWalk(self): - timer_start("walk") - for i in xrange(100): - d = self.tree.walk(None,DictAction()) - timer_end("walk") - for k,v in d.iteritems(): - self.assertEquals(self.tree[k],v[1]) - - def testWalkWithRoot(self): - ref = self.tree.walk(None,DictAction()) - - timer_start("walk_root") - for i in xrange(100): - d = self.tree.walk(None,DictAction(),'0.1') - timer_end("walk_root") - for k, v in ref.iteritems(): - if k.startswith('0.1'): - self.assert_(k in d) - self.assertEquals(v,d[k]) - for k, v in d.iteritems(): - self.assert_(k.startswith('0.1')) - self.assertEquals(self.tree[k],v[1]) - - def testCloseMatch(self): - for k1 in self.keys.iterkeys(): - timer_start("close_match") - d = self.tree.close_match(k1,4,None,DictAction()) - timer_end("close_match") - for k2 in self.keys.iterkeys(): - distance = levenshtein(k1,k2) - if distance<=4: - self.assert_(k2 in d,"Match manquant pour %s : %s (distance = %i)"%( - k1, - k2, - distance, - )) - self.assert_(k2 in d and d[k2][0]==distance,"Mauvaise distance pour %s et %s : %i != %s"%( - k1, - k2, - distance, - d.get(k2)[0] - )) - else: - self.assert_(k2 not in d,"Mauvaise distance pour %s et %s : %i > 4 mais trouvé %s"%( - k1, - k2, - distance, - d.get(k2) - )) - - def testPrefixMatch(self): - for k1 in self.keys.iterkeys(): - timer_start("prefix_match") - d = self.tree.prefix_match(k1[:len(k1)/2],None,DictAction()) - timer_end("prefix_match") - self.assert_(k1 in d,"Une cle manque dans un prefix_match pour %s"%(k1,)) - k2 = k1 + k1 - timer_start("prefix_match") - d = self.tree.prefix_match(k2,None,DictAction()) - timer_end("prefix_match") - self.assert_(k2 not in d,"Une cle manque dans un prefix_match pour %s"%(k1,)) - - def testWriteRead(self): - self.tree.write_to_file('test.tst') - - self.tree = TST() - self.tree.read_from_file('test.tst') - - self.testGet() - -class TestMatch(unittest.TestCase): - def setUp(self): - self.tree = TST() - self.tree['abc'] = 'abc' - self.tree['ab'] = 'ab' - self.tree['a'] = 'a' - self.tree['bbc'] = 'bbc' - self.tree['efgfjhny'] = 'ok' - - def testJoker1(self): - d = self.tree.match("a?c",None,DictAction()) - self.assertEquals(d,dict(abc=(0,"abc"))) - - def testJoker2(self): - d = self.tree.match("???",None,DictAction()) - self.assertEquals(d,{'abc': (0, 'abc'), 'bbc': (0, 'bbc')}) - - def testJoker3(self): - d = self.tree.match("??",None,DictAction()) - self.assertEquals(d,{'ab': (0, 'ab')}) - - def testStar1(self): - d = self.tree.match("a*c",None,DictAction()) - self.assertEquals(d,dict(abc=(0,"abc"))) - - def testStar2(self): - d = self.tree.match("a*",None,DictAction()) - self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'abc': (0, 'abc')}) - - def testStar2_1(self): - d = self.tree.match("ab*",None,DictAction()) - self.assertEquals(d,{'ab': (0, 'ab'), 'abc': (0, 'abc')}) - - def testStar2_2(self): - d = self.tree.match("*b",None,DictAction()) - self.assertEquals(d,{'ab': (0, 'ab')}) - - d = self.tree.match("*bbc",None,DictAction()) - self.assertEquals(d,{'bbc': (0, 'bbc')}) - - def testStar3(self): - d = self.tree.match("*",None,DictAction()) - self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) - - d = self.tree.match("*?*",None,DictAction()) - self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) - - def testStar3_1(self): - d = self.tree.match("**",None,DictAction()) - self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) - - d = self.tree.match("***",None,DictAction()) - self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) - - def testStar4(self): - d = self.tree.match("e*ny",None,DictAction()) - self.assertEquals(d,{'efgfjhny': (0, 'ok')}) - - def testStar5(self): - d = self.tree.match("*****y",None,DictAction()) - self.assertEquals(d,{'efgfjhny': (0, 'ok')}) - - def testStar6(self): - d = self.tree.match("????*",None,DictAction()) - self.assertEquals(d,{'efgfjhny': (0, 'ok')}) - - def testStar7(self): - d = self.tree.match("ef?f*n?",None,DictAction()) - self.assertEquals(d,{'efgfjhny': (0, 'ok')}) - -class TestIterators(unittest.TestCase): - def setUp(self): - self.tree = TST() - self.keys = dict( - titi = 1, - toto = 2, - tati = 3, - a = 5 - ) - for k, v in self.keys.iteritems(): - self.tree[k] = v - - def testLexical1(self): - d = {} - for k, v in self.tree: - d[k] = v - self.assertEqual(d,self.keys) - - def testLexical2(self): - d = {} - for k, v in self.tree.iterator('t'): - d[k] = v - self.keys.pop('a') - self.assertEqual(d,self.keys) - - def testCloseMatch(self): - d = {} - for k, v in self.tree.close_match_iterator('t',1): - d[k] = v - self.assertEqual(d,dict( - a = 5 - )) - d = {} - for k, v in self.tree.close_match_iterator('tito',1): - d[k] = v - self.assertEqual(d,dict( - titi = 1, - toto = 2 - )) - d = {} - for k, v in self.tree.close_match_iterator('tuto',1): - d[k] = v - self.assertEqual(d,dict( - toto = 2 - )) - -class TestCallableAction(unittest.TestCase): - def setUp(self): - self.tree = TST() - self.tree['foo'] = 'bar' - - def testCA1(self): - res = {} - - def callback(key, length, obj): - res[key] = obj - - def result(): - res['hello'] = 'world' - return res - - self.assertEqual( - self.tree.walk(None, CallableAction(callback, result)), - {'foo':'bar', 'hello':'world'} - ) - - def testCA2(self): - res = {} - - def callback(key, length, obj): - # Provoke an exception - print 0 / 0 - res[key] = obj - - def result(): - return res - - try: - self.tree.walk(None, CallableAction(callback, result)), - self.fail("Should have raised an exception") - except ZeroDivisionError: - pass - - def testCA3(self): - res = {} - - def callback(key, length, obj): - res[key] = obj - - def result(): - # Provoke an exception - return 0/0 - - try: - self.tree.walk(None, CallableAction(callback, result)), - self.fail("Should have raised an exception") - except ZeroDivisionError: - pass - -class TestCallableFilter(unittest.TestCase): - def setUp(self): - self.tree = TST() - self.tree['foo'] = 'bar' - self.tree['bar'] = 'foo' - - def testCF1(self): - res = {} - - def cfilter(key, length, obj): - res[key] = obj - return obj - - self.tree.walk(CallableFilter(cfilter),None) - - self.assertEqual( - res, - {'foo':'bar', 'bar':'foo'} - ) - - def testCF2(self): - def cfilter(key, length, obj): - if key=='foo': - return 'boo' - else: - return obj - - self.assertEqual( - self.tree.walk(CallableFilter(cfilter),DictAction()), - {'foo':(0,'boo'),'bar':(0,'foo')} - ) - - def testCF3(self): - def cfilter(key, length, obj): - if key=='foo': - # raises an exception - return 0 / 0 - else: - return obj - - try: - self.tree.walk(CallableFilter(cfilter),DictAction()), - self.fail("Should have raised an exception") - except ZeroDivisionError: - pass - -class TestHighCapacity(unittest.TestCase): - def setUp(self): - tree = TST() - timer_start('build_big') - keys = map(str,xrange(100000)) - random.shuffle(keys) - timer_end('build_big') - timer_start('write_big') - for k in keys: - tree[k] = k - timer_end('write_big') - - self.keys, self.tree = keys, tree - - def testGet(self): - timer_start('read_big') - for k in self.keys: - self.assertEqual(self.tree[k],k) - timer_end('read_big') - - def testFullPack(self): - timer_start('delete_full') - for k in self.keys: - del self.tree[k] - timer_end('delete_full') - - self.tree.pack() - - for k in self.keys: - self.assertEqual(self.tree[k],None) - - sample = random.sample(self.keys,len(self.keys)/10) - random.shuffle(sample) - timer_start('refill_post_pack/10') - for k in sample: - self.tree[k] = k - timer_end('refill_post_pack/10',10) - - for k in sample: - self.assertEqual(self.tree[k],k) - del self.tree[k] - - self.tree.pack() - - for k in self.keys: - self.assertEqual(self.tree[k],None) - - self.tree.write_to_file('test.tst') - - def testDelete(self): - sample = random.sample(self.keys,len(self.keys)/10) - - random.shuffle(sample) - timer_start('delete_big/10') - for k in sample: - del self.tree[k] - timer_end('delete_big/10',10) - - random.shuffle(sample) - timer_start('refill_pre_pack/10') - for k in sample: - self.tree[k] = k - timer_end('refill_pre_pack/10',10) - - self.testGet() - - random.shuffle(sample) - timer_start('delete_big/10') - for k in sample: - del self.tree[k] - timer_end('delete_big/10',10) - - self.tree.pack() - - random.shuffle(sample) - timer_start('refill_post_pack/10') - for k in sample: - self.tree[k] = k - timer_end('refill_post_pack/10',10) - - self.testGet() - - timer_start('delete_big/10') - for k in self.keys[:len(self.keys)/10]: - del self.tree[k] - timer_end('delete_big/10',10) - - timer_start('pack/10') - self.tree.pack() - timer_end('pack/10',10) - - timer_start('check_delete_big') - for k in self.keys[:len(self.keys)/10]: - self.assertEqual(self.tree[k],None) - for k in self.keys[len(self.keys)/10+1:]: - self.assertEqual(self.tree[k],k) - timer_end('check_delete_big') - - def testUpdate(self): - timer_start('build_big/10') - old_keys = self.keys[:len(self.keys)/10] - new_keys = map(lambda x:str(int(x) + 1),old_keys) - timer_end('build_big/10',10) - timer_start('update_big/10') - for k,kp in izip(old_keys,new_keys): - self.assertEqual(self.tree.put(k,kp),k) - timer_end('update_big/10',10) - timer_start('check_update_big') - for k,kp in izip(old_keys,new_keys): - self.assertEqual(self.tree[k],kp) - timer_end('check_update_big') - -class TestScan(unittest.TestCase): - def setUp(self): - self.tree = TST() - self.tree['Nicolas']='Nicolas' - self.tree['olaf']='olaf' - self.tree['lazlo']='lazlo' - self.tree['Nicolas-Antoinette']='Nicolas-Antoinette' - self.tree['Antoinette']='Antoinette' - self.tree['Antoine']='Antoine' - self.tree['astride']='astride' - self.tree['VICTOIRE']='VICTOIRE' - self.tree['IAN']='IAN' - self.tree['x']='x' - self.tree['V']='V' - self.tree['ROBERT']='ROBERT' - self.tree['A N']='A N' - self.tree['olaaf']='olaaf' - self.tree['laslo']='laslo' - - def testScanMikeThornton(self): - t = TST() - t['ccc'] = 1 - self.assertEqual(t.scan('cc',TupleListAction()),[('cc',-2,None)]) - self.assertEqual(t.scan('ccd',TupleListAction()),[('ccd',-3,None)]) - - - def testScan0_1(self): - self.assertEqual(self.tree.scan('Nicolas',TupleListAction()),[('Nicolas', 7, 'Nicolas'),]) - - def testScan0_2(self): - self.assertEqual(self.tree.scan(' Nicolas',TupleListAction()),[(' ',-1,None),('Nicolas', 7, 'Nicolas'),]) - - def testScan0_3(self): - self.assertEqual(self.tree.scan('Nicolas ',TupleListAction()),[('Nicolas', 7, 'Nicolas'),(' ',-1,None),]) - - def testScan0_4(self): - self.assertEqual(self.tree.scan(' Nicolas ',TupleListAction()),[(' ',-1,None),('Nicolas', 7, 'Nicolas'),(' ',-1,None),]) - - def testScan0_5(self): - self.assertEqual(self.tree.scan(' ',TupleListAction()),[(' ',-1,None),]) - - def testScan0_6(self): - self.assertEqual(self.tree.scan('la',TupleListAction()),[('la', -2, None)]) - - def testScan0_7(self): - self.assertEqual(self.tree.scan('lazl',TupleListAction()),[('lazl', -4, None)]) - - def testScan1(self): - timer_start("scan") - for i in xrange(10000): - self.assertEqual(self.tree.scan('lazlo',TupleListAction()),[('lazlo', 5, 'lazlo')]) - self.assertEqual(self.tree.scan('Nicolazlo',TupleListAction()),[('Nico', -4, None), ('lazlo', 5, 'lazlo')]) - timer_end("scan") - - def testScan24(self): - self.assertEqual(self.tree.scan('A NicoNicoNicolasNicoNico',TupleListAction()),[('A N', 3, 'A N'), ('icoNico', -7, None), ('Nicolas', 7, 'Nicolas'), ('NicoNico', -8, None)]) - - def testScan1_1(self): - self.assertEqual(self.tree.scan('hippocampe',TupleListAction()),[('hippocampe', -10, None)]) - - def testScan2(self): - self.assertEqual(self.tree.scan('NicolaNicolaNicolaNicolaNicola',TupleListAction()),[('NicolaNicolaNicolaNicolaNicola', -30, None)]) - - def testScan3(self): - self.assertEqual(self.tree.scan('Nicolasstupide',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('stupide', -7, None)]) - - def testScan4(self): - self.assertEqual(self.tree.scan('Nicolast',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('t', -1, None)]) - - def testScan5(self): - self.assertEqual(self.tree.scan('xxxNicolas',TupleListAction()),[('x', 1, 'x'), ('x', 1, 'x'), ('x', 1, 'x'), ('Nicolas', 7, 'Nicolas')]) - - def testScan6(self): - self.assertEqual(self.tree.scan('xxx Nicolas',TupleListAction()),[('x', 1, 'x'), ('x', 1, 'x'), ('x', 1, 'x'), (' ', -1, None), ('Nicolas', 7, 'Nicolas')]) - - def testScan7(self): - self.assertEqual(self.tree.scan('Antoinette Antoinette',TupleListAction()),[('Antoinette', 10, 'Antoinette'), (' ', -1, None), ('Antoinette', 10, 'Antoinette')]) - - def testScan8(self): - self.assertEqual(self.tree.scan('Nicolas-Antoinette',TupleListAction()),[('Nicolas-Antoinette', 18, 'Nicolas-Antoinette')]) - - def testScan9(self): - self.assertEqual(self.tree.scan('Nicolas-Antoine',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) - - def testScan9_1(self): - self.assertEqual(self.tree.scan('Nicolas-Antoine-Antoine',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) - - def testScan9_2(self): - self.assertEqual(self.tree.scan('Nicolas-Antoine-Antoine-',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None)]) - - def testScan10(self): - self.assertEqual(self.tree.scan('Nicolas-Antoinet',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('t', -1, None)]) - - def testScanWithStopChars1(self): - self.assertEqual(self.tree.scan_with_stop_chars('Nicolas',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas')]) - - def testScanWithStopChars2(self): - self.assertEqual(self.tree.scan_with_stop_chars('Nicolasstupide',' -',TupleListAction()),[('Nicolasstupide', -14, None)]) - - def testScanWithStopChars25(self): - timer_start("scan_stop_chars") - for i in xrange(10000): - self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) - self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) - self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) - timer_end("scan_stop_chars") - - def testScanWithStopChars3(self): - self.assertEqual(self.tree.scan_with_stop_chars('Nicolast',' -',TupleListAction()),[('Nicolast', -8, None)]) - - def testScanWithStopChars4(self): - self.assertEqual(self.tree.scan_with_stop_chars('xxxNicolas',' -',TupleListAction()),[('xxxNicolas', -10, None)]) - - def testScanWithStopChars5(self): - self.assertEqual(self.tree.scan_with_stop_chars('xxx Nicolas',' -',TupleListAction()),[('xxx ', -4, None),('Nicolas', 7, 'Nicolas')]) - - def testScanWithStopChars6(self): - self.assertEqual(self.tree.scan_with_stop_chars('xxxAntoine Nicolas',' -',TupleListAction()),[('xxxAntoine ', -11, None),('Nicolas', 7, 'Nicolas')]) - - def testScanWithStopChars8(self): - self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoinette',' -',TupleListAction()),[('Nicolas-Antoinette', 18, 'Nicolas-Antoinette')]) - - def testScanWithStopChars9(self): - self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoine',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) - - def testScanWithStopChars10(self): - self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoinet',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-Antoinet', -9, None)]) - - def testScanVicieux(self): - self.assertEqual(self.tree.scan_with_stop_chars('xxxAntoine A Nicolas',' -',TupleListAction()),[('xxxAntoine A ', -13, None),('Nicolas', 7, 'Nicolas')]) - - def testScanVicieux2(self): - self.assertEqual(self.tree.scan_with_stop_chars('Antoinette Antoinette',' -',TupleListAction()),[('Antoinette', 10, 'Antoinette'), (' ', -1, None), ('Antoinette', 10, 'Antoinette')]) - - def testScanVicieux3(self): - self.assertEqual(self.tree.scan_with_stop_chars('nastride lazlo',' -',TupleListAction()),[('nastride ', -9, None), ('lazlo', 5, 'lazlo')]) - self.assertEqual(self.tree.scan_with_stop_chars('VIAN ROBERT',' -',TupleListAction()),[('VIAN ', -5, None), ('ROBERT', 6, 'ROBERT')]) - -if __name__ == '__main__': - print "Testing pytst %s"%TST_VERSION - - comment = ' '.join(sys.argv[1:]) - - suite = unittest.TestSuite(( - unittest.makeSuite(TestCollectors), - unittest.makeSuite(TestBasics), - unittest.makeSuite(TestHighCapacity), - unittest.makeSuite(TestScan), - unittest.makeSuite(TestIterators), - unittest.makeSuite(TestMatch), - unittest.makeSuite(TestCallableAction), - unittest.makeSuite(TestCallableFilter), - )) - - for i in xrange(3): - unittest.TextTestRunner().run(suite) - - print_timers(comment) +# -*- coding: iso-8859-1 -*- + +import sys +# sys.path.insert(0,r"D:\projets\tst\python\Debug") + +import unittest +import os +import random +import string +import datetime +from time import time +from itertools import izip + +from tst import * + +random.seed(0) + +def random_string(length): + return ''.join([random.choice(string.letters) for x in xrange(length)]) + +from timer import Timer +from distance import levenshtein + +timers = {} + +def timer_start(name): + timers.setdefault(name,Timer()).start() + +def timer_end(name,normalize=1.0): + timers.setdefault(name,Timer()).stop(normalize) + +def print_timers(comment): + keys = timers.keys() + keys.sort() + + for name in keys: + print '%16s : %s'%(name,timers[name]) + + statsfilename = os.path.join(os.path.dirname(__file__),'stats.csv') + if os.path.isfile(statsfilename): + statsfile = file(statsfilename,'ab') + else: + statsfile = file(statsfilename,'wb') + header = [ + 'date', + 'version', + 'comment' + ] + for key in keys: + header.append('%s:min'%key) + header.append('%s:med'%key) + header.append('%s:avg'%key) + header.append('%s:max'%key) + + statsfile.write(';'.join(header)) + statsfile.write('\n') + + row = [ + datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S'), + TST_VERSION, + comment, + ] + for key in keys: + timer = timers[key] + row.append(('%7.4f'%timer.min).replace('.',',')) + row.append(('%7.4f'%timer.med).replace('.',',')) + row.append(('%7.4f'%timer.avg).replace('.',',')) + row.append(('%7.4f'%timer.max).replace('.',',')) + + statsfile.write(';'.join(row)) + statsfile.write('\n') + +class TestRefCount(unittest.TestCase): + def setUp(self): + self.a = 'toto' + self.rc_a = sys.getrefcount(self.a) + self.rc_None = sys.getrefcount(None) + self.tree=TST() + + def testSetup(self): + self.assertEqual(sys.getrefcount(None),self.rc_None+17) + self.assertEqual(sys.getrefcount(self.a),self.rc_a) + + def testStore(self): + self.tree[self.a]=self.a + self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) + + def testOverwrite(self): + self.tree[self.a]=self.a + a2 = self.tree.put(self.a,'coucou') + self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) + del(a2) + self.assertEqual(sys.getrefcount(self.a),self.rc_a) + + def testWalkList(self): + l=self.tree.walk(None,ListAction()) + self.assertEqual(sys.getrefcount(self.a),self.rc_a) + self.tree[self.a]=self.a + self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) + l=self.tree.walk(None,ListAction()) + self.assertEqual(sys.getrefcount(self.a),self.rc_a+2) + del(l) + self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) + + def testWalkDict(self): + self.tree[self.a]=self.a + self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) + d=self.tree.walk(None,DictAction()) + self.assertEqual(sys.getrefcount(self.a),self.rc_a+2) + del(d) + self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) + del self.tree[self.a] + self.assertEqual(sys.getrefcount(self.a),self.rc_a) + + def testRemove(self): + del(self.tree) + self.assertEqual(sys.getrefcount(None),self.rc_None) + self.assertEqual(sys.getrefcount(self.a),self.rc_a) + +class TestCollectors(unittest.TestCase): + def setUp(self): + self.tree = TST() + self.keys = dict( + a = 1, + ab = 2, + abc = 3, + b = 4 + ) + for k,v in self.keys.iteritems(): + self.tree[k] = v + + def testListAction(self): + l = self.tree.walk(None,ListAction()) + self.assertEqual(l,[1,2,3,4]) + + def testTupleListAction(self): + l = self.tree.walk(None,TupleListAction()) + self.assertEqual(l,[('a',0,1),('ab',0,2),('abc',0,3),('b',0,4)]) + + def testDictAction(self): + l = self.tree.walk(None,DictAction()) + self.assertEqual(l,dict(a=(0,1),ab=(0,2),abc=(0,3),b=(0,4))) + +def skey(): + format = '%%.%if'%random.randint(1,10) + return format%random.random() + +class TestBasics(unittest.TestCase): + def setUp(self): + self.tree = TST() + self.keys = dict([ + (skey(),random.random()) + for x in xrange(250) + ]) + for k,v in self.keys.iteritems(): + self.tree[k] = v + + def testGet(self): + for k,v in self.keys.iteritems(): + self.assertEqual(self.tree[k],v) + + def testWithRemove(self): + for k in random.sample(self.keys,len(self.keys)/8): + del self.keys[k] + del self.tree[k] + self.tree.pack() + self.testGet() + + def testWithUpdate(self): + for k in random.sample(self.keys,len(self.keys)/8): + v = self.keys[k] + nv = random.random() + self.keys[k] = nv + self.assertEqual(self.tree.put(k,nv),v) + self.testGet() + + def testWalk(self): + timer_start("walk") + for i in xrange(100): + d = self.tree.walk(None,DictAction()) + timer_end("walk") + for k,v in d.iteritems(): + self.assertEquals(self.tree[k],v[1]) + + def testWalkWithRoot(self): + ref = self.tree.walk(None,DictAction()) + + timer_start("walk_root") + for i in xrange(100): + d = self.tree.walk(None,DictAction(),'0.1') + timer_end("walk_root") + for k, v in ref.iteritems(): + if k.startswith('0.1'): + self.assert_(k in d) + self.assertEquals(v,d[k]) + for k, v in d.iteritems(): + self.assert_(k.startswith('0.1')) + self.assertEquals(self.tree[k],v[1]) + + def testCloseMatch(self): + for k1 in self.keys.iterkeys(): + timer_start("close_match") + d = self.tree.close_match(k1,4,None,DictAction()) + timer_end("close_match") + for k2 in self.keys.iterkeys(): + distance = levenshtein(k1,k2) + if distance<=4: + self.assert_(k2 in d,"Match manquant pour %s : %s (distance = %i)"%( + k1, + k2, + distance, + )) + self.assert_(k2 in d and d[k2][0]==distance,"Mauvaise distance pour %s et %s : %i != %s"%( + k1, + k2, + distance, + d.get(k2)[0] + )) + else: + self.assert_(k2 not in d,"Mauvaise distance pour %s et %s : %i > 4 mais trouvé %s"%( + k1, + k2, + distance, + d.get(k2) + )) + + def testPrefixMatch(self): + for k1 in self.keys.iterkeys(): + timer_start("prefix_match") + d = self.tree.prefix_match(k1[:len(k1)/2],None,DictAction()) + timer_end("prefix_match") + self.assert_(k1 in d,"Une cle manque dans un prefix_match pour %s"%(k1,)) + k2 = k1 + k1 + timer_start("prefix_match") + d = self.tree.prefix_match(k2,None,DictAction()) + timer_end("prefix_match") + self.assert_(k2 not in d,"Une cle manque dans un prefix_match pour %s"%(k1,)) + + def testWriteRead(self): + self.tree.write_to_file('test.tst') + + self.tree = TST() + self.tree.read_from_file('test.tst') + + self.testGet() + +class TestMatch(unittest.TestCase): + def setUp(self): + self.tree = TST() + self.tree['abc'] = 'abc' + self.tree['ab'] = 'ab' + self.tree['a'] = 'a' + self.tree['bbc'] = 'bbc' + self.tree['efgfjhny'] = 'ok' + + def testJoker1(self): + d = self.tree.match("a?c",None,DictAction()) + self.assertEquals(d,dict(abc=(0,"abc"))) + + def testJoker2(self): + d = self.tree.match("???",None,DictAction()) + self.assertEquals(d,{'abc': (0, 'abc'), 'bbc': (0, 'bbc')}) + + def testJoker3(self): + d = self.tree.match("??",None,DictAction()) + self.assertEquals(d,{'ab': (0, 'ab')}) + + def testStar1(self): + d = self.tree.match("a*c",None,DictAction()) + self.assertEquals(d,dict(abc=(0,"abc"))) + + def testStar2(self): + d = self.tree.match("a*",None,DictAction()) + self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'abc': (0, 'abc')}) + + def testStar2_1(self): + d = self.tree.match("ab*",None,DictAction()) + self.assertEquals(d,{'ab': (0, 'ab'), 'abc': (0, 'abc')}) + + def testStar2_2(self): + d = self.tree.match("*b",None,DictAction()) + self.assertEquals(d,{'ab': (0, 'ab')}) + + d = self.tree.match("*bbc",None,DictAction()) + self.assertEquals(d,{'bbc': (0, 'bbc')}) + + def testStar3(self): + d = self.tree.match("*",None,DictAction()) + self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) + + d = self.tree.match("*?*",None,DictAction()) + self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) + + def testStar3_1(self): + d = self.tree.match("**",None,DictAction()) + self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) + + d = self.tree.match("***",None,DictAction()) + self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) + + def testStar4(self): + d = self.tree.match("e*ny",None,DictAction()) + self.assertEquals(d,{'efgfjhny': (0, 'ok')}) + + def testStar5(self): + d = self.tree.match("*****y",None,DictAction()) + self.assertEquals(d,{'efgfjhny': (0, 'ok')}) + + def testStar6(self): + d = self.tree.match("????*",None,DictAction()) + self.assertEquals(d,{'efgfjhny': (0, 'ok')}) + + def testStar7(self): + d = self.tree.match("ef?f*n?",None,DictAction()) + self.assertEquals(d,{'efgfjhny': (0, 'ok')}) + +class TestIterators(unittest.TestCase): + def setUp(self): + self.tree = TST() + self.keys = dict( + titi = 1, + toto = 2, + tati = 3, + a = 5 + ) + for k, v in self.keys.iteritems(): + self.tree[k] = v + + def testLexical1(self): + d = {} + for k, v in self.tree: + d[k] = v + self.assertEqual(d,self.keys) + + def testLexical2(self): + d = {} + for k, v in self.tree.iterator('t'): + d[k] = v + self.keys.pop('a') + self.assertEqual(d,self.keys) + + def testCloseMatch(self): + d = {} + for k, v in self.tree.close_match_iterator('t',1): + d[k] = v + self.assertEqual(d,dict( + a = 5 + )) + d = {} + for k, v in self.tree.close_match_iterator('tito',1): + d[k] = v + self.assertEqual(d,dict( + titi = 1, + toto = 2 + )) + d = {} + for k, v in self.tree.close_match_iterator('tuto',1): + d[k] = v + self.assertEqual(d,dict( + toto = 2 + )) + +class TestCallableAction(unittest.TestCase): + def setUp(self): + self.tree = TST() + self.tree['foo'] = 'bar' + + def testCA1(self): + res = {} + + def callback(key, length, obj): + res[key] = obj + + def result(): + res['hello'] = 'world' + return res + + self.assertEqual( + self.tree.walk(None, CallableAction(callback, result)), + {'foo':'bar', 'hello':'world'} + ) + + def testCA2(self): + res = {} + + def callback(key, length, obj): + # Provoke an exception + print 0 / 0 + res[key] = obj + + def result(): + return res + + try: + self.tree.walk(None, CallableAction(callback, result)), + self.fail("Should have raised an exception") + except ZeroDivisionError: + pass + + def testCA3(self): + res = {} + + def callback(key, length, obj): + res[key] = obj + + def result(): + # Provoke an exception + return 0/0 + + try: + self.tree.walk(None, CallableAction(callback, result)), + self.fail("Should have raised an exception") + except ZeroDivisionError: + pass + +class TestCallableFilter(unittest.TestCase): + def setUp(self): + self.tree = TST() + self.tree['foo'] = 'bar' + self.tree['bar'] = 'foo' + + def testCF1(self): + res = {} + + def cfilter(key, length, obj): + res[key] = obj + return obj + + self.tree.walk(CallableFilter(cfilter),None) + + self.assertEqual( + res, + {'foo':'bar', 'bar':'foo'} + ) + + def testCF2(self): + def cfilter(key, length, obj): + if key=='foo': + return 'boo' + else: + return obj + + self.assertEqual( + self.tree.walk(CallableFilter(cfilter),DictAction()), + {'foo':(0,'boo'),'bar':(0,'foo')} + ) + + def testCF3(self): + def cfilter(key, length, obj): + if key=='foo': + # raises an exception + return 0 / 0 + else: + return obj + + try: + self.tree.walk(CallableFilter(cfilter),DictAction()), + self.fail("Should have raised an exception") + except ZeroDivisionError: + pass + +class TestHighCapacity(unittest.TestCase): + def setUp(self): + tree = TST() + timer_start('build_big') + keys = map(str,xrange(100000)) + random.shuffle(keys) + timer_end('build_big') + timer_start('write_big') + for k in keys: + tree[k] = k + timer_end('write_big') + + self.keys, self.tree = keys, tree + + def testGet(self): + timer_start('read_big') + for k in self.keys: + self.assertEqual(self.tree[k],k) + timer_end('read_big') + + def testFullPack(self): + timer_start('delete_full') + for k in self.keys: + del self.tree[k] + timer_end('delete_full') + + self.tree.pack() + + for k in self.keys: + self.assertEqual(self.tree[k],None) + + sample = random.sample(self.keys,len(self.keys)/10) + random.shuffle(sample) + timer_start('refill_post_pack/10') + for k in sample: + self.tree[k] = k + timer_end('refill_post_pack/10',10) + + for k in sample: + self.assertEqual(self.tree[k],k) + del self.tree[k] + + self.tree.pack() + + for k in self.keys: + self.assertEqual(self.tree[k],None) + + self.tree.write_to_file('test.tst') + + def testDelete(self): + sample = random.sample(self.keys,len(self.keys)/10) + + random.shuffle(sample) + timer_start('delete_big/10') + for k in sample: + del self.tree[k] + timer_end('delete_big/10',10) + + random.shuffle(sample) + timer_start('refill_pre_pack/10') + for k in sample: + self.tree[k] = k + timer_end('refill_pre_pack/10',10) + + self.testGet() + + random.shuffle(sample) + timer_start('delete_big/10') + for k in sample: + del self.tree[k] + timer_end('delete_big/10',10) + + self.tree.pack() + + random.shuffle(sample) + timer_start('refill_post_pack/10') + for k in sample: + self.tree[k] = k + timer_end('refill_post_pack/10',10) + + self.testGet() + + timer_start('delete_big/10') + for k in self.keys[:len(self.keys)/10]: + del self.tree[k] + timer_end('delete_big/10',10) + + timer_start('pack/10') + self.tree.pack() + timer_end('pack/10',10) + + timer_start('check_delete_big') + for k in self.keys[:len(self.keys)/10]: + self.assertEqual(self.tree[k],None) + for k in self.keys[len(self.keys)/10+1:]: + self.assertEqual(self.tree[k],k) + timer_end('check_delete_big') + + def testUpdate(self): + timer_start('build_big/10') + old_keys = self.keys[:len(self.keys)/10] + new_keys = map(lambda x:str(int(x) + 1),old_keys) + timer_end('build_big/10',10) + timer_start('update_big/10') + for k,kp in izip(old_keys,new_keys): + self.assertEqual(self.tree.put(k,kp),k) + timer_end('update_big/10',10) + timer_start('check_update_big') + for k,kp in izip(old_keys,new_keys): + self.assertEqual(self.tree[k],kp) + timer_end('check_update_big') + +class TestScan(unittest.TestCase): + def setUp(self): + self.tree = TST() + self.tree['Nicolas']='Nicolas' + self.tree['olaf']='olaf' + self.tree['lazlo']='lazlo' + self.tree['Nicolas-Antoinette']='Nicolas-Antoinette' + self.tree['Antoinette']='Antoinette' + self.tree['Antoine']='Antoine' + self.tree['astride']='astride' + self.tree['VICTOIRE']='VICTOIRE' + self.tree['IAN']='IAN' + self.tree['x']='x' + self.tree['V']='V' + self.tree['ROBERT']='ROBERT' + self.tree['A N']='A N' + self.tree['olaaf']='olaaf' + self.tree['laslo']='laslo' + + def testScanMikeThornton(self): + t = TST() + t['ccc'] = 1 + self.assertEqual(t.scan('cc',TupleListAction()),[('cc',-2,None)]) + self.assertEqual(t.scan('ccd',TupleListAction()),[('ccd',-3,None)]) + + def testScanKeithDavidson1(self): + t = TST() + t['333'] = 'ccc' + # self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) + self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) + + def testScanKeithDavidson2(self): + t = TST() + t['333'] = 'ccc' + self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) + self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) + + + def testScanKeithDavidson3(self): + t = TST() + t['333'] = 'ccc' + self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) + self.assertEqual(t.scan('.3.',TupleListAction()),[('.3.',-3,None)]) + self.assertEqual(t.scan('.33.',TupleListAction()),[('.33.',-4,None)]) + self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) + self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) + + def testScanKeithDavidson4(self): + t = TST() + t['3333'] = 'ccc' + # self.assertEqual(t.scan('.333.',TupleListAction()),[('.333.',-5,None)]) + self.assertEqual(t.scan('.333333.',TupleListAction()),[('.',-1,None),('3333',4,'ccc'),('33.',-3,None)]) + + def testScanKeithDavidson5(self): + t = TST() + t['3333'] = 'ccc' + self.assertEqual(t.scan('.333.',TupleListAction()),[('.333.',-5,None)]) + self.assertEqual(t.scan('.333333.',TupleListAction()),[('.',-1,None),('3333',4,'ccc'),('33.',-3,None)]) + + def testScanKeithDavidson6(self): + t = TST() + t['333'] = 'ccc' + self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) + self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('333',3,'ccc'),('.',-1,None)]) + + def testScanKeithDavidson7(self): + t = TST() + t['333'] = 'ccc' + self.assertEqual(t.scan('.3.',TupleListAction()),[('.3.',-3,None)]) + self.assertEqual(t.scan('.333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('.',-1,None)]) + self.assertEqual(t.scan('.33333.',TupleListAction()),[('.',-1,None),('333',3,'ccc'),('33.',-3,None)]) + + def testScan0_1(self): + self.assertEqual(self.tree.scan('Nicolas',TupleListAction()),[('Nicolas', 7, 'Nicolas'),]) + + def testScan0_2(self): + self.assertEqual(self.tree.scan(' Nicolas',TupleListAction()),[(' ',-1,None),('Nicolas', 7, 'Nicolas'),]) + + def testScan0_3(self): + self.assertEqual(self.tree.scan('Nicolas ',TupleListAction()),[('Nicolas', 7, 'Nicolas'),(' ',-1,None),]) + + def testScan0_4(self): + self.assertEqual(self.tree.scan(' Nicolas ',TupleListAction()),[(' ',-1,None),('Nicolas', 7, 'Nicolas'),(' ',-1,None),]) + + def testScan0_5(self): + self.assertEqual(self.tree.scan(' ',TupleListAction()),[(' ',-1,None),]) + + def testScan0_6(self): + self.assertEqual(self.tree.scan('la',TupleListAction()),[('la', -2, None)]) + + def testScan0_7(self): + self.assertEqual(self.tree.scan('lazl',TupleListAction()),[('lazl', -4, None)]) + + def testScan1(self): + timer_start("scan") + for i in xrange(10000): + self.assertEqual(self.tree.scan('lazlo',TupleListAction()),[('lazlo', 5, 'lazlo')]) + self.assertEqual(self.tree.scan('Nicolazlo',TupleListAction()),[('Nico', -4, None), ('lazlo', 5, 'lazlo')]) + timer_end("scan") + + def testScan24(self): + self.assertEqual(self.tree.scan('A NicoNicoNicolasNicoNico',TupleListAction()),[('A N', 3, 'A N'), ('icoNico', -7, None), ('Nicolas', 7, 'Nicolas'), ('NicoNico', -8, None)]) + + def testScan1_1(self): + self.assertEqual(self.tree.scan('hippocampe',TupleListAction()),[('hippocampe', -10, None)]) + + def testScan2(self): + self.assertEqual(self.tree.scan('NicolaNicolaNicolaNicolaNicola',TupleListAction()),[('NicolaNicolaNicolaNicolaNicola', -30, None)]) + + def testScan3(self): + self.assertEqual(self.tree.scan('Nicolasstupide',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('stupide', -7, None)]) + + def testScan4(self): + self.assertEqual(self.tree.scan('Nicolast',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('t', -1, None)]) + + def testScan5(self): + self.assertEqual(self.tree.scan('xxxNicolas',TupleListAction()),[('x', 1, 'x'), ('x', 1, 'x'), ('x', 1, 'x'), ('Nicolas', 7, 'Nicolas')]) + + def testScan6(self): + self.assertEqual(self.tree.scan('xxx Nicolas',TupleListAction()),[('x', 1, 'x'), ('x', 1, 'x'), ('x', 1, 'x'), (' ', -1, None), ('Nicolas', 7, 'Nicolas')]) + + def testScan7(self): + self.assertEqual(self.tree.scan('Antoinette Antoinette',TupleListAction()),[('Antoinette', 10, 'Antoinette'), (' ', -1, None), ('Antoinette', 10, 'Antoinette')]) + + def testScan8(self): + self.assertEqual(self.tree.scan('Nicolas-Antoinette',TupleListAction()),[('Nicolas-Antoinette', 18, 'Nicolas-Antoinette')]) + + def testScan9(self): + self.assertEqual(self.tree.scan('Nicolas-Antoine',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) + + def testScan9_1(self): + self.assertEqual(self.tree.scan('Nicolas-Antoine-Antoine',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) + + def testScan9_2(self): + self.assertEqual(self.tree.scan('Nicolas-Antoine-Antoine-',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None)]) + + def testScan10(self): + self.assertEqual(self.tree.scan('Nicolas-Antoinet',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('t', -1, None)]) + + def testScanWithStopChars1(self): + self.assertEqual(self.tree.scan_with_stop_chars('Nicolas',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas')]) + + def testScanWithStopChars2(self): + self.assertEqual(self.tree.scan_with_stop_chars('Nicolasstupide',' -',TupleListAction()),[('Nicolasstupide', -14, None)]) + + def testScanWithStopChars25(self): + timer_start("scan_stop_chars") + for i in xrange(10000): + self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) + self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) + self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) + timer_end("scan_stop_chars") + + def testScanWithStopChars3(self): + self.assertEqual(self.tree.scan_with_stop_chars('Nicolast',' -',TupleListAction()),[('Nicolast', -8, None)]) + + def testScanWithStopChars4(self): + self.assertEqual(self.tree.scan_with_stop_chars('xxxNicolas',' -',TupleListAction()),[('xxxNicolas', -10, None)]) + + def testScanWithStopChars5(self): + self.assertEqual(self.tree.scan_with_stop_chars('xxx Nicolas',' -',TupleListAction()),[('xxx ', -4, None),('Nicolas', 7, 'Nicolas')]) + + def testScanWithStopChars6(self): + self.assertEqual(self.tree.scan_with_stop_chars('xxxAntoine Nicolas',' -',TupleListAction()),[('xxxAntoine ', -11, None),('Nicolas', 7, 'Nicolas')]) + + def testScanWithStopChars8(self): + self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoinette',' -',TupleListAction()),[('Nicolas-Antoinette', 18, 'Nicolas-Antoinette')]) + + def testScanWithStopChars9(self): + self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoine',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) + + def testScanWithStopChars10(self): + self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoinet',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-Antoinet', -9, None)]) + + def testScanVicieux(self): + self.assertEqual(self.tree.scan_with_stop_chars('xxxAntoine A Nicolas',' -',TupleListAction()),[('xxxAntoine A ', -13, None),('Nicolas', 7, 'Nicolas')]) + + def testScanVicieux2(self): + self.assertEqual(self.tree.scan_with_stop_chars('Antoinette Antoinette',' -',TupleListAction()),[('Antoinette', 10, 'Antoinette'), (' ', -1, None), ('Antoinette', 10, 'Antoinette')]) + + def testScanVicieux3(self): + self.assertEqual(self.tree.scan_with_stop_chars('nastride lazlo',' -',TupleListAction()),[('nastride ', -9, None), ('lazlo', 5, 'lazlo')]) + self.assertEqual(self.tree.scan_with_stop_chars('VIAN ROBERT',' -',TupleListAction()),[('VIAN ', -5, None), ('ROBERT', 6, 'ROBERT')]) + +if __name__ == '__main__': + print "Testing pytst %s"%TST_VERSION + + comment = ' '.join(sys.argv[1:]) + + suite = unittest.TestSuite(( + unittest.makeSuite(TestCollectors), + unittest.makeSuite(TestBasics), + unittest.makeSuite(TestHighCapacity), + unittest.makeSuite(TestScan), + unittest.makeSuite(TestIterators), + unittest.makeSuite(TestMatch), + unittest.makeSuite(TestCallableAction), + unittest.makeSuite(TestCallableFilter), + )) + + for i in xrange(3): + unittest.TextTestRunner().run(suite) + + print_timers(comment)
nlehuen/pytst
f1f99e50aac002d185272a80bd181ef050689fbe
Changed URLs for PyPI
diff --git a/python/setup.py b/python/setup.py index eafc9bd..fa07548 100644 --- a/python/setup.py +++ b/python/setup.py @@ -1,49 +1,49 @@ # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from distutils.core import setup, Extension import sys extra_compile_args = [] setup( name = "pytst", version = "1.17", author = "Nicolas Lehuen", author_email = "nicolas@lehuen.com", - url = "http://nicolas.lehuen.com/index.php/category/Pytst", + url = "http://github.com/nlehuen/pytst", description = "An implementation of a Ternary Search Tree (TST) in C++ with Python bindings", py_modules = ["tst"], ext_modules = [ Extension( "_tst", ["tst_wrap.cxx"], include_dirs=['../include'], extra_compile_args = extra_compile_args, define_macros=[('SCANNER', None),], ) ], - download_url = "http://nicolas.lehuen.com/download/pytst/", + download_url = "http://github.com/nlehuen/pytst/downloads", classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: C++', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Scientific/Engineering :: Information Analysis', ] )
nlehuen/pytst
b18614340cad1de02eef89b3d5e53f9e02e6855b
Upgrade to SWIG version 1.3.39.
diff --git a/python/tst.py b/python/tst.py index 6670819..1394e0a 100644 --- a/python/tst.py +++ b/python/tst.py @@ -1,509 +1,515 @@ # This file was automatically generated by SWIG (http://www.swig.org). -# Version 1.3.38 +# Version 1.3.39 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (3,0,0): new_instancemethod = lambda func, inst, cls: _tst.SWIG_PyInstanceMethod_New(func) else: from new import instancemethod as new_instancemethod if version_info >= (2,6,0): def swig_import_helper(): from os.path import dirname import imp + fp = None try: fp, pathname, description = imp.find_module('_tst', [dirname(__file__)]) - _mod = imp.load_module('_tst', fp, pathname, description) - finally: - if fp is not None: fp.close() - return _mod + except ImportError: + import _tst + return _tst + if fp is not None: + try: + _mod = imp.load_module('_tst', fp, pathname, description) + finally: + fp.close() + return _mod _tst = swig_import_helper() del swig_import_helper else: import _tst del version_info try: _swig_property = property except NameError: pass # Python < 2.2 doesn't have 'property'. def _swig_setattr_nondynamic(self,class_type,name,value,static=1): if (name == "thisown"): return self.this.own(value) if (name == "this"): if type(value).__name__ == 'SwigPyObject': self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name,None) if method: return method(self,value) if (not static) or hasattr(self,name): self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self,class_type,name,value): return _swig_setattr_nondynamic(self,class_type,name,value,0) def _swig_getattr(self,class_type,name): if (name == "thisown"): return self.this.own() method = class_type.__swig_getmethods__.get(name,None) if method: return method(self) raise AttributeError(name) def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) try: _object = object _newclass = 1 except AttributeError: class _object : pass _newclass = 0 def _swig_setattr_nondynamic_method(set): def set_attr(self,name,value): if (name == "thisown"): return self.this.own(value) if hasattr(self,name) or (name == "this"): set(self,name,value) else: raise AttributeError("You cannot add attributes to %s" % self) return set_attr class TSTException(object): """Proxy of C++ TSTException class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): """__init__(self, char _message) -> TSTException""" _tst.TSTException_swiginit(self,_tst.new_TSTException(*args)) def what(self): """what(self) -> char""" return _tst.TSTException_what(self) __swig_destroy__ = _tst.delete_TSTException TSTException.what = new_instancemethod(_tst.TSTException_what,None,TSTException) TSTException_swigregister = _tst.TSTException_swigregister TSTException_swigregister(TSTException) cvar = _tst.cvar TST_VERSION = cvar.TST_VERSION UNDEFINED_INDEX = cvar.UNDEFINED_INDEX class _TST(object): """Proxy of C++ tst<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,string_type)> class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self): """__init__(self) -> _TST""" _tst._TST_swiginit(self,_tst.new__TST()) __swig_destroy__ = _tst.delete__TST def pack(self): """pack(self)""" return _tst._TST_pack(self) def walk(self, *args): """ walk(self, _Filter filter, _Action to_perform) -> PythonReference walk(self, _Filter filter, _Action to_perform, string_type string) -> PythonReference """ return _tst._TST_walk(self, *args) def close_match(self, *args): """ close_match(self, string_type string, int maximum_distance, _Filter filter, _Action to_perform) -> PythonReference """ return _tst._TST_close_match(self, *args) def prefix_match(self, *args): """prefix_match(self, string_type string, _Filter filter, _Action to_perform) -> PythonReference""" return _tst._TST_prefix_match(self, *args) def match(self, *args): """match(self, string_type string, _Filter filter, _Action to_perform) -> PythonReference""" return _tst._TST_match(self, *args) def get(self, *args): """get(self, string_type string) -> PythonReference""" return _tst._TST_get(self, *args) def get_or_build(self, *args): """get_or_build(self, string_type string, _Filter factory) -> PythonReference""" return _tst._TST_get_or_build(self, *args) def put(self, *args): """put(self, string_type string, PythonReference data) -> PythonReference""" return _tst._TST_put(self, *args) def remove(self, *args): """remove(self, string_type string)""" return _tst._TST_remove(self, *args) def contains(self, *args): """contains(self, string_type string) -> bool""" return _tst._TST_contains(self, *args) def write(self, *args): """write(self, std::ostream file)""" return _tst._TST_write(self, *args) def read(self, *args): """read(self, std::istream file)""" return _tst._TST_read(self, *args) def iterator(self, *args): """ iterator(self) -> _lexical_iterator_type iterator(self, string_type string) -> _lexical_iterator_type """ return _tst._TST_iterator(self, *args) def close_match_iterator(self, *args): """close_match_iterator(self, string_type string, int distance) -> _close_match_iterator_type""" return _tst._TST_close_match_iterator(self, *args) def get_number_of_nodes(self): """get_number_of_nodes(self) -> int""" return _tst._TST_get_number_of_nodes(self) def get_default_value(self): """get_default_value(self) -> PythonReference""" return _tst._TST_get_default_value(self) def scan(self, *args): """scan(self, string_type string, _Action to_perform) -> PythonReference""" return _tst._TST_scan(self, *args) def scan_with_stop_chars(self, *args): """scan_with_stop_chars(self, string_type string, string_type stop_chars, _Action to_perform) -> PythonReference""" return _tst._TST_scan_with_stop_chars(self, *args) _TST.pack = new_instancemethod(_tst._TST_pack,None,_TST) _TST.walk = new_instancemethod(_tst._TST_walk,None,_TST) _TST.close_match = new_instancemethod(_tst._TST_close_match,None,_TST) _TST.prefix_match = new_instancemethod(_tst._TST_prefix_match,None,_TST) _TST.match = new_instancemethod(_tst._TST_match,None,_TST) _TST.get = new_instancemethod(_tst._TST_get,None,_TST) _TST.get_or_build = new_instancemethod(_tst._TST_get_or_build,None,_TST) _TST.put = new_instancemethod(_tst._TST_put,None,_TST) _TST.remove = new_instancemethod(_tst._TST_remove,None,_TST) _TST.contains = new_instancemethod(_tst._TST_contains,None,_TST) _TST.write = new_instancemethod(_tst._TST_write,None,_TST) _TST.read = new_instancemethod(_tst._TST_read,None,_TST) _TST.iterator = new_instancemethod(_tst._TST_iterator,None,_TST) _TST.close_match_iterator = new_instancemethod(_tst._TST_close_match_iterator,None,_TST) _TST.get_number_of_nodes = new_instancemethod(_tst._TST_get_number_of_nodes,None,_TST) _TST.get_default_value = new_instancemethod(_tst._TST_get_default_value,None,_TST) _TST.scan = new_instancemethod(_tst._TST_scan,None,_TST) _TST.scan_with_stop_chars = new_instancemethod(_tst._TST_scan_with_stop_chars,None,_TST) _TST_swigregister = _tst._TST_swigregister _TST_swigregister(_TST) class _Action(object): """Proxy of C++ tst_action<(char,PythonReference,string_type)> class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr __swig_destroy__ = _tst.delete__Action def perform(self, *args): """perform(self, string_type string, int remaining_distance, PythonReference data)""" return _tst._Action_perform(self, *args) def result(self): """result(self) -> PythonReference""" return _tst._Action_result(self) _Action.perform = new_instancemethod(_tst._Action_perform,None,_Action) _Action.result = new_instancemethod(_tst._Action_result,None,_Action) _Action_swigregister = _tst._Action_swigregister _Action_swigregister(_Action) class _Filter(object): """Proxy of C++ tst_filter<(char,PythonReference,string_type)> class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr __swig_destroy__ = _tst.delete__Filter def perform(self, *args): """perform(self, string_type string, int remaining_distance, PythonReference data) -> PythonReference""" return _tst._Filter_perform(self, *args) _Filter.perform = new_instancemethod(_tst._Filter_perform,None,_Filter) _Filter_swigregister = _tst._Filter_swigregister _Filter_swigregister(_Filter) class CallableAction(_Action): """Proxy of C++ CallableAction class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): """__init__(self, PythonReference perform, PythonReference result) -> CallableAction""" _tst.CallableAction_swiginit(self,_tst.new_CallableAction(*args)) __swig_destroy__ = _tst.delete_CallableAction CallableAction_swigregister = _tst.CallableAction_swigregister CallableAction_swigregister(CallableAction) class CallableFilter(_Filter): """Proxy of C++ CallableFilter class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): """__init__(self, PythonReference _callable) -> CallableFilter""" _tst.CallableFilter_swiginit(self,_tst.new_CallableFilter(*args)) __swig_destroy__ = _tst.delete_CallableFilter CallableFilter_swigregister = _tst.CallableFilter_swigregister CallableFilter_swigregister(CallableFilter) class DictAction(_Action): """Proxy of C++ DictAction class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self): """__init__(self) -> DictAction""" _tst.DictAction_swiginit(self,_tst.new_DictAction()) __swig_destroy__ = _tst.delete_DictAction DictAction_swigregister = _tst.DictAction_swigregister DictAction_swigregister(DictAction) class ListAction(_Action): """Proxy of C++ ListAction class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self): """__init__(self) -> ListAction""" _tst.ListAction_swiginit(self,_tst.new_ListAction()) __swig_destroy__ = _tst.delete_ListAction ListAction_swigregister = _tst.ListAction_swigregister ListAction_swigregister(ListAction) class TupleListAction(_Action): """Proxy of C++ TupleListAction class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self): """__init__(self) -> TupleListAction""" _tst.TupleListAction_swiginit(self,_tst.new_TupleListAction()) __swig_destroy__ = _tst.delete_TupleListAction TupleListAction_swigregister = _tst.TupleListAction_swigregister TupleListAction_swigregister(TupleListAction) class ObjectSerializer(object): """Proxy of C++ ObjectSerializer class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self): """__init__(self) -> ObjectSerializer""" _tst.ObjectSerializer_swiginit(self,_tst.new_ObjectSerializer()) def write(self, *args): """write(self, std::ostream file, PythonReference data)""" return _tst.ObjectSerializer_write(self, *args) def read(self, *args): """read(self, std::istream file) -> PythonReference""" return _tst.ObjectSerializer_read(self, *args) __swig_destroy__ = _tst.delete_ObjectSerializer ObjectSerializer.write = new_instancemethod(_tst.ObjectSerializer_write,None,ObjectSerializer) ObjectSerializer.read = new_instancemethod(_tst.ObjectSerializer_read,None,ObjectSerializer) ObjectSerializer_swigregister = _tst.ObjectSerializer_swigregister ObjectSerializer_swigregister(ObjectSerializer) class TST(_TST): """Proxy of C++ TST class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self): """__init__(self) -> TST""" _tst.TST_swiginit(self,_tst.new_TST()) __swig_destroy__ = _tst.delete_TST def write_to_file(self, *args): """write_to_file(self, PythonReference file) -> PythonReference""" return _tst.TST_write_to_file(self, *args) def read_from_file(self, *args): """read_from_file(self, PythonReference file) -> PythonReference""" return _tst.TST_read_from_file(self, *args) def __getitem__(self, *args): """__getitem__(self, string_type string) -> PythonReference""" return _tst.TST___getitem__(self, *args) def __setitem__(self, *args): """__setitem__(self, string_type string, PythonReference data) -> PythonReference""" return _tst.TST___setitem__(self, *args) def __delitem__(self, *args): """__delitem__(self, string_type string)""" return _tst.TST___delitem__(self, *args) def __contains__(self, *args): """__contains__(self, string_type string) -> PythonReference""" return _tst.TST___contains__(self, *args) def __iter__(self): """__iter__(self) -> TSTLexicalIterator""" return _tst.TST___iter__(self) def iterator(self, *args): """ iterator(self) -> TSTLexicalIterator iterator(self, string_type string) -> TSTLexicalIterator """ return _tst.TST_iterator(self, *args) def close_match_iterator(self, *args): """close_match_iterator(self, string_type string, int distance) -> TSTCloseMatchIterator""" return _tst.TST_close_match_iterator(self, *args) def put(self, *args): """put(self, string_type string, PythonReference data) -> PythonReference""" return _tst.TST_put(self, *args) def get(self, *args): """get(self, string_type string) -> PythonReference""" return _tst.TST_get(self, *args) def pack(self): """pack(self)""" return _tst.TST_pack(self) def walk(self, *args): """ walk(self, _Filter filter, _Action to_perform) -> PythonReference walk(self, _Filter filter, _Action to_perform, string_type string) -> PythonReference """ return _tst.TST_walk(self, *args) def close_match(self, *args): """ close_match(self, string_type string, int maximum_distance, _Filter filter, _Action to_perform) -> PythonReference """ return _tst.TST_close_match(self, *args) def match(self, *args): """match(self, string_type string, _Filter filter, _Action to_perform) -> PythonReference""" return _tst.TST_match(self, *args) def scan(self, *args): """scan(self, string_type string, _Action to_perform) -> PythonReference""" return _tst.TST_scan(self, *args) def scan_with_stop_chars(self, *args): """scan_with_stop_chars(self, string_type string, string_type stop_chars, _Action to_perform) -> PythonReference""" return _tst.TST_scan_with_stop_chars(self, *args) TST.write_to_file = new_instancemethod(_tst.TST_write_to_file,None,TST) TST.read_from_file = new_instancemethod(_tst.TST_read_from_file,None,TST) TST.__getitem__ = new_instancemethod(_tst.TST___getitem__,None,TST) TST.__setitem__ = new_instancemethod(_tst.TST___setitem__,None,TST) TST.__delitem__ = new_instancemethod(_tst.TST___delitem__,None,TST) TST.__contains__ = new_instancemethod(_tst.TST___contains__,None,TST) TST.__iter__ = new_instancemethod(_tst.TST___iter__,None,TST) TST.iterator = new_instancemethod(_tst.TST_iterator,None,TST) TST.close_match_iterator = new_instancemethod(_tst.TST_close_match_iterator,None,TST) TST.put = new_instancemethod(_tst.TST_put,None,TST) TST.get = new_instancemethod(_tst.TST_get,None,TST) TST.pack = new_instancemethod(_tst.TST_pack,None,TST) TST.walk = new_instancemethod(_tst.TST_walk,None,TST) TST.close_match = new_instancemethod(_tst.TST_close_match,None,TST) TST.match = new_instancemethod(_tst.TST_match,None,TST) TST.scan = new_instancemethod(_tst.TST_scan,None,TST) TST.scan_with_stop_chars = new_instancemethod(_tst.TST_scan_with_stop_chars,None,TST) TST_swigregister = _tst.TST_swigregister TST_swigregister(TST) class _lexical_iterator_type(object): """Proxy of C++ lexical_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,string_type)> class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr state_left = _tst._lexical_iterator_type_state_left state_current = _tst._lexical_iterator_type_state_current state_right = _tst._lexical_iterator_type_state_right state_end = _tst._lexical_iterator_type_state_end def __init__(self, *args): """ __init__(self, tst<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)> t, qad_string<(char)> key, int root) -> _lexical_iterator_type """ _tst._lexical_iterator_type_swiginit(self,_tst.new__lexical_iterator_type(*args)) def next(self): """next(self) -> lexical_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)>::value_type""" return _tst._lexical_iterator_type_next(self) __swig_destroy__ = _tst.delete__lexical_iterator_type _lexical_iterator_type.next = new_instancemethod(_tst._lexical_iterator_type_next,None,_lexical_iterator_type) _lexical_iterator_type_swigregister = _tst._lexical_iterator_type_swigregister _lexical_iterator_type_swigregister(_lexical_iterator_type) class _close_match_iterator_type(object): """Proxy of C++ match_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,string_type)> class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr state_left = _tst._close_match_iterator_type_state_left state_current = _tst._close_match_iterator_type_state_current state_skip_input = _tst._close_match_iterator_type_state_skip_input state_skip_base = _tst._close_match_iterator_type_state_skip_base state_right = _tst._close_match_iterator_type_state_right state_end = _tst._close_match_iterator_type_state_end def __init__(self, *args): """ __init__(self, tst<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)> t, qad_string<(char)> string, int distance, int root) -> _close_match_iterator_type """ _tst._close_match_iterator_type_swiginit(self,_tst.new__close_match_iterator_type(*args)) def next(self): """next(self) -> match_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)>::value_type""" return _tst._close_match_iterator_type_next(self) __swig_destroy__ = _tst.delete__close_match_iterator_type _close_match_iterator_type.next = new_instancemethod(_tst._close_match_iterator_type_next,None,_close_match_iterator_type) _close_match_iterator_type_swigregister = _tst._close_match_iterator_type_swigregister _close_match_iterator_type_swigregister(_close_match_iterator_type) class TSTLexicalIterator(object): """Proxy of C++ TSTIterator<(lexical_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,string_type)>)> class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr def __iter__(self): """__iter__(self) -> TSTLexicalIterator""" return _tst.TSTLexicalIterator___iter__(self) def next(self): """next(self) -> PyObject""" return _tst.TSTLexicalIterator_next(self) __swig_destroy__ = _tst.delete_TSTLexicalIterator TSTLexicalIterator.__iter__ = new_instancemethod(_tst.TSTLexicalIterator___iter__,None,TSTLexicalIterator) TSTLexicalIterator.next = new_instancemethod(_tst.TSTLexicalIterator_next,None,TSTLexicalIterator) TSTLexicalIterator_swigregister = _tst.TSTLexicalIterator_swigregister TSTLexicalIterator_swigregister(TSTLexicalIterator) class TSTCloseMatchIterator(object): """Proxy of C++ TSTIterator<(match_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,string_type)>)> class""" thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr def __iter__(self): """__iter__(self) -> TSTCloseMatchIterator""" return _tst.TSTCloseMatchIterator___iter__(self) def next(self): """next(self) -> PyObject""" return _tst.TSTCloseMatchIterator_next(self) __swig_destroy__ = _tst.delete_TSTCloseMatchIterator TSTCloseMatchIterator.__iter__ = new_instancemethod(_tst.TSTCloseMatchIterator___iter__,None,TSTCloseMatchIterator) TSTCloseMatchIterator.next = new_instancemethod(_tst.TSTCloseMatchIterator_next,None,TSTCloseMatchIterator) TSTCloseMatchIterator_swigregister = _tst.TSTCloseMatchIterator_swigregister TSTCloseMatchIterator_swigregister(TSTCloseMatchIterator) diff --git a/python/tst_wrap.cxx b/python/tst_wrap.cxx index 23fdb6b..afd0327 100644 --- a/python/tst_wrap.cxx +++ b/python/tst_wrap.cxx @@ -1,3392 +1,3445 @@ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). - * Version 1.3.38 + * Version 1.3.39 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make * changes to this file unless you know what you are doing--modify the SWIG * interface file instead. * ----------------------------------------------------------------------------- */ #define SWIGPYTHON #define SWIG_PYTHON_NO_BUILD_NONE #ifdef __cplusplus /* SwigValueWrapper is described in swig.swg */ template<typename T> class SwigValueWrapper { struct SwigMovePointer { T *ptr; SwigMovePointer(T *p) : ptr(p) { } ~SwigMovePointer() { delete ptr; } SwigMovePointer& operator=(SwigMovePointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; } } pointer; SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs); SwigValueWrapper(const SwigValueWrapper<T>& rhs); public: SwigValueWrapper() : pointer(0) { } SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; } operator T&() const { return *pointer.ptr; } T *operator&() { return pointer.ptr; } }; template <typename T> T SwigValueInit() { return T(); } #endif /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # elif defined(__HP_aCC) /* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ /* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIG_MSC_UNSUPPRESS_4505 # if defined(_MSC_VER) # pragma warning(disable : 4505) /* unreferenced local function has been removed */ # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ #if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) # define _SCL_SECURE_NO_DEPRECATE #endif /* Python.h has to appear first */ #include <Python.h> /* ----------------------------------------------------------------------------- * swigrun.swg * * This file contains generic C API SWIG runtime support for pointer * type checking. * ----------------------------------------------------------------------------- */ /* This should only be incremented when either the layout of swig_type_info changes, or for whatever reason, the runtime changes incompatibly */ #define SWIG_RUNTIME_VERSION "4" /* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ #ifdef SWIG_TYPE_TABLE # define SWIG_QUOTE_STRING(x) #x # define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) # define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) #else # define SWIG_TYPE_TABLE_NAME #endif /* You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for creating a static or dynamic library from the SWIG runtime code. In 99.9% of the cases, SWIG just needs to declare them as 'static'. But only do this if strictly necessary, ie, if you have problems with your compiler or suchlike. */ #ifndef SWIGRUNTIME # define SWIGRUNTIME SWIGINTERN #endif #ifndef SWIGRUNTIMEINLINE # define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE #endif /* Generic buffer size */ #ifndef SWIG_BUFFER_SIZE # define SWIG_BUFFER_SIZE 1024 #endif /* Flags for pointer conversions */ #define SWIG_POINTER_DISOWN 0x1 #define SWIG_CAST_NEW_MEMORY 0x2 /* Flags for new pointer objects */ #define SWIG_POINTER_OWN 0x1 /* Flags/methods for returning states. The SWIG conversion methods, as ConvertPtr, return and integer that tells if the conversion was successful or not. And if not, an error code can be returned (see swigerrors.swg for the codes). Use the following macros/flags to set or process the returning states. In old versions of SWIG, code such as the following was usually written: if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { // success code } else { //fail code } Now you can be more explicit: int res = SWIG_ConvertPtr(obj,vptr,ty.flags); if (SWIG_IsOK(res)) { // success code } else { // fail code } which is the same really, but now you can also do Type *ptr; int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); if (SWIG_IsOK(res)) { // success code if (SWIG_IsNewObj(res) { ... delete *ptr; } else { ... } } else { // fail code } I.e., now SWIG_ConvertPtr can return new objects and you can identify the case and take care of the deallocation. Of course that also requires SWIG_ConvertPtr to return new result values, such as int SWIG_ConvertPtr(obj, ptr,...) { if (<obj is ok>) { if (<need new object>) { *ptr = <ptr to new allocated object>; return SWIG_NEWOBJ; } else { *ptr = <ptr to old object>; return SWIG_OLDOBJ; } } else { return SWIG_BADOBJ; } } Of course, returning the plain '0(success)/-1(fail)' still works, but you can be more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the SWIG errors code. Finally, if the SWIG_CASTRANK_MODE is enabled, the result code allows to return the 'cast rank', for example, if you have this int food(double) int fooi(int); and you call food(1) // cast rank '1' (1 -> 1.0) fooi(1) // cast rank '0' just use the SWIG_AddCast()/SWIG_CheckState() */ #define SWIG_OK (0) #define SWIG_ERROR (-1) #define SWIG_IsOK(r) (r >= 0) #define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) /* The CastRankLimit says how many bits are used for the cast rank */ #define SWIG_CASTRANKLIMIT (1 << 8) /* The NewMask denotes the object was created (using new/malloc) */ #define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) /* The TmpMask is for in/out typemaps that use temporal objects */ #define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) /* Simple returning values */ #define SWIG_BADOBJ (SWIG_ERROR) #define SWIG_OLDOBJ (SWIG_OK) #define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) #define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) /* Check, add and del mask methods */ #define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) #define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) #define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) #define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) #define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) #define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) /* Cast-Rank Mode */ #if defined(SWIG_CASTRANK_MODE) # ifndef SWIG_TypeRank # define SWIG_TypeRank unsigned long # endif # ifndef SWIG_MAXCASTRANK /* Default cast allowed */ # define SWIG_MAXCASTRANK (2) # endif # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast # define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) #endif #include <string.h> #ifdef __cplusplus extern "C" { #endif typedef void *(*swig_converter_func)(void *, int *); typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { const char *name; /* mangled name of this type */ const char *str; /* human readable name of this type */ swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ struct swig_cast_info *cast; /* linked list of types that can cast into this type */ void *clientdata; /* language specific type data */ int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { swig_type_info *type; /* pointer to type that is equivalent to this type */ swig_converter_func converter; /* function to cast the void pointers */ struct swig_cast_info *next; /* pointer to next cast in linked list */ struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ size_t size; /* Number of types in this module */ struct swig_module_info *next; /* Pointer to next element in circularly linked list */ swig_type_info **type_initial; /* Array of initially generated type structures */ swig_cast_info **cast_initial; /* Array of initially generated casting structures */ void *clientdata; /* Language specific module data */ } swig_module_info; /* Compare two type names skipping the space characters, therefore "char*" == "char *" and "Class<int>" == "Class<int >", etc. Return 0 when the two name types are equivalent, as in strncmp, but skipping ' '. */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, const char *f2, const char *l2) { for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { while ((*f1 == ' ') && (f1 != l1)) ++f1; while ((*f2 == ' ') && (f2 != l2)) ++f2; if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; } return (int)((l1 - f1) - (l2 - f2)); } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if not equal, 1 if equal */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if equal, -1 if nb < tb, 1 if nb > tb */ SWIGRUNTIME int SWIG_TypeCompare(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* Check the typename */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (strcmp(iter->type->name, c) == 0) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (iter->type == from) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Cast a pointer up an inheritance hierarchy */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* Dynamic pointer casting. Down an inheritance hierarchy */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { swig_type_info *lastty = ty; if (!ty || !ty->dcast) return ty; while (ty && (ty->dcast)) { ty = (*ty->dcast)(ptr); if (ty) lastty = ty; } return lastty; } /* Return the name associated with this type */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { return ty->name; } /* Return the pretty name associated with this type, that is an unmangled type name in a form presentable to the user. */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { /* The "str" field contains the equivalent pretty names of the type, separated by vertical-bar characters. We choose to print the last name, as it is often (?) the most specific. */ if (!type) return NULL; if (type->str != NULL) { const char *last_name = type->str; const char *s; for (s = type->str; *s; s++) if (*s == '|') last_name = s+1; return last_name; } else return type->name; } /* Set the clientdata field for a type */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { swig_cast_info *cast = ti->cast; /* if (ti->clientdata == clientdata) return; */ ti->clientdata = clientdata; while (cast) { if (!cast->converter) { swig_type_info *tc = cast->type; if (!tc->clientdata) { SWIG_TypeClientData(tc, clientdata); } } cast = cast->next; } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIG_TypeClientData(ti, clientdata); ti->owndata = 1; } /* Search for a swig_type_info structure only by mangled name Search is a O(log #types) We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { swig_module_info *iter = start; do { if (iter->size) { register size_t l = 0; register size_t r = iter->size - 1; do { /* since l+r >= 0, we can (>> 1) instead (/ 2) */ register size_t i = (l + r) >> 1; const char *iname = iter->types[i]->name; if (iname) { register int compare = strcmp(name, iname); if (compare == 0) { return iter->types[i]; } else if (compare < 0) { if (i) { r = i - 1; } else { break; } } else if (compare > 0) { l = i + 1; } } else { break; /* should never happen */ } } while (l <= r); } iter = iter->next; } while (iter != end); return 0; } /* Search for a swig_type_info structure for either a mangled name or a human readable name. It first searches the mangled names of the types, which is a O(log #types) If a type is not found it then searches the human readable names, which is O(#types). We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { /* STEP 1: Search the name field using binary search */ swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); if (ret) { return ret; } else { /* STEP 2: If the type hasn't been found, do a complete search of the str field (the human readable name) */ swig_module_info *iter = start; do { register size_t i = 0; for (; i < iter->size; ++i) { if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) return iter->types[i]; } iter = iter->next; } while (iter != end); } /* neither found a match */ return 0; } /* Pack binary data into a string */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { static const char hex[17] = "0123456789abcdef"; register const unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register unsigned char uu = *u; *(c++) = hex[(uu & 0xf0) >> 4]; *(c++) = hex[uu & 0xf]; } return c; } /* Unpack binary data from a string */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { register unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register char d = *(c++); register unsigned char uu; if ((d >= '0') && (d <= '9')) uu = ((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) uu = ((d - ('a'-10)) << 4); else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (d - '0'); else if ((d >= 'a') && (d <= 'f')) uu |= (d - ('a'-10)); else return (char *) 0; *u = uu; } return c; } /* Pack 'void *' into a string buffer. */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { char *r = buff; if ((2*sizeof(void *) + 2) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,&ptr,sizeof(void *)); if (strlen(name) + 1 > (bsz - (r - buff))) return 0; strcpy(r,name); return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { *ptr = (void *) 0; return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { char *r = buff; size_t lname = (name ? strlen(name) : 0); if ((2*sz + 2 + lname) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,ptr,sz); if (lname) { strncpy(r,name,lname+1); } else { *r = 0; } return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { memset(ptr,0,sz); return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sz); } #ifdef __cplusplus } #endif /* Errors in SWIG */ #define SWIG_UnknownError -1 #define SWIG_IOError -2 #define SWIG_RuntimeError -3 #define SWIG_IndexError -4 #define SWIG_TypeError -5 #define SWIG_DivisionByZero -6 #define SWIG_OverflowError -7 #define SWIG_SyntaxError -8 #define SWIG_ValueError -9 #define SWIG_SystemError -10 #define SWIG_AttributeError -11 #define SWIG_MemoryError -12 #define SWIG_NullReferenceError -13 /* Compatibility marcos for Python 3 */ #if PY_VERSION_HEX >= 0x03000000 #define PyClass_Check(obj) PyObject_IsInstance(obj, (PyObject *)&PyType_Type) #define PyInt_Check(x) PyLong_Check(x) #define PyInt_AsLong(x) PyLong_AsLong(x) #define PyInt_FromLong(x) PyLong_FromLong(x) #define PyString_Format(fmt, args) PyUnicode_Format(fmt, args) #endif #ifndef Py_TYPE # define Py_TYPE(op) ((op)->ob_type) #endif /* SWIG APIs for compatibility of both Python 2 & 3 */ #if PY_VERSION_HEX >= 0x03000000 # define SWIG_Python_str_FromFormat PyUnicode_FromFormat #else # define SWIG_Python_str_FromFormat PyString_FromFormat #endif + +/* Warning: This function will allocate a new string in Python 3, + * so please call SWIG_Python_str_DelForPy3(x) to free the space. + */ SWIGINTERN char* SWIG_Python_str_AsChar(PyObject *str) { #if PY_VERSION_HEX >= 0x03000000 + char *cstr; + char *newstr; + int len; str = PyUnicode_AsUTF8String(str); - return PyBytes_AsString(str); + PyBytes_AsStringAndSize(str, &cstr, &len); + newstr = (char *) malloc(len+1); + memcpy(newstr, cstr, len+1); + Py_XDECREF(str); + return newstr; #else return PyString_AsString(str); #endif } +#if PY_VERSION_HEX >= 0x03000000 +# define SWIG_Python_str_DelForPy3(x) free( (void*) (x) ) +#else +# define SWIG_Python_str_DelForPy3(x) +#endif + + SWIGINTERN PyObject* SWIG_Python_str_FromChar(const char *c) { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_FromString(c); #else return PyString_FromString(c); #endif } /* Add PyOS_snprintf for old Pythons */ #if PY_VERSION_HEX < 0x02020000 # if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) # define PyOS_snprintf _snprintf # else # define PyOS_snprintf snprintf # endif #endif /* A crude PyString_FromFormat implementation for old Pythons */ #if PY_VERSION_HEX < 0x02020000 #ifndef SWIG_PYBUFFER_SIZE # define SWIG_PYBUFFER_SIZE 1024 #endif static PyObject * PyString_FromFormat(const char *fmt, ...) { va_list ap; char buf[SWIG_PYBUFFER_SIZE * 2]; int res; va_start(ap, fmt); res = vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf); } #endif /* Add PyObject_Del for old Pythons */ #if PY_VERSION_HEX < 0x01060000 # define PyObject_Del(op) PyMem_DEL((op)) #endif #ifndef PyObject_DEL # define PyObject_DEL PyObject_Del #endif /* A crude PyExc_StopIteration exception for old Pythons */ #if PY_VERSION_HEX < 0x02020000 # ifndef PyExc_StopIteration # define PyExc_StopIteration PyExc_RuntimeError # endif # ifndef PyObject_GenericGetAttr # define PyObject_GenericGetAttr 0 # endif #endif /* Py_NotImplemented is defined in 2.1 and up. */ #if PY_VERSION_HEX < 0x02010000 # ifndef Py_NotImplemented # define Py_NotImplemented PyExc_RuntimeError # endif #endif /* A crude PyString_AsStringAndSize implementation for old Pythons */ #if PY_VERSION_HEX < 0x02010000 # ifndef PyString_AsStringAndSize # define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;} # endif #endif /* PySequence_Size for old Pythons */ #if PY_VERSION_HEX < 0x02000000 # ifndef PySequence_Size # define PySequence_Size PySequence_Length # endif #endif /* PyBool_FromLong for old Pythons */ #if PY_VERSION_HEX < 0x02030000 static PyObject *PyBool_FromLong(long ok) { PyObject *result = ok ? Py_True : Py_False; Py_INCREF(result); return result; } #endif /* Py_ssize_t for old Pythons */ /* This code is as recommended by: */ /* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */ #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; # define PY_SSIZE_T_MAX INT_MAX # define PY_SSIZE_T_MIN INT_MIN #endif /* ----------------------------------------------------------------------------- * error manipulation * ----------------------------------------------------------------------------- */ SWIGRUNTIME PyObject* SWIG_Python_ErrorType(int code) { PyObject* type = 0; switch(code) { case SWIG_MemoryError: type = PyExc_MemoryError; break; case SWIG_IOError: type = PyExc_IOError; break; case SWIG_RuntimeError: type = PyExc_RuntimeError; break; case SWIG_IndexError: type = PyExc_IndexError; break; case SWIG_TypeError: type = PyExc_TypeError; break; case SWIG_DivisionByZero: type = PyExc_ZeroDivisionError; break; case SWIG_OverflowError: type = PyExc_OverflowError; break; case SWIG_SyntaxError: type = PyExc_SyntaxError; break; case SWIG_ValueError: type = PyExc_ValueError; break; case SWIG_SystemError: type = PyExc_SystemError; break; case SWIG_AttributeError: type = PyExc_AttributeError; break; default: type = PyExc_RuntimeError; } return type; } SWIGRUNTIME void SWIG_Python_AddErrorMsg(const char* mesg) { PyObject *type = 0; PyObject *value = 0; PyObject *traceback = 0; if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback); if (value) { + char *tmp; PyObject *old_str = PyObject_Str(value); PyErr_Clear(); Py_XINCREF(type); - PyErr_Format(type, "%s %s", SWIG_Python_str_AsChar(old_str), mesg); + PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); + SWIG_Python_str_DelForPy3(tmp); Py_DECREF(old_str); Py_DECREF(value); } else { PyErr_SetString(PyExc_RuntimeError, mesg); } } #if defined(SWIG_PYTHON_NO_THREADS) # if defined(SWIG_PYTHON_THREADS) # undef SWIG_PYTHON_THREADS # endif #endif #if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */ # if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL) # if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */ # define SWIG_PYTHON_USE_GIL # endif # endif # if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */ # ifndef SWIG_PYTHON_INITIALIZE_THREADS # define SWIG_PYTHON_INITIALIZE_THREADS PyEval_InitThreads() # endif # ifdef __cplusplus /* C++ code */ class SWIG_Python_Thread_Block { bool status; PyGILState_STATE state; public: void end() { if (status) { PyGILState_Release(state); status = false;} } SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} ~SWIG_Python_Thread_Block() { end(); } }; class SWIG_Python_Thread_Allow { bool status; PyThreadState *save; public: void end() { if (status) { PyEval_RestoreThread(save); status = false; }} SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} ~SWIG_Python_Thread_Allow() { end(); } }; # define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block # define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() # define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow # define SWIG_PYTHON_THREAD_END_ALLOW _swig_thread_allow.end() # else /* C code */ # define SWIG_PYTHON_THREAD_BEGIN_BLOCK PyGILState_STATE _swig_thread_block = PyGILState_Ensure() # define SWIG_PYTHON_THREAD_END_BLOCK PyGILState_Release(_swig_thread_block) # define SWIG_PYTHON_THREAD_BEGIN_ALLOW PyThreadState *_swig_thread_allow = PyEval_SaveThread() # define SWIG_PYTHON_THREAD_END_ALLOW PyEval_RestoreThread(_swig_thread_allow) # endif # else /* Old thread way, not implemented, user must provide it */ # if !defined(SWIG_PYTHON_INITIALIZE_THREADS) # define SWIG_PYTHON_INITIALIZE_THREADS # endif # if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK) # define SWIG_PYTHON_THREAD_BEGIN_BLOCK # endif # if !defined(SWIG_PYTHON_THREAD_END_BLOCK) # define SWIG_PYTHON_THREAD_END_BLOCK # endif # if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW) # define SWIG_PYTHON_THREAD_BEGIN_ALLOW # endif # if !defined(SWIG_PYTHON_THREAD_END_ALLOW) # define SWIG_PYTHON_THREAD_END_ALLOW # endif # endif #else /* No thread support */ # define SWIG_PYTHON_INITIALIZE_THREADS # define SWIG_PYTHON_THREAD_BEGIN_BLOCK # define SWIG_PYTHON_THREAD_END_BLOCK # define SWIG_PYTHON_THREAD_BEGIN_ALLOW # define SWIG_PYTHON_THREAD_END_ALLOW #endif /* ----------------------------------------------------------------------------- * Python API portion that goes into the runtime * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* cc-mode */ #endif #endif /* ----------------------------------------------------------------------------- * Constant declarations * ----------------------------------------------------------------------------- */ /* Constant Types */ #define SWIG_PY_POINTER 4 #define SWIG_PY_BINARY 5 /* Constant information structure */ typedef struct swig_const_info { int type; char *name; long lvalue; double dvalue; void *pvalue; swig_type_info **ptype; } swig_const_info; /* ----------------------------------------------------------------------------- * Wrapper of PyInstanceMethod_New() used in Python 3 * It is exported to the generated module, used for -fastproxy * ----------------------------------------------------------------------------- */ SWIGRUNTIME PyObject* SWIG_PyInstanceMethod_New(PyObject *self, PyObject *func) { #if PY_VERSION_HEX >= 0x03000000 return PyInstanceMethod_New(func); #else return NULL; #endif } #ifdef __cplusplus #if 0 { /* cc-mode */ #endif } #endif /* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * * pyrun.swg * * This file contains the runtime support for Python modules * and includes code for managing global variables and pointer * type checking. * * ----------------------------------------------------------------------------- */ /* Common SWIG API */ /* for raw pointers */ #define SWIG_Python_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0) #define SWIG_ConvertPtr(obj, pptr, type, flags) SWIG_Python_ConvertPtr(obj, pptr, type, flags) #define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own) SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own) #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(ptr, type, flags) #define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) #define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) #define swig_owntype int /* for raw packed data */ #define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewPackedObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) /* for class or struct pointers */ #define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_ConvertPtr(obj, pptr, type, flags) #define SWIG_NewInstanceObj(ptr, type, flags) SWIG_NewPointerObj(ptr, type, flags) /* for C or C++ function pointers */ #define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Python_ConvertFunctionPtr(obj, pptr, type) #define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Python_NewPointerObj(ptr, type, 0) /* for C++ member pointers, ie, member methods */ #define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Python_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewMemberObj(ptr, sz, type) SWIG_Python_NewPackedObj(ptr, sz, type) /* Runtime API */ #define SWIG_GetModule(clientdata) SWIG_Python_GetModule() #define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) #define SWIG_NewClientData(obj) SwigPyClientData_New(obj) #define SWIG_SetErrorObj SWIG_Python_SetErrorObj #define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg #define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) #define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) #define SWIG_fail goto fail /* Runtime API implementation */ /* Error manipulation */ SWIGINTERN void SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetObject(errtype, obj); Py_DECREF(obj); SWIG_PYTHON_THREAD_END_BLOCK; } SWIGINTERN void SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { SWIG_PYTHON_THREAD_BEGIN_BLOCK; PyErr_SetString(errtype, (char *) msg); SWIG_PYTHON_THREAD_END_BLOCK; } #define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) /* Set a constant value */ SWIGINTERN void SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { PyDict_SetItemString(d, (char*) name, obj); Py_DECREF(obj); } /* Append a value to the result obj */ SWIGINTERN PyObject* SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { #if !defined(SWIG_PYTHON_OUTPUT_TUPLE) if (!result) { result = obj; } else if (result == Py_None) { Py_DECREF(result); result = obj; } else { if (!PyList_Check(result)) { PyObject *o2 = result; result = PyList_New(1); PyList_SetItem(result, 0, o2); } PyList_Append(result,obj); Py_DECREF(obj); } return result; #else PyObject* o2; PyObject* o3; if (!result) { result = obj; } else if (result == Py_None) { Py_DECREF(result); result = obj; } else { if (!PyTuple_Check(result)) { o2 = result; result = PyTuple_New(1); PyTuple_SET_ITEM(result, 0, o2); } o3 = PyTuple_New(1); PyTuple_SET_ITEM(o3, 0, obj); o2 = result; result = PySequence_Concat(o2, o3); Py_DECREF(o2); Py_DECREF(o3); } return result; #endif } /* Unpack the argument tuple */ SWIGINTERN int SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) { if (!args) { if (!min && !max) { return 1; } else { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", name, (min == max ? "" : "at least "), (int)min); return 0; } } if (!PyTuple_Check(args)) { PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); return 0; } else { register Py_ssize_t l = PyTuple_GET_SIZE(args); if (l < min) { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", name, (min == max ? "" : "at least "), (int)min, (int)l); return 0; } else if (l > max) { PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", name, (min == max ? "" : "at most "), (int)max, (int)l); return 0; } else { register int i; for (i = 0; i < l; ++i) { objs[i] = PyTuple_GET_ITEM(args, i); } for (; l < max; ++l) { objs[l] = 0; } return i + 1; } } } /* A functor is a function object with one single object argument */ #if PY_VERSION_HEX >= 0x02020000 #define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunctionObjArgs(functor, obj, NULL); #else #define SWIG_Python_CallFunctor(functor, obj) PyObject_CallFunction(functor, "O", obj); #endif /* Helper for static pointer initialization for both C and C++ code, for example static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...); */ #ifdef __cplusplus #define SWIG_STATIC_POINTER(var) var #else #define SWIG_STATIC_POINTER(var) var = 0; if (!var) var #endif /* ----------------------------------------------------------------------------- * Pointer declarations * ----------------------------------------------------------------------------- */ /* Flags for new pointer objects */ #define SWIG_POINTER_NOSHADOW (SWIG_POINTER_OWN << 1) #define SWIG_POINTER_NEW (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN) #define SWIG_POINTER_IMPLICIT_CONV (SWIG_POINTER_DISOWN << 1) #ifdef __cplusplus extern "C" { #if 0 } /* cc-mode */ #endif #endif /* How to access Py_None */ #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # ifndef SWIG_PYTHON_NO_BUILD_NONE # ifndef SWIG_PYTHON_BUILD_NONE # define SWIG_PYTHON_BUILD_NONE # endif # endif #endif #ifdef SWIG_PYTHON_BUILD_NONE # ifdef Py_None # undef Py_None # define Py_None SWIG_Py_None() # endif SWIGRUNTIMEINLINE PyObject * _SWIG_Py_None(void) { PyObject *none = Py_BuildValue((char*)""); Py_DECREF(none); return none; } SWIGRUNTIME PyObject * SWIG_Py_None(void) { static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None(); return none; } #endif /* The python void return value */ SWIGRUNTIMEINLINE PyObject * SWIG_Py_Void(void) { PyObject *none = Py_None; Py_INCREF(none); return none; } /* SwigPyClientData */ typedef struct { PyObject *klass; PyObject *newraw; PyObject *newargs; PyObject *destroy; int delargs; int implicitconv; } SwigPyClientData; SWIGRUNTIMEINLINE int SWIG_Python_CheckImplicit(swig_type_info *ty) { SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; return data ? data->implicitconv : 0; } SWIGRUNTIMEINLINE PyObject * SWIG_Python_ExceptionType(swig_type_info *desc) { SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; PyObject *klass = data ? data->klass : 0; return (klass ? klass : PyExc_RuntimeError); } SWIGRUNTIME SwigPyClientData * SwigPyClientData_New(PyObject* obj) { if (!obj) { return 0; } else { SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); /* the klass element */ data->klass = obj; Py_INCREF(data->klass); /* the newraw method and newargs arguments used to create a new raw instance */ if (PyClass_Check(obj)) { data->newraw = 0; data->newargs = obj; Py_INCREF(obj); } else { #if (PY_VERSION_HEX < 0x02020000) data->newraw = 0; #else data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__"); #endif if (data->newraw) { Py_INCREF(data->newraw); data->newargs = PyTuple_New(1); PyTuple_SetItem(data->newargs, 0, obj); } else { data->newargs = obj; } Py_INCREF(data->newargs); } /* the destroy method, aka as the C++ delete method */ data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__"); if (PyErr_Occurred()) { PyErr_Clear(); data->destroy = 0; } if (data->destroy) { int flags; Py_INCREF(data->destroy); flags = PyCFunction_GET_FLAGS(data->destroy); #ifdef METH_O data->delargs = !(flags & (METH_O)); #else data->delargs = 0; #endif } else { data->delargs = 0; } data->implicitconv = 0; return data; } } SWIGRUNTIME void SwigPyClientData_Del(SwigPyClientData* data) { Py_XDECREF(data->newraw); Py_XDECREF(data->newargs); Py_XDECREF(data->destroy); } /* =============== SwigPyObject =====================*/ typedef struct { PyObject_HEAD void *ptr; swig_type_info *ty; int own; PyObject *next; } SwigPyObject; SWIGRUNTIME PyObject * SwigPyObject_long(SwigPyObject *v) { return PyLong_FromVoidPtr(v->ptr); } SWIGRUNTIME PyObject * SwigPyObject_format(const char* fmt, SwigPyObject *v) { PyObject *res = NULL; PyObject *args = PyTuple_New(1); if (args) { if (PyTuple_SetItem(args, 0, SwigPyObject_long(v)) == 0) { PyObject *ofmt = SWIG_Python_str_FromChar(fmt); if (ofmt) { #if PY_VERSION_HEX >= 0x03000000 res = PyUnicode_Format(ofmt,args); #else res = PyString_Format(ofmt,args); #endif Py_DECREF(ofmt); } Py_DECREF(args); } } return res; } SWIGRUNTIME PyObject * SwigPyObject_oct(SwigPyObject *v) { return SwigPyObject_format("%o",v); } SWIGRUNTIME PyObject * SwigPyObject_hex(SwigPyObject *v) { return SwigPyObject_format("%x",v); } SWIGRUNTIME PyObject * #ifdef METH_NOARGS SwigPyObject_repr(SwigPyObject *v) #else SwigPyObject_repr(SwigPyObject *v, PyObject *args) #endif { const char *name = SWIG_TypePrettyName(v->ty); PyObject *hex = SwigPyObject_hex(v); PyObject *repr = SWIG_Python_str_FromFormat("<Swig Object of type '%s' at %p>", name, hex); Py_DECREF(hex); if (v->next) { #ifdef METH_NOARGS PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); #else PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next, args); #endif #if PY_VERSION_HEX >= 0x03000000 PyObject *joined = PyUnicode_Concat(repr, nrep); Py_DecRef(repr); Py_DecRef(nrep); repr = joined; #else PyString_ConcatAndDel(&repr,nrep); #endif } return repr; } SWIGRUNTIME int SwigPyObject_print(SwigPyObject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { + char *str; #ifdef METH_NOARGS PyObject *repr = SwigPyObject_repr(v); #else PyObject *repr = SwigPyObject_repr(v, NULL); #endif if (repr) { - fputs(SWIG_Python_str_AsChar(repr), fp); + str = SWIG_Python_str_AsChar(repr); + fputs(str, fp); + SWIG_Python_str_DelForPy3(str); Py_DECREF(repr); return 0; } else { return 1; } } SWIGRUNTIME PyObject * SwigPyObject_str(SwigPyObject *v) { char result[SWIG_BUFFER_SIZE]; return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ? SWIG_Python_str_FromChar(result) : 0; } SWIGRUNTIME int SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) { void *i = v->ptr; void *j = w->ptr; return (i < j) ? -1 : ((i > j) ? 1 : 0); } /* Added for Python 3.x, whould it also useful for Python 2.x? */ SWIGRUNTIME PyObject* SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) { PyObject* res; if( op != Py_EQ && op != Py_NE ) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } if( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ) res = Py_True; else res = Py_False; Py_INCREF(res); return res; } SWIGRUNTIME PyTypeObject* _PySwigObject_type(void); SWIGRUNTIME PyTypeObject* SwigPyObject_type(void) { static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigObject_type(); return type; } SWIGRUNTIMEINLINE int SwigPyObject_Check(PyObject *op) { return (Py_TYPE(op) == SwigPyObject_type()) || (strcmp(Py_TYPE(op)->tp_name,"SwigPyObject") == 0); } SWIGRUNTIME PyObject * SwigPyObject_New(void *ptr, swig_type_info *ty, int own); SWIGRUNTIME void SwigPyObject_dealloc(PyObject *v) { SwigPyObject *sobj = (SwigPyObject *) v; PyObject *next = sobj->next; if (sobj->own == SWIG_POINTER_OWN) { swig_type_info *ty = sobj->ty; SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; PyObject *destroy = data ? data->destroy : 0; if (destroy) { /* destroy is always a VARARGS method */ PyObject *res; if (data->delargs) { /* we need to create a temporal object to carry the destroy operation */ PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); res = SWIG_Python_CallFunctor(destroy, tmp); Py_DECREF(tmp); } else { PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); PyObject *mself = PyCFunction_GET_SELF(destroy); res = ((*meth)(mself, v)); } Py_XDECREF(res); } #if !defined(SWIG_PYTHON_SILENT_MEMLEAK) else { const char *name = SWIG_TypePrettyName(ty); printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); } #endif } Py_XDECREF(next); PyObject_DEL(v); } SWIGRUNTIME PyObject* SwigPyObject_append(PyObject* v, PyObject* next) { SwigPyObject *sobj = (SwigPyObject *) v; #ifndef METH_O PyObject *tmp = 0; if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL; next = tmp; #endif if (!SwigPyObject_Check(next)) { return NULL; } sobj->next = next; Py_INCREF(next); return SWIG_Py_Void(); } SWIGRUNTIME PyObject* #ifdef METH_NOARGS SwigPyObject_next(PyObject* v) #else SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *) v; if (sobj->next) { Py_INCREF(sobj->next); return sobj->next; } else { return SWIG_Py_Void(); } } SWIGINTERN PyObject* #ifdef METH_NOARGS SwigPyObject_disown(PyObject *v) #else SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *)v; sobj->own = 0; return SWIG_Py_Void(); } SWIGINTERN PyObject* #ifdef METH_NOARGS SwigPyObject_acquire(PyObject *v) #else SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) #endif { SwigPyObject *sobj = (SwigPyObject *)v; sobj->own = SWIG_POINTER_OWN; return SWIG_Py_Void(); } SWIGINTERN PyObject* SwigPyObject_own(PyObject *v, PyObject *args) { PyObject *val = 0; #if (PY_VERSION_HEX < 0x02020000) if (!PyArg_ParseTuple(args,(char *)"|O:own",&val)) #else if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) #endif { return NULL; } else { SwigPyObject *sobj = (SwigPyObject *)v; PyObject *obj = PyBool_FromLong(sobj->own); if (val) { #ifdef METH_NOARGS if (PyObject_IsTrue(val)) { SwigPyObject_acquire(v); } else { SwigPyObject_disown(v); } #else if (PyObject_IsTrue(val)) { SwigPyObject_acquire(v,args); } else { SwigPyObject_disown(v,args); } #endif } return obj; } } #ifdef METH_O static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_NOARGS, (char *)"aquires ownership of the pointer"}, {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)SwigPyObject_append, METH_O, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)SwigPyObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_NOARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #else static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)SwigPyObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)SwigPyObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, {(char *)"own", (PyCFunction)SwigPyObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)SwigPyObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)SwigPyObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)SwigPyObject_repr, METH_VARARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #endif #if PY_VERSION_HEX < 0x02020000 SWIGINTERN PyObject * SwigPyObject_getattr(SwigPyObject *sobj,char *name) { return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); } #endif SWIGRUNTIME PyTypeObject* _PySwigObject_type(void) { static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; static PyNumberMethods SwigPyObject_as_number = { (binaryfunc)0, /*nb_add*/ (binaryfunc)0, /*nb_subtract*/ (binaryfunc)0, /*nb_multiply*/ /* nb_divide removed in Python 3 */ #if PY_VERSION_HEX < 0x03000000 (binaryfunc)0, /*nb_divide*/ #endif (binaryfunc)0, /*nb_remainder*/ (binaryfunc)0, /*nb_divmod*/ (ternaryfunc)0,/*nb_power*/ (unaryfunc)0, /*nb_negative*/ (unaryfunc)0, /*nb_positive*/ (unaryfunc)0, /*nb_absolute*/ (inquiry)0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ #if PY_VERSION_HEX < 0x03000000 0, /*nb_coerce*/ #endif (unaryfunc)SwigPyObject_long, /*nb_int*/ +#if PY_VERSION_HEX < 0x03000000 (unaryfunc)SwigPyObject_long, /*nb_long*/ +#else + 0, /*nb_reserved*/ +#endif (unaryfunc)0, /*nb_float*/ #if PY_VERSION_HEX < 0x03000000 (unaryfunc)SwigPyObject_oct, /*nb_oct*/ (unaryfunc)SwigPyObject_hex, /*nb_hex*/ #endif #if PY_VERSION_HEX >= 0x03000000 /* 3.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ #elif PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ #elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ #elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */ 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ #endif }; static PyTypeObject swigpyobject_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyOjbect header changed in Python 3 */ #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(&PyType_Type, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"SwigPyObject", /* tp_name */ sizeof(SwigPyObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SwigPyObject_dealloc, /* tp_dealloc */ (printfunc)SwigPyObject_print, /* tp_print */ #if PY_VERSION_HEX < 0x02020000 (getattrfunc)SwigPyObject_getattr, /* tp_getattr */ #else (getattrfunc)0, /* tp_getattr */ #endif (setattrfunc)0, /* tp_setattr */ - (cmpfunc)SwigPyObject_compare, /* tp_compare */ +#if PY_VERSION_HEX >= 0x03000000 + 0, /* tp_reserved in 3.0.1 */ +#else + (cmpfunc)SwigPyObject_compare, /* tp_compare */ +#endif (reprfunc)SwigPyObject_repr, /* tp_repr */ &SwigPyObject_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ (reprfunc)SwigPyObject_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigobject_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)SwigPyObject_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ swigobject_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; swigpyobject_type = tmp; /* for Python 3 we already assigned the ob_type in PyVarObject_HEAD_INIT() */ #if PY_VERSION_HEX < 0x03000000 swigpyobject_type.ob_type = &PyType_Type; #endif type_init = 1; } return &swigpyobject_type; } SWIGRUNTIME PyObject * SwigPyObject_New(void *ptr, swig_type_info *ty, int own) { SwigPyObject *sobj = PyObject_NEW(SwigPyObject, SwigPyObject_type()); if (sobj) { sobj->ptr = ptr; sobj->ty = ty; sobj->own = own; sobj->next = 0; } return (PyObject *)sobj; } /* ----------------------------------------------------------------------------- * Implements a simple Swig Packed type, and use it instead of string * ----------------------------------------------------------------------------- */ typedef struct { PyObject_HEAD void *pack; swig_type_info *ty; size_t size; } SwigPyPacked; SWIGRUNTIME int SwigPyPacked_print(SwigPyPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char result[SWIG_BUFFER_SIZE]; fputs("<Swig Packed ", fp); if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { fputs("at ", fp); fputs(result, fp); } fputs(v->ty->name,fp); fputs(">", fp); return 0; } SWIGRUNTIME PyObject * SwigPyPacked_repr(SwigPyPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { return SWIG_Python_str_FromFormat("<Swig Packed at %s%s>", result, v->ty->name); } else { return SWIG_Python_str_FromFormat("<Swig Packed %s>", v->ty->name); } } SWIGRUNTIME PyObject * SwigPyPacked_str(SwigPyPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); } else { return SWIG_Python_str_FromChar(v->ty->name); } } SWIGRUNTIME int SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) { size_t i = v->size; size_t j = w->size; int s = (i < j) ? -1 : ((i > j) ? 1 : 0); return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); } SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void); SWIGRUNTIME PyTypeObject* SwigPyPacked_type(void) { static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type(); return type; } SWIGRUNTIMEINLINE int SwigPyPacked_Check(PyObject *op) { return ((op)->ob_type == _PySwigPacked_type()) || (strcmp((op)->ob_type->tp_name,"SwigPyPacked") == 0); } SWIGRUNTIME void SwigPyPacked_dealloc(PyObject *v) { if (SwigPyPacked_Check(v)) { SwigPyPacked *sobj = (SwigPyPacked *) v; free(sobj->pack); } PyObject_DEL(v); } SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void) { static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; static PyTypeObject swigpypacked_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX>=0x03000000 PyVarObject_HEAD_INIT(&PyType_Type, 0) #else PyObject_HEAD_INIT(NULL) 0, /* ob_size */ #endif (char *)"SwigPyPacked", /* tp_name */ sizeof(SwigPyPacked), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ (printfunc)SwigPyPacked_print, /* tp_print */ (getattrfunc)0, /* tp_getattr */ (setattrfunc)0, /* tp_setattr */ - (cmpfunc)SwigPyPacked_compare, /* tp_compare */ - (reprfunc)SwigPyPacked_repr, /* tp_repr */ - 0, /* tp_as_number */ +#if PY_VERSION_HEX>=0x03000000 + 0, /* tp_reserved in 3.0.1 */ +#else + (cmpfunc)SwigPyPacked_compare, /* tp_compare */ +#endif + (reprfunc)SwigPyPacked_repr, /* tp_repr */ + 0, /* tp_as_number */ 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - (reprfunc)SwigPyPacked_str, /* tp_str */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)SwigPyPacked_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigpacked_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; swigpypacked_type = tmp; /* for Python 3 the ob_type already assigned in PyVarObject_HEAD_INIT() */ #if PY_VERSION_HEX < 0x03000000 swigpypacked_type.ob_type = &PyType_Type; #endif type_init = 1; } return &swigpypacked_type; } SWIGRUNTIME PyObject * SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) { SwigPyPacked *sobj = PyObject_NEW(SwigPyPacked, SwigPyPacked_type()); if (sobj) { void *pack = malloc(size); if (pack) { memcpy(pack, ptr, size); sobj->pack = pack; sobj->ty = ty; sobj->size = size; } else { PyObject_DEL((PyObject *) sobj); sobj = 0; } } return (PyObject *) sobj; } SWIGRUNTIME swig_type_info * SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) { if (SwigPyPacked_Check(obj)) { SwigPyPacked *sobj = (SwigPyPacked *)obj; if (sobj->size != size) return 0; memcpy(ptr, sobj->pack, size); return sobj->ty; } else { return 0; } } /* ----------------------------------------------------------------------------- * pointers/data manipulation * ----------------------------------------------------------------------------- */ SWIGRUNTIMEINLINE PyObject * _SWIG_This(void) { return SWIG_Python_str_FromChar("this"); } SWIGRUNTIME PyObject * SWIG_This(void) { static PyObject *SWIG_STATIC_POINTER(swig_this) = _SWIG_This(); return swig_this; } /* #define SWIG_PYTHON_SLOW_GETSET_THIS */ /* TODO: I don't know how to implement the fast getset in Python 3 right now */ #if PY_VERSION_HEX>=0x03000000 #define SWIG_PYTHON_SLOW_GETSET_THIS #endif SWIGRUNTIME SwigPyObject * SWIG_Python_GetSwigThis(PyObject *pyobj) { if (SwigPyObject_Check(pyobj)) { return (SwigPyObject *) pyobj; } else { PyObject *obj = 0; #if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) if (PyInstance_Check(pyobj)) { obj = _PyInstance_Lookup(pyobj, SWIG_This()); } else { PyObject **dictptr = _PyObject_GetDictPtr(pyobj); if (dictptr != NULL) { PyObject *dict = *dictptr; obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; } else { #ifdef PyWeakref_CheckProxy if (PyWeakref_CheckProxy(pyobj)) { PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; } #endif obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } } } #else obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } #endif if (obj && !SwigPyObject_Check(obj)) { /* a PyObject is called 'this', try to get the 'real this' SwigPyObject from it */ return SWIG_Python_GetSwigThis(obj); } return (SwigPyObject *)obj; } } /* Acquire a pointer value */ SWIGRUNTIME int SWIG_Python_AcquirePtr(PyObject *obj, int own) { if (own == SWIG_POINTER_OWN) { SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); if (sobj) { int oldown = sobj->own; sobj->own = own; return oldown; } } return 0; } /* Convert a pointer value */ SWIGRUNTIME int SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { if (!obj) return SWIG_ERROR; if (obj == Py_None) { if (ptr) *ptr = 0; return SWIG_OK; } else { SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); if (own) *own = 0; while (sobj) { void *vptr = sobj->ptr; if (ty) { swig_type_info *to = sobj->ty; if (to == ty) { /* no type cast needed */ if (ptr) *ptr = vptr; break; } else { swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) { sobj = (SwigPyObject *)sobj->next; } else { if (ptr) { int newmemory = 0; *ptr = SWIG_TypeCast(tc,vptr,&newmemory); if (newmemory == SWIG_CAST_NEW_MEMORY) { assert(own); if (own) *own = *own | SWIG_CAST_NEW_MEMORY; } } break; } } } else { if (ptr) *ptr = vptr; break; } } if (sobj) { if (own) *own = *own | sobj->own; if (flags & SWIG_POINTER_DISOWN) { sobj->own = 0; } return SWIG_OK; } else { int res = SWIG_ERROR; if (flags & SWIG_POINTER_IMPLICIT_CONV) { SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; if (data && !data->implicitconv) { PyObject *klass = data->klass; if (klass) { PyObject *impconv; data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ impconv = SWIG_Python_CallFunctor(klass, obj); data->implicitconv = 0; if (PyErr_Occurred()) { PyErr_Clear(); impconv = 0; } if (impconv) { SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); if (iobj) { void *vptr; res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); if (SWIG_IsOK(res)) { if (ptr) { *ptr = vptr; /* transfer the ownership to 'ptr' */ iobj->own = 0; res = SWIG_AddCast(res); res = SWIG_AddNewMask(res); } else { res = SWIG_AddCast(res); } } } Py_DECREF(impconv); } } } } return res; } } } /* Convert a function ptr value */ SWIGRUNTIME int SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { if (!PyCFunction_Check(obj)) { return SWIG_ConvertPtr(obj, ptr, ty, 0); } else { void *vptr = 0; /* here we get the method pointer for callbacks */ const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; if (desc) { desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; if (!desc) return SWIG_ERROR; } if (ty) { swig_cast_info *tc = SWIG_TypeCheck(desc,ty); if (tc) { int newmemory = 0; *ptr = SWIG_TypeCast(tc,vptr,&newmemory); assert(!newmemory); /* newmemory handling not yet implemented */ } else { return SWIG_ERROR; } } else { *ptr = vptr; } return SWIG_OK; } } /* Convert a packed value value */ SWIGRUNTIME int SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); if (!to) return SWIG_ERROR; if (ty) { if (to != ty) { /* check type cast? */ swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) return SWIG_ERROR; } } return SWIG_OK; } /* ----------------------------------------------------------------------------- * Create a new pointer object * ----------------------------------------------------------------------------- */ /* Create a new instance object, whitout calling __init__, and set the 'this' attribute. */ SWIGRUNTIME PyObject* SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) { #if (PY_VERSION_HEX >= 0x02020000) PyObject *inst = 0; PyObject *newraw = data->newraw; if (newraw) { inst = PyObject_Call(newraw, data->newargs, NULL); if (inst) { #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { PyObject *dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; PyDict_SetItem(dict, SWIG_This(), swig_this); } } #else PyObject *key = SWIG_This(); PyObject_SetAttr(inst, key, swig_this); #endif } } else { #if PY_VERSION_HEX >= 0x03000000 inst = PyBaseObject_Type.tp_new((PyTypeObject*) data->newargs, Py_None, Py_None); - Py_INCREF(data->newargs); PyObject_SetAttr(inst, SWIG_This(), swig_this); Py_TYPE(inst)->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; #else PyObject *dict = PyDict_New(); PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); #endif } return inst; #else #if (PY_VERSION_HEX >= 0x02010000) PyObject *inst; PyObject *dict = PyDict_New(); PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); return (PyObject *) inst; #else PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type); if (inst == NULL) { return NULL; } inst->in_class = (PyClassObject *)data->newargs; Py_INCREF(inst->in_class); inst->in_dict = PyDict_New(); if (inst->in_dict == NULL) { Py_DECREF(inst); return NULL; } #ifdef Py_TPFLAGS_HAVE_WEAKREFS inst->in_weakreflist = NULL; #endif #ifdef Py_TPFLAGS_GC PyObject_GC_Init(inst); #endif PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this); return (PyObject *) inst; #endif #endif } SWIGRUNTIME void SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) { PyObject *dict; #if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; } PyDict_SetItem(dict, SWIG_This(), swig_this); return; } #endif dict = PyObject_GetAttrString(inst, (char*)"__dict__"); PyDict_SetItem(dict, SWIG_This(), swig_this); Py_DECREF(dict); } SWIGINTERN PyObject * SWIG_Python_InitShadowInstance(PyObject *args) { PyObject *obj[2]; if (!SWIG_Python_UnpackTuple(args,(char*)"swiginit", 2, 2, obj)) { return NULL; } else { SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); if (sthis) { SwigPyObject_append((PyObject*) sthis, obj[1]); } else { SWIG_Python_SetSwigThis(obj[0], obj[1]); } return SWIG_Py_Void(); } } /* Create a new pointer object */ SWIGRUNTIME PyObject * SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int flags) { if (!ptr) { return SWIG_Py_Void(); } else { int own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; PyObject *robj = SwigPyObject_New(ptr, type, own); SwigPyClientData *clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); if (inst) { Py_DECREF(robj); robj = inst; } } return robj; } } /* Create a new packed object */ SWIGRUNTIMEINLINE PyObject * SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); } /* -----------------------------------------------------------------------------* * Get type list * -----------------------------------------------------------------------------*/ #ifdef SWIG_LINK_RUNTIME void *SWIG_ReturnGlobalTypeList(void *); #endif SWIGRUNTIME swig_module_info * SWIG_Python_GetModule(void) { static void *type_pointer = (void *)0; /* first check if module already created */ if (!type_pointer) { #ifdef SWIG_LINK_RUNTIME type_pointer = SWIG_ReturnGlobalTypeList((void *)0); #else type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME); if (PyErr_Occurred()) { PyErr_Clear(); type_pointer = (void *)0; } #endif } return (swig_module_info *) type_pointer; } #if PY_MAJOR_VERSION < 2 /* PyModule_AddObject function was introduced in Python 2.0. The following function is copied out of Python/modsupport.c in python version 2.3.4 */ SWIGINTERN int PyModule_AddObject(PyObject *m, char *name, PyObject *o) { PyObject *dict; if (!PyModule_Check(m)) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs module as first arg"); return SWIG_ERROR; } if (!o) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs non-NULL value"); return SWIG_ERROR; } dict = PyModule_GetDict(m); if (dict == NULL) { /* Internal error -- modules must have a dict! */ PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", PyModule_GetName(m)); return SWIG_ERROR; } if (PyDict_SetItemString(dict, name, o)) return SWIG_ERROR; Py_DECREF(o); return SWIG_OK; } #endif SWIGRUNTIME void SWIG_Python_DestroyModule(void *vptr) { swig_module_info *swig_module = (swig_module_info *) vptr; swig_type_info **types = swig_module->types; size_t i; for (i =0; i < swig_module->size; ++i) { swig_type_info *ty = types[i]; if (ty->owndata) { SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; if (data) SwigPyClientData_Del(data); } } Py_DECREF(SWIG_This()); } SWIGRUNTIME void SWIG_Python_SetModule(swig_module_info *swig_module) { static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */ #if PY_VERSION_HEX >= 0x03000000 /* Add a dummy module object into sys.modules */ PyObject *module = PyImport_AddModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION); #else PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); #endif PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule); if (pointer && module) { PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer); } else { Py_XDECREF(pointer); } } /* The python cached type query */ SWIGRUNTIME PyObject * SWIG_Python_TypeCache(void) { static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New(); return cache; } SWIGRUNTIME swig_type_info * SWIG_Python_TypeQuery(const char *type) { PyObject *cache = SWIG_Python_TypeCache(); PyObject *key = SWIG_Python_str_FromChar(type); PyObject *obj = PyDict_GetItem(cache, key); swig_type_info *descriptor; if (obj) { descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj); } else { swig_module_info *swig_module = SWIG_Python_GetModule(); descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); if (descriptor) { obj = PyCObject_FromVoidPtr(descriptor, NULL); PyDict_SetItem(cache, key, obj); Py_DECREF(obj); } } Py_DECREF(key); return descriptor; } /* For backward compatibility only */ #define SWIG_POINTER_EXCEPTION 0 #define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) #define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) SWIGRUNTIME int SWIG_Python_AddErrMesg(const char* mesg, int infront) -{ +{ if (PyErr_Occurred()) { PyObject *type = 0; PyObject *value = 0; PyObject *traceback = 0; PyErr_Fetch(&type, &value, &traceback); if (value) { + char *tmp; PyObject *old_str = PyObject_Str(value); Py_XINCREF(type); PyErr_Clear(); if (infront) { - PyErr_Format(type, "%s %s", mesg, SWIG_Python_str_AsChar(old_str)); + PyErr_Format(type, "%s %s", mesg, tmp = SWIG_Python_str_AsChar(old_str)); } else { - PyErr_Format(type, "%s %s", SWIG_Python_str_AsChar(old_str), mesg); + PyErr_Format(type, "%s %s", tmp = SWIG_Python_str_AsChar(old_str), mesg); } + SWIG_Python_str_DelForPy3(tmp); Py_DECREF(old_str); } return 1; } else { return 0; } } SWIGRUNTIME int SWIG_Python_ArgFail(int argnum) { if (PyErr_Occurred()) { /* add information about failing argument */ char mesg[256]; PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); return SWIG_Python_AddErrMesg(mesg, 1); } else { return 0; } } SWIGRUNTIMEINLINE const char * SwigPyObject_GetDesc(PyObject *self) { SwigPyObject *v = (SwigPyObject *)self; swig_type_info *ty = v ? v->ty : 0; return ty ? ty->str : (char*)""; } SWIGRUNTIME void SWIG_Python_TypeError(const char *type, PyObject *obj) { if (type) { #if defined(SWIG_COBJECT_TYPES) if (obj && SwigPyObject_Check(obj)) { const char *otype = (const char *) SwigPyObject_GetDesc(obj); if (otype) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", type, otype); return; } } else #endif { const char *otype = (obj ? obj->ob_type->tp_name : 0); if (otype) { PyObject *str = PyObject_Str(obj); const char *cstr = str ? SWIG_Python_str_AsChar(str) : 0; if (cstr) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", type, otype, cstr); + SWIG_Python_str_DelForPy3(cstr); } else { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", type, otype); } Py_XDECREF(str); return; } } PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); } else { PyErr_Format(PyExc_TypeError, "unexpected type is received"); } } /* Convert a pointer value, signal an exception on a type mismatch */ SWIGRUNTIME void * SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) { void *result; if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { PyErr_Clear(); - if (flags & SWIG_POINTER_EXCEPTION) { +#if SWIG_POINTER_EXCEPTION + if (flags) { SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj); SWIG_Python_ArgFail(argnum); } +#endif } return result; } #ifdef __cplusplus #if 0 { /* cc-mode */ #endif } #endif #define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) #define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else /* -------- TYPES TABLE (BEGIN) -------- */ #define SWIGTYPE_p_CallableAction swig_types[0] #define SWIGTYPE_p_CallableFilter swig_types[1] #define SWIGTYPE_p_DictAction swig_types[2] #define SWIGTYPE_p_ListAction swig_types[3] #define SWIGTYPE_p_ObjectSerializer swig_types[4] #define SWIGTYPE_p_PythonReference swig_types[5] #define SWIGTYPE_p_TST swig_types[6] #define SWIGTYPE_p_TSTException swig_types[7] #define SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t swig_types[8] #define SWIGTYPE_p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t swig_types[9] #define SWIGTYPE_p_TupleListAction swig_types[10] #define SWIGTYPE_p_char swig_types[11] #define SWIGTYPE_p_character_type swig_types[12] #define SWIGTYPE_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t swig_types[13] #define SWIGTYPE_p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t swig_types[14] #define SWIGTYPE_p_qad_stringT_char_t swig_types[15] #define SWIGTYPE_p_serializer_type swig_types[16] #define SWIGTYPE_p_std__istream swig_types[17] #define SWIGTYPE_p_std__ostream swig_types[18] #define SWIGTYPE_p_std__pairT_qad_stringT_char_t_PythonReference_p_t swig_types[19] #define SWIGTYPE_p_storage_type swig_types[20] #define SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t swig_types[21] #define SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t swig_types[22] #define SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t swig_types[23] #define SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t swig_types[24] #define SWIGTYPE_p_value_type swig_types[25] static swig_type_info *swig_types[27]; static swig_module_info swig_module = {swig_types, 26, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) /* -------- TYPES TABLE (END) -------- */ #if (PY_VERSION_HEX <= 0x02000000) # if !defined(SWIG_PYTHON_CLASSIC) # error "This python version requires swig to be run with the '-classic' option" # endif #endif #if (PY_VERSION_HEX <= 0x02020000) # error "This python version requires swig to be run with the '-nomodern' option" #endif #if (PY_VERSION_HEX <= 0x02020000) # error "This python version requires swig to be run with the '-nomodernargs' option" #endif #ifndef METH_O # error "This python version requires swig to be run with the '-nofastunpack' option" #endif #ifdef SWIG_TypeQuery # undef SWIG_TypeQuery #endif #define SWIG_TypeQuery SWIG_Python_TypeQuery /*----------------------------------------------- @(target):= _tst.so ------------------------------------------------*/ #if PY_VERSION_HEX >= 0x03000000 # define SWIG_init PyInit__tst #else # define SWIG_init init_tst #endif #define SWIG_name "_tst" -#define SWIGVERSION 0x010338 +#define SWIGVERSION 0x010339 #define SWIG_VERSION SWIGVERSION #define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) #define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) #include <stdexcept> namespace swig { class SwigPtr_PyObject { protected: PyObject *_obj; public: SwigPtr_PyObject() :_obj(0) { } SwigPtr_PyObject(const SwigPtr_PyObject& item) : _obj(item._obj) { Py_XINCREF(_obj); } SwigPtr_PyObject(PyObject *obj, bool initial_ref = true) :_obj(obj) { if (initial_ref) { Py_XINCREF(_obj); } } SwigPtr_PyObject & operator=(const SwigPtr_PyObject& item) { Py_XINCREF(item._obj); Py_XDECREF(_obj); _obj = item._obj; return *this; } ~SwigPtr_PyObject() { Py_XDECREF(_obj); } operator PyObject *() const { return _obj; } PyObject *operator->() const { return _obj; } }; } namespace swig { struct SwigVar_PyObject : SwigPtr_PyObject { SwigVar_PyObject(PyObject* obj = 0) : SwigPtr_PyObject(obj, false) { } SwigVar_PyObject & operator = (PyObject* obj) { Py_XDECREF(_obj); _obj = obj; return *this; } }; } SWIGINTERN swig_type_info* SWIG_pchar_descriptor(void) { static int init = 0; static swig_type_info* info = 0; if (!init) { info = SWIG_TypeQuery("_p_char"); init = 1; } return info; } SWIGINTERNINLINE PyObject * SWIG_FromCharPtrAndSize(const char* carray, size_t size) { if (carray) { if (size > INT_MAX) { swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); return pchar_descriptor ? SWIG_NewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : SWIG_Py_Void(); } else { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_FromStringAndSize(carray, static_cast< int >(size)); #else return PyString_FromStringAndSize(carray, static_cast< int >(size)); #endif } } else { return SWIG_Py_Void(); } } SWIGINTERNINLINE PyObject * SWIG_FromCharPtr(const char *cptr) { return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); } #define SWIG_From_long PyInt_FromLong SWIGINTERNINLINE PyObject * SWIG_From_int (int value) { return SWIG_From_long (value); } SWIGINTERN int SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc) { #if PY_VERSION_HEX>=0x03000000 - if (PyUnicode_Check(obj)) + if (PyUnicode_Check(obj)) #else - if (PyString_Check(obj)) + if (PyString_Check(obj)) #endif { char *cstr; Py_ssize_t len; #if PY_VERSION_HEX>=0x03000000 + if (!alloc && cptr) { + /* We can't allow converting without allocation, since the internal + representation of string in Python 3 is UCS-2/UCS-4 but we require + a UTF-8 representation. + TODO(bhy) More detailed explanation */ + return SWIG_RuntimeError; + } obj = PyUnicode_AsUTF8String(obj); PyBytes_AsStringAndSize(obj, &cstr, &len); + if(alloc) *alloc = SWIG_NEWOBJ; #else PyString_AsStringAndSize(obj, &cstr, &len); #endif - if (cptr) { + if (cptr) { if (alloc) { /* In python the user should not be able to modify the inner string representation. To warranty that, if you define SWIG_PYTHON_SAFE_CSTRINGS, a new/copy of the python string buffer is always returned. The default behavior is just to return the pointer value, so, be careful. */ #if defined(SWIG_PYTHON_SAFE_CSTRINGS) if (*alloc != SWIG_OLDOBJ) #else if (*alloc == SWIG_NEWOBJ) #endif { *cptr = reinterpret_cast< char* >(memcpy((new char[len + 1]), cstr, sizeof(char)*(len + 1))); *alloc = SWIG_NEWOBJ; } else { *cptr = cstr; *alloc = SWIG_OLDOBJ; } } else { + #if PY_VERSION_HEX>=0x03000000 + assert(0); /* Should never reach here in Python 3 */ + #endif *cptr = SWIG_Python_str_AsChar(obj); } } if (psize) *psize = len + 1; +#if PY_VERSION_HEX>=0x03000000 + Py_XDECREF(obj); +#endif return SWIG_OK; } else { swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); if (pchar_descriptor) { void* vptr = 0; if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { if (cptr) *cptr = (char *) vptr; if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; if (alloc) *alloc = SWIG_OLDOBJ; return SWIG_OK; } } } return SWIG_TypeError; } #include <limits.h> #if !defined(SWIG_NO_LLONG_MAX) # if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) # define LLONG_MAX __LONG_LONG_MAX__ # define LLONG_MIN (-LLONG_MAX - 1LL) # define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) # endif #endif SWIGINTERN int SWIG_AsVal_double (PyObject *obj, double *val) { int res = SWIG_TypeError; if (PyFloat_Check(obj)) { if (val) *val = PyFloat_AsDouble(obj); return SWIG_OK; } else if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { double v = PyLong_AsDouble(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; double d = PyFloat_AsDouble(obj); if (!PyErr_Occurred()) { if (val) *val = d; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); } else { PyErr_Clear(); } } } #endif return res; } #include <float.h> #include <math.h> SWIGINTERNINLINE int SWIG_CanCastAsInteger(double *d, double min, double max) { double x = *d; if ((min <= x && x <= max)) { double fx = floor(x); double cx = ceil(x); double rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ if ((errno == EDOM) || (errno == ERANGE)) { errno = 0; } else { double summ, reps, diff; if (rd < x) { diff = x - rd; } else if (rd > x) { diff = rd - x; } else { return 1; } summ = rd + x; reps = diff/summ; if (reps < 8*DBL_EPSILON) { *d = rd; return 1; } } } return 0; } SWIGINTERN int SWIG_AsVal_long (PyObject *obj, long* val) { if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; long v = PyInt_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { double d; int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) { if (val) *val = (long)(d); return res; } } } #endif return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_int (PyObject * obj, int *val) { long v; int res = SWIG_AsVal_long (obj, &v); if (SWIG_IsOK(res)) { if ((v < INT_MIN || v > INT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = static_cast< int >(v); } } return res; } SWIGINTERNINLINE PyObject* SWIG_From_bool (bool value) { return PyBool_FromLong(value ? 1 : 0); } #include "pythonTST.h" #ifdef __cplusplus extern "C" { #endif SWIGINTERN int Swig_var_TST_VERSION_set(PyObject *) { SWIG_Error(SWIG_AttributeError,"Variable TST_VERSION is read-only."); return 1; } SWIGINTERN PyObject *Swig_var_TST_VERSION_get(void) { PyObject *pyobj = 0; pyobj = SWIG_FromCharPtr(TST_VERSION); return pyobj; } SWIGINTERN int Swig_var_UNDEFINED_INDEX_set(PyObject *) { SWIG_Error(SWIG_AttributeError,"Variable UNDEFINED_INDEX is read-only."); return 1; } SWIGINTERN PyObject *Swig_var_UNDEFINED_INDEX_get(void) { PyObject *pyobj = 0; pyobj = SWIG_From_int(static_cast< int >(UNDEFINED_INDEX)); return pyobj; } SWIGINTERN PyObject *_wrap_new_TSTException(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; char *arg1 = (char *) 0 ; int res1 ; char *buf1 = 0 ; int alloc1 = 0 ; PyObject *swig_obj[1] ; TSTException *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_AsCharPtrAndSize(swig_obj[0], &buf1, NULL, &alloc1); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_TSTException" "', argument " "1"" of type '" "char const *""'"); } arg1 = reinterpret_cast< char * >(buf1); { try { result = (TSTException *)new TSTException((char const *)arg1); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_TSTException, SWIG_POINTER_NEW | 0 ); if (alloc1 == SWIG_NEWOBJ) delete[] buf1; return resultobj; fail: if (alloc1 == SWIG_NEWOBJ) delete[] buf1; return NULL; } SWIGINTERN PyObject *_wrap_TSTException_what(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTException *arg1 = (TSTException *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; char *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TSTException, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TSTException_what" "', argument " "1"" of type '" "TSTException *""'"); } arg1 = reinterpret_cast< TSTException * >(argp1); { try { result = (char *)(arg1)->what(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_FromCharPtr((const char *)result); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_TSTException(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTException *arg1 = (TSTException *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TSTException, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_TSTException" "', argument " "1"" of type '" "TSTException *""'"); } arg1 = reinterpret_cast< TSTException * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *TSTException_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_TSTException, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *TSTException_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { return SWIG_Python_InitShadowInstance(args); } SWIGINTERN PyObject *_wrap_new__TST(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *result = 0 ; if (!SWIG_Python_UnpackTuple(args,"new__TST",0,0,0)) SWIG_fail; { try { result = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *)new tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete__TST(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete__TST" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_pack(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_pack" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { (arg1)->pack(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_walk__SWIG_0(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; tst_filter< char,PythonReference,string_type > *arg2 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg3 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; PythonReference result; if ((nobjs < 3) || (nobjs > 3)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_walk" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &argp2,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "_TST_walk" "', argument " "2"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg2 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp2); res3 = SWIG_ConvertPtr(swig_obj[2], &argp3,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "_TST_walk" "', argument " "3"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp3); { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->walk(arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_walk__SWIG_1(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; tst_filter< char,PythonReference,string_type > *arg2 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg3 = (tst_action< char,PythonReference,string_type > *) 0 ; string_type *arg4 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; PythonReference result; if ((nobjs < 4) || (nobjs > 4)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_walk" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &argp2,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "_TST_walk" "', argument " "2"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg2 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp2); res3 = SWIG_ConvertPtr(swig_obj[2], &argp3,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "_TST_walk" "', argument " "3"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp3); { @@ -6923,797 +6976,801 @@ static PyMethodDef SwigMethods[] = { { (char *)"TST___delitem__", _wrap_TST___delitem__, METH_VARARGS, (char *)"TST___delitem__(TST self, string_type string)"}, { (char *)"TST___contains__", _wrap_TST___contains__, METH_VARARGS, (char *)"TST___contains__(TST self, string_type string) -> PythonReference"}, { (char *)"TST___iter__", (PyCFunction)_wrap_TST___iter__, METH_O, (char *)"TST___iter__(TST self) -> TSTLexicalIterator"}, { (char *)"TST_iterator", _wrap_TST_iterator, METH_VARARGS, (char *)"\n" "iterator() -> TSTLexicalIterator\n" "TST_iterator(TST self, string_type string) -> TSTLexicalIterator\n" ""}, { (char *)"TST_close_match_iterator", _wrap_TST_close_match_iterator, METH_VARARGS, (char *)"TST_close_match_iterator(TST self, string_type string, int distance) -> TSTCloseMatchIterator"}, { (char *)"TST_put", _wrap_TST_put, METH_VARARGS, (char *)"TST_put(TST self, string_type string, PythonReference data) -> PythonReference"}, { (char *)"TST_get", _wrap_TST_get, METH_VARARGS, (char *)"TST_get(TST self, string_type string) -> PythonReference"}, { (char *)"TST_pack", (PyCFunction)_wrap_TST_pack, METH_O, (char *)"TST_pack(TST self)"}, { (char *)"TST_walk", _wrap_TST_walk, METH_VARARGS, (char *)"\n" "walk(_Filter filter, _Action to_perform) -> PythonReference\n" "TST_walk(TST self, _Filter filter, _Action to_perform, string_type string) -> PythonReference\n" ""}, { (char *)"TST_close_match", _wrap_TST_close_match, METH_VARARGS, (char *)"\n" "TST_close_match(TST self, string_type string, int maximum_distance, \n" " _Filter filter, _Action to_perform) -> PythonReference\n" ""}, { (char *)"TST_match", _wrap_TST_match, METH_VARARGS, (char *)"TST_match(TST self, string_type string, _Filter filter, _Action to_perform) -> PythonReference"}, { (char *)"TST_scan", _wrap_TST_scan, METH_VARARGS, (char *)"TST_scan(TST self, string_type string, _Action to_perform) -> PythonReference"}, { (char *)"TST_scan_with_stop_chars", _wrap_TST_scan_with_stop_chars, METH_VARARGS, (char *)"\n" "TST_scan_with_stop_chars(TST self, string_type string, string_type stop_chars, \n" " _Action to_perform) -> PythonReference\n" ""}, { (char *)"TST_swigregister", TST_swigregister, METH_VARARGS, NULL}, { (char *)"TST_swiginit", TST_swiginit, METH_VARARGS, NULL}, { (char *)"new__lexical_iterator_type", _wrap_new__lexical_iterator_type, METH_VARARGS, (char *)"\n" "new__lexical_iterator_type(tst<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)> t, \n" " qad_string<(char)> key, \n" " int root) -> _lexical_iterator_type\n" ""}, { (char *)"_lexical_iterator_type_next", (PyCFunction)_wrap__lexical_iterator_type_next, METH_O, (char *)"_lexical_iterator_type_next(_lexical_iterator_type self) -> lexical_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)>::value_type"}, { (char *)"delete__lexical_iterator_type", (PyCFunction)_wrap_delete__lexical_iterator_type, METH_O, (char *)"delete__lexical_iterator_type(_lexical_iterator_type self)"}, { (char *)"_lexical_iterator_type_swigregister", _lexical_iterator_type_swigregister, METH_VARARGS, NULL}, { (char *)"_lexical_iterator_type_swiginit", _lexical_iterator_type_swiginit, METH_VARARGS, NULL}, { (char *)"new__close_match_iterator_type", _wrap_new__close_match_iterator_type, METH_VARARGS, (char *)"\n" "new__close_match_iterator_type(tst<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)> t, \n" " qad_string<(char)> string, \n" " int distance, \n" " int root) -> _close_match_iterator_type\n" ""}, { (char *)"_close_match_iterator_type_next", (PyCFunction)_wrap__close_match_iterator_type_next, METH_O, (char *)"_close_match_iterator_type_next(_close_match_iterator_type self) -> match_iterator<(char,PythonReference,memory_storage<(char,PythonReference)>,ObjectSerializer,qad_string<(char)>)>::value_type"}, { (char *)"delete__close_match_iterator_type", (PyCFunction)_wrap_delete__close_match_iterator_type, METH_O, (char *)"delete__close_match_iterator_type(_close_match_iterator_type self)"}, { (char *)"_close_match_iterator_type_swigregister", _close_match_iterator_type_swigregister, METH_VARARGS, NULL}, { (char *)"_close_match_iterator_type_swiginit", _close_match_iterator_type_swiginit, METH_VARARGS, NULL}, { (char *)"TSTLexicalIterator___iter__", (PyCFunction)_wrap_TSTLexicalIterator___iter__, METH_O, (char *)"TSTLexicalIterator___iter__(TSTLexicalIterator self) -> TSTLexicalIterator"}, { (char *)"TSTLexicalIterator_next", (PyCFunction)_wrap_TSTLexicalIterator_next, METH_O, (char *)"TSTLexicalIterator_next(TSTLexicalIterator self) -> PyObject"}, { (char *)"delete_TSTLexicalIterator", (PyCFunction)_wrap_delete_TSTLexicalIterator, METH_O, (char *)"delete_TSTLexicalIterator(TSTLexicalIterator self)"}, { (char *)"TSTLexicalIterator_swigregister", TSTLexicalIterator_swigregister, METH_VARARGS, NULL}, { (char *)"TSTCloseMatchIterator___iter__", (PyCFunction)_wrap_TSTCloseMatchIterator___iter__, METH_O, (char *)"TSTCloseMatchIterator___iter__(TSTCloseMatchIterator self) -> TSTCloseMatchIterator"}, { (char *)"TSTCloseMatchIterator_next", (PyCFunction)_wrap_TSTCloseMatchIterator_next, METH_O, (char *)"TSTCloseMatchIterator_next(TSTCloseMatchIterator self) -> PyObject"}, { (char *)"delete_TSTCloseMatchIterator", (PyCFunction)_wrap_delete_TSTCloseMatchIterator, METH_O, (char *)"delete_TSTCloseMatchIterator(TSTCloseMatchIterator self)"}, { (char *)"TSTCloseMatchIterator_swigregister", TSTCloseMatchIterator_swigregister, METH_VARARGS, NULL}, { NULL, NULL, 0, NULL } }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ static void *_p_CallableFilterTo_p_tst_filterT_char_PythonReference_string_type_t(void *x, int *SWIGUNUSEDPARM(newmemory)) { return (void *)((tst_filter< char,PythonReference,string_type > *) ((CallableFilter *) x)); } static void *_p_DictActionTo_p_tst_actionT_char_PythonReference_string_type_t(void *x, int *SWIGUNUSEDPARM(newmemory)) { return (void *)((tst_action< char,PythonReference,string_type > *) ((DictAction *) x)); } static void *_p_ListActionTo_p_tst_actionT_char_PythonReference_string_type_t(void *x, int *SWIGUNUSEDPARM(newmemory)) { return (void *)((tst_action< char,PythonReference,string_type > *) ((ListAction *) x)); } static void *_p_TupleListActionTo_p_tst_actionT_char_PythonReference_string_type_t(void *x, int *SWIGUNUSEDPARM(newmemory)) { return (void *)((tst_action< char,PythonReference,string_type > *) ((TupleListAction *) x)); } static void *_p_CallableActionTo_p_tst_actionT_char_PythonReference_string_type_t(void *x, int *SWIGUNUSEDPARM(newmemory)) { return (void *)((tst_action< char,PythonReference,string_type > *) ((CallableAction *) x)); } static void *_p_TSTTo_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t(void *x, int *SWIGUNUSEDPARM(newmemory)) { return (void *)((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) ((TST *) x)); } static swig_type_info _swigt__p_CallableAction = {"_p_CallableAction", "CallableAction *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_CallableFilter = {"_p_CallableFilter", "CallableFilter *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_DictAction = {"_p_DictAction", "DictAction *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ListAction = {"_p_ListAction", "ListAction *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_ObjectSerializer = {"_p_ObjectSerializer", "ObjectSerializer *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_PythonReference = {"_p_PythonReference", "PythonReference *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_TST = {"_p_TST", "TST *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_TSTException = {"_p_TSTException", "TSTException *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t = {"_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t", "TSTLexicalIterator *|TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > *|TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t = {"_p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t", "TSTCloseMatchIterator *|TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > *|TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_TupleListAction = {"_p_TupleListAction", "TupleListAction *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_character_type = {"_p_character_type", "character_type *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t = {"_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t", "lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *|lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t = {"_p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t", "match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *|match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_qad_stringT_char_t = {"_p_qad_stringT_char_t", "string_type *|qad_string< char > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_serializer_type = {"_p_serializer_type", "serializer_type *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_std__istream = {"_p_std__istream", "std::istream *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_std__ostream = {"_p_std__ostream", "std::ostream *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_std__pairT_qad_stringT_char_t_PythonReference_p_t = {"_p_std__pairT_qad_stringT_char_t_PythonReference_p_t", "match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type *|std::pair< qad_string< char >,PythonReference * > *|lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_storage_type = {"_p_storage_type", "storage_type *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t = {"_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t", "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t = {"_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t", "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_tst_actionT_char_PythonReference_string_type_t = {"_p_tst_actionT_char_PythonReference_string_type_t", "tst_action< char,PythonReference,string_type > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_tst_filterT_char_PythonReference_string_type_t = {"_p_tst_filterT_char_PythonReference_string_type_t", "tst_filter< char,PythonReference,string_type > *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_value_type = {"_p_value_type", "value_type *", 0, 0, (void*)0, 0}; static swig_type_info *swig_type_initial[] = { &_swigt__p_CallableAction, &_swigt__p_CallableFilter, &_swigt__p_DictAction, &_swigt__p_ListAction, &_swigt__p_ObjectSerializer, &_swigt__p_PythonReference, &_swigt__p_TST, &_swigt__p_TSTException, &_swigt__p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, &_swigt__p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, &_swigt__p_TupleListAction, &_swigt__p_char, &_swigt__p_character_type, &_swigt__p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, &_swigt__p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, &_swigt__p_qad_stringT_char_t, &_swigt__p_serializer_type, &_swigt__p_std__istream, &_swigt__p_std__ostream, &_swigt__p_std__pairT_qad_stringT_char_t_PythonReference_p_t, &_swigt__p_storage_type, &_swigt__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, &_swigt__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, &_swigt__p_tst_actionT_char_PythonReference_string_type_t, &_swigt__p_tst_filterT_char_PythonReference_string_type_t, &_swigt__p_value_type, }; static swig_cast_info _swigc__p_CallableAction[] = { {&_swigt__p_CallableAction, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_CallableFilter[] = { {&_swigt__p_CallableFilter, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_DictAction[] = { {&_swigt__p_DictAction, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ListAction[] = { {&_swigt__p_ListAction, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ObjectSerializer[] = { {&_swigt__p_ObjectSerializer, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_PythonReference[] = { {&_swigt__p_PythonReference, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TST[] = { {&_swigt__p_TST, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TSTException[] = { {&_swigt__p_TSTException, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t[] = { {&_swigt__p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t[] = { {&_swigt__p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TupleListAction[] = { {&_swigt__p_TupleListAction, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_character_type[] = { {&_swigt__p_character_type, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t[] = { {&_swigt__p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t[] = { {&_swigt__p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_qad_stringT_char_t[] = { {&_swigt__p_qad_stringT_char_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_serializer_type[] = { {&_swigt__p_serializer_type, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_std__istream[] = { {&_swigt__p_std__istream, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_std__ostream[] = { {&_swigt__p_std__ostream, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_std__pairT_qad_stringT_char_t_PythonReference_p_t[] = { {&_swigt__p_std__pairT_qad_stringT_char_t_PythonReference_p_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_storage_type[] = { {&_swigt__p_storage_type, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t[] = { {&_swigt__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t[] = { {&_swigt__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0, 0, 0}, {&_swigt__p_TST, _p_TSTTo_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_tst_actionT_char_PythonReference_string_type_t[] = { {&_swigt__p_tst_actionT_char_PythonReference_string_type_t, 0, 0, 0}, {&_swigt__p_DictAction, _p_DictActionTo_p_tst_actionT_char_PythonReference_string_type_t, 0, 0}, {&_swigt__p_ListAction, _p_ListActionTo_p_tst_actionT_char_PythonReference_string_type_t, 0, 0}, {&_swigt__p_TupleListAction, _p_TupleListActionTo_p_tst_actionT_char_PythonReference_string_type_t, 0, 0}, {&_swigt__p_CallableAction, _p_CallableActionTo_p_tst_actionT_char_PythonReference_string_type_t, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_tst_filterT_char_PythonReference_string_type_t[] = { {&_swigt__p_CallableFilter, _p_CallableFilterTo_p_tst_filterT_char_PythonReference_string_type_t, 0, 0}, {&_swigt__p_tst_filterT_char_PythonReference_string_type_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_value_type[] = { {&_swigt__p_value_type, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { _swigc__p_CallableAction, _swigc__p_CallableFilter, _swigc__p_DictAction, _swigc__p_ListAction, _swigc__p_ObjectSerializer, _swigc__p_PythonReference, _swigc__p_TST, _swigc__p_TSTException, _swigc__p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, _swigc__p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, _swigc__p_TupleListAction, _swigc__p_char, _swigc__p_character_type, _swigc__p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, _swigc__p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, _swigc__p_qad_stringT_char_t, _swigc__p_serializer_type, _swigc__p_std__istream, _swigc__p_std__ostream, _swigc__p_std__pairT_qad_stringT_char_t_PythonReference_p_t, _swigc__p_storage_type, _swigc__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, _swigc__p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, _swigc__p_tst_actionT_char_PythonReference_string_type_t, _swigc__p_tst_filterT_char_PythonReference_string_type_t, _swigc__p_value_type, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ static swig_const_info swig_const_table[] = { {0, 0, 0, 0.0, 0, 0}}; #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * Type initialization: * This problem is tough by the requirement that no dynamic * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back * to swig_type_info structures, we need some lookup code at initialization. * The idea is that swig generates all the structures that are needed. * The runtime then collects these partially filled structures. * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * * The generated swig_type_info structures are assigned staticly to an initial * array. We just loop through that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the * cast linked list. The cast data is initially stored in something like a * two-dimensional array. Each row corresponds to a type (there are the same * number of rows as there are in the swig_type_initial array). Each entry in * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that * swig_cast_info to the linked list (because the cast->type) pointer will * be correct. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* c-mode */ #endif #endif #if 0 #define SWIGRUNTIME_DEBUG #endif SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) { size_t i; swig_module_info *module_head, *iter; int found, init; clientdata = clientdata; /* check to see if the circular list has been setup, if not, set it up */ if (swig_module.next==0) { /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; init = 1; } else { init = 0; } /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (!module_head) { /* This is the first module loaded for this interpreter */ /* so set the swig module into the interpreter */ SWIG_SetModule(clientdata, &swig_module); module_head = &swig_module; } else { /* the interpreter has loaded a SWIG module, but has it loaded this one? */ found=0; iter=module_head; do { if (iter==&swig_module) { found=1; break; } iter=iter->next; } while (iter!= module_head); /* if the is found in the list, then all is done and we may leave */ if (found) return; /* otherwise we must add out module into the list */ swig_module.next = module_head->next; module_head->next = &swig_module; } /* When multiple interpeters are used, a module could have already been initialized in a different interpreter, but not yet have a pointer in this interpreter. In this case, we do not want to continue adding types... everything should be set up already */ if (init == 0) return; /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); #endif for (i = 0; i < swig_module.size; ++i) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); #endif /* if there is another module already loaded */ if (swig_module.next != &swig_module) { type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found type %s\n", type->name); #endif if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); #endif } } else { type = swig_module.type_initial[i]; } /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif cast->type = ret; ret = 0; } else { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif if (!ocast) ret = 0; } } if (!ret) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif if (type->cast) { type->cast->prev = cast; cast->next = type->cast; } type->cast = cast; } cast++; } /* Set entry in modules->types array equal to the type */ swig_module.types[i] = type; } swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } printf("---- Total casts: %d\n",j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } /* This function will propagate the clientdata field of type to * any new swig_type_info structures that have been added into the list * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ SWIGRUNTIME void SWIG_PropagateClientData(void) { size_t i; swig_cast_info *equiv; static int init_run = 0; if (init_run) return; init_run = 1; for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } equiv = equiv->next; } } } } #ifdef __cplusplus #if 0 { /* c-mode */ #endif } #endif #ifdef __cplusplus extern "C" { #endif /* Python-specific SWIG API */ #define SWIG_newvarlink() SWIG_Python_newvarlink() #define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) #define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) /* ----------------------------------------------------------------------------- * global variable support code. * ----------------------------------------------------------------------------- */ typedef struct swig_globalvar { char *name; /* Name of global variable */ PyObject *(*get_attr)(void); /* Return the current value */ int (*set_attr)(PyObject *); /* Set the value */ struct swig_globalvar *next; } swig_globalvar; typedef struct swig_varlinkobject { PyObject_HEAD swig_globalvar *vars; } swig_varlinkobject; SWIGINTERN PyObject * swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { #if PY_VERSION_HEX >= 0x03000000 return PyUnicode_InternFromString("<Swig global variables>"); #else return PyString_FromString("<Swig global variables>"); #endif } SWIGINTERN PyObject * swig_varlink_str(swig_varlinkobject *v) { #if PY_VERSION_HEX >= 0x03000000 PyObject *str = PyUnicode_InternFromString("("); PyObject *tail; PyObject *joined; swig_globalvar *var; for (var = v->vars; var; var=var->next) { tail = PyUnicode_FromString(var->name); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; if (var->next) { tail = PyUnicode_InternFromString(", "); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; } } tail = PyUnicode_InternFromString(")"); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; #else PyObject *str = PyString_FromString("("); swig_globalvar *var; for (var = v->vars; var; var=var->next) { PyString_ConcatAndDel(&str,PyString_FromString(var->name)); if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); } PyString_ConcatAndDel(&str,PyString_FromString(")")); #endif return str; } SWIGINTERN int swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { + char *tmp; PyObject *str = swig_varlink_str(v); fprintf(fp,"Swig global variables "); - fprintf(fp,"%s\n", SWIG_Python_str_AsChar(str)); + fprintf(fp,"%s\n", tmp = SWIG_Python_str_AsChar(str)); + SWIG_Python_str_DelForPy3(tmp); Py_DECREF(str); return 0; } SWIGINTERN void swig_varlink_dealloc(swig_varlinkobject *v) { swig_globalvar *var = v->vars; while (var) { swig_globalvar *n = var->next; free(var->name); free(var); var = n; } } SWIGINTERN PyObject * swig_varlink_getattr(swig_varlinkobject *v, char *n) { PyObject *res = NULL; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->get_attr)(); break; } var = var->next; } if (res == NULL && !PyErr_Occurred()) { PyErr_SetString(PyExc_NameError,"Unknown C global variable"); } return res; } SWIGINTERN int swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { int res = 1; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->set_attr)(p); break; } var = var->next; } if (res == 1 && !PyErr_Occurred()) { PyErr_SetString(PyExc_NameError,"Unknown C global variable"); } return res; } SWIGINTERN PyTypeObject* swig_varlink_type(void) { static char varlink__doc__[] = "Swig var link object"; static PyTypeObject varlink_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { /* PyObject header changed in Python 3 */ #if PY_VERSION_HEX >= 0x03000000 PyVarObject_HEAD_INIT(&PyType_Type, 0) #else PyObject_HEAD_INIT(NULL) 0, /* Number of items in variable part (ob_size) */ #endif (char *)"swigvarlink", /* Type name (tp_name) */ sizeof(swig_varlinkobject), /* Basic size (tp_basicsize) */ 0, /* Itemsize (tp_itemsize) */ (destructor) swig_varlink_dealloc, /* Deallocator (tp_dealloc) */ (printfunc) swig_varlink_print, /* Print (tp_print) */ (getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */ (setattrfunc) swig_varlink_setattr, /* Set attr (tp_setattr) */ 0, /* tp_compare */ (reprfunc) swig_varlink_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)swig_varlink_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ varlink__doc__, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; varlink_type = tmp; /* for Python 3 we already assigned the ob_type in PyVarObject_HEAD_INIT() */ #if PY_VERSION_HEX < 0x03000000 varlink_type.ob_type = &PyType_Type; #endif type_init = 1; } return &varlink_type; } /* Create a variable linking object for use later */ SWIGINTERN PyObject * SWIG_Python_newvarlink(void) { swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type()); if (result) { result->vars = 0; } return ((PyObject*) result); } SWIGINTERN void SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { swig_varlinkobject *v = (swig_varlinkobject *) p; swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); if (gv) { size_t size = strlen(name)+1; gv->name = (char *)malloc(size); if (gv->name) { strncpy(gv->name,name,size); gv->get_attr = get_attr; gv->set_attr = set_attr; gv->next = v->vars; } } v->vars = gv; } SWIGINTERN PyObject * SWIG_globals(void) { static PyObject *_SWIG_globals = 0; if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink(); return _SWIG_globals; } /* ----------------------------------------------------------------------------- * constants/methods manipulation * ----------------------------------------------------------------------------- */ /* Install Constants */ SWIGINTERN void SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { PyObject *obj = 0; size_t i; for (i = 0; constants[i].type; ++i) { switch(constants[i].type) { case SWIG_PY_POINTER: obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); break; case SWIG_PY_BINARY: obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); break; default: obj = 0; break; } if (obj) { PyDict_SetItemString(d, constants[i].name, obj); Py_DECREF(obj); } } } /* -----------------------------------------------------------------------------*/ /* Fix SwigMethods to carry the callback ptrs when needed */ /* -----------------------------------------------------------------------------*/ SWIGINTERN void SWIG_Python_FixMethods(PyMethodDef *methods, swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { size_t i; for (i = 0; methods[i].ml_name; ++i) { const char *c = methods[i].ml_doc; if (c && (c = strstr(c, "swig_ptr: "))) { int j; swig_const_info *ci = 0; const char *name = c + 10; for (j = 0; const_table[j].type; ++j) { if (strncmp(const_table[j].name, name, strlen(const_table[j].name)) == 0) { ci = &(const_table[j]); break; } } if (ci) { size_t shift = (ci->ptype) - types; swig_type_info *ty = types_initial[shift]; size_t ldoc = (c - methods[i].ml_doc); size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; char *ndoc = (char*)malloc(ldoc + lptr + 10); if (ndoc) { char *buff = ndoc; void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; if (ptr) { strncpy(buff, methods[i].ml_doc, ldoc); buff += ldoc; strncpy(buff, "swig_ptr: ", 10); buff += 10; SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); methods[i].ml_doc = ndoc; } } } } } } #ifdef __cplusplus } #endif /* -----------------------------------------------------------------------------* * Partial Init method * -----------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" #endif SWIGEXPORT #if PY_VERSION_HEX >= 0x03000000 PyObject* #else void #endif SWIG_init(void) { - PyObject *m, *d; - - /* Fix SwigMethods to carry the callback ptrs when needed */ - SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); + PyObject *m, *d; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef SWIG_module = { PyModuleDef_HEAD_INIT, (char *) SWIG_name, NULL, -1, SwigMethods, NULL, NULL, NULL, NULL }; +#endif + /* Fix SwigMethods to carry the callback ptrs when needed */ + SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); + +#if PY_VERSION_HEX >= 0x03000000 m = PyModule_Create(&SWIG_module); #else m = Py_InitModule((char *) SWIG_name, SwigMethods); #endif d = PyModule_GetDict(m); SWIG_InitializeModule(0); SWIG_InstallConstants(d,swig_const_table); PyDict_SetItemString(d,(char*)"cvar", SWIG_globals()); SWIG_addvarlink(SWIG_globals(),(char*)"TST_VERSION",Swig_var_TST_VERSION_get, Swig_var_TST_VERSION_set); SWIG_addvarlink(SWIG_globals(),(char*)"UNDEFINED_INDEX",Swig_var_UNDEFINED_INDEX_get, Swig_var_UNDEFINED_INDEX_set); SWIG_Python_SetConstant(d, "_lexical_iterator_type_state_left",SWIG_From_int(static_cast< int >(lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >::state_left))); SWIG_Python_SetConstant(d, "_lexical_iterator_type_state_current",SWIG_From_int(static_cast< int >(lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >::state_current))); SWIG_Python_SetConstant(d, "_lexical_iterator_type_state_right",SWIG_From_int(static_cast< int >(lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >::state_right))); SWIG_Python_SetConstant(d, "_lexical_iterator_type_state_end",SWIG_From_int(static_cast< int >(lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >::state_end))); SWIG_Python_SetConstant(d, "_close_match_iterator_type_state_left",SWIG_From_int(static_cast< int >(match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >::state_left))); SWIG_Python_SetConstant(d, "_close_match_iterator_type_state_current",SWIG_From_int(static_cast< int >(match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >::state_current))); SWIG_Python_SetConstant(d, "_close_match_iterator_type_state_skip_input",SWIG_From_int(static_cast< int >(match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >::state_skip_input))); SWIG_Python_SetConstant(d, "_close_match_iterator_type_state_skip_base",SWIG_From_int(static_cast< int >(match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >::state_skip_base))); SWIG_Python_SetConstant(d, "_close_match_iterator_type_state_right",SWIG_From_int(static_cast< int >(match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >::state_right))); SWIG_Python_SetConstant(d, "_close_match_iterator_type_state_end",SWIG_From_int(static_cast< int >(match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >::state_end))); #if PY_VERSION_HEX >= 0x03000000 return m; #else return; #endif }
nlehuen/pytst
cfc9059d408118e20d26869743cc09f97affd30c
Release 1.17
diff --git a/include/tst.h b/include/tst.h index a795499..7ec107b 100644 --- a/include/tst.h +++ b/include/tst.h @@ -1,534 +1,534 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __TST__H_INCLUDED__ #define __TST__H_INCLUDED__ -const char* const TST_VERSION = "1.17-dev"; +const char* const TST_VERSION = "1.17"; #include "debug.h" #include <iostream> #ifdef __PYTHON__BUILD__ #include "Python.h" #define tst_malloc PyMem_Malloc #define tst_realloc PyMem_Realloc #define tst_free PyMem_Free // Pour ajouter/supprimer les fonctions de scanning. // #define SCANNER #else #include "stdlib.h" #define tst_malloc malloc #define tst_realloc realloc #define tst_free free // Pour ajouter/supprimer les fonctions de scanning. // #define SCANNER #endif template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst; #include "fundamentals.h" #include "memory_storage.h" #include "iterators.h" template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst { public: friend class lexical_iterator<charT,valueT,storageT,serializerT,stringT>; friend class match_iterator<charT,valueT,storageT,serializerT,stringT>; typedef charT character_type; typedef valueT value_type; typedef storageT storage_type; typedef serializerT serializer_type; tst(); virtual ~tst() { delete storage; } void pack() { storage->pack(root); } valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,const stringT & string) const; valueT close_match(const stringT & string,int maximum_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT prefix_match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT get(const stringT & string) const; valueT get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory); valueT put(const stringT & string,valueT data); void remove(const stringT & string); bool contains(const stringT & string) const; void write(std::ostream &file) const; void read(std::istream &file); lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator() const { stringT key; return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,key,root); } lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; find_node(&current_index,&best_node,string); return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,string.substr(0,string.size()-1),current_index); } match_iterator<charT,valueT,storageT,serializerT,stringT> close_match_iterator(const stringT & string,int distance) const { return match_iterator<charT,valueT,storageT,serializerT,stringT>(this,string,distance,root); } int get_number_of_nodes() const { return storage->size(); } valueT get_default_value() const { return default_value; } #ifdef SCANNER valueT scan(const stringT & string,tst_action<charT,valueT,stringT>* to_perform); valueT scan_with_stop_chars(const stringT & string,const stringT& stop_chars,tst_action<charT,valueT,stringT>* to_perform) const; #endif protected: void set_storage(storageT* new_storage) { delete storage; storage = new_storage; } private: storageT* storage; valueT default_value; int root; void walk_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void close_match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,const size_t position, const int distance, const int remaining_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_joker_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_star_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; int build_node(node_info<charT,valueT>* current_node,const stringT & string,size_t current_position); void remove_node(int* current_index,const stringT & string,const size_t position); tst_node<charT,valueT>* find_node(int* current_index,int* best_node, const stringT & string) const; void balance_node(node_info<charT,valueT>* bal); void ll(node_info<charT,valueT>* bal); void rr(node_info<charT,valueT>* bal); void lr(node_info<charT,valueT>* bal); void rl(node_info<charT,valueT>* bal); void compute_height_and_balance(node_info<charT,valueT>* current_node_info) const; void write_node(std::ostream& file,serializerT* writer,int index) const; int read_node(std::istream& file,serializerT* reader,int depth); #ifdef SCANNER void compute_backtrack(tst_node<charT,valueT> *current_node,const stringT & string,int si_match_start,int si_match_end); #endif }; template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst<charT,valueT,storageT,serializerT,stringT>::tst() : storage(new storage_type(16)), default_value() { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } /*************************** high-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return current_node->data; } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> bool tst<charT,valueT,storageT,serializerT,stringT>::contains(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return true; } else { return false; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::put(const stringT & string,valueT data) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; return storage->get(node_index)->store(data); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; tst_node<charT,valueT>* current_node=storage->get(node_index); valueT data = current_node->data; if(data==default_value) { data=factory->perform(string,0,current_node->data); current_node->store(data); return data; } else { return data; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove(const stringT & string) { remove_node(&root,string,0); if(root==UNDEFINED_INDEX) { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } } /**************************** low-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst_node<charT,valueT>* tst<charT,valueT,storageT,serializerT,stringT>::find_node(int* current_index,int* best_node,const stringT & string) const { tst_node<charT,valueT>* current_node; int diff; size_t pos=0; while(*current_index!=UNDEFINED_INDEX) { current_node=storage->get(*current_index); if(current_node->c==0) { *current_index=UNDEFINED_INDEX; return 0; } else { diff=string[pos]-(current_node->c); } if(diff==0) { if(current_node->data!=default_value) { *best_node=*current_index; } ++pos; if(pos<string.size()) { *current_index = current_node->next; } else { return current_node; } } else if(diff>0) { *current_index=current_node->right; } else { *current_index=current_node->left; } } return 0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> int tst<charT,valueT,storageT,serializerT,stringT>::build_node(node_info<charT,valueT>* current_node_info,const stringT & string,size_t current_position) { int diff,result; if(current_node_info->node->c==0) { current_node_info->node->c=string[current_position]; #ifdef SCANNER current_node_info->node->position=current_position; #endif diff=0; } else { diff=string[current_position]-(current_node_info->node->c); } current_node_info->height=-1; current_node_info->balance_performed=0; if(diff==0) { ++current_position; compute_height_and_balance(current_node_info); // TODO : est-ce bien necessaire ? if(current_position<string.size()) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->next; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->next = next_node_info.index; return result; } else { return current_node_info->index; } } else if(diff>0) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->right; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->right = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->left==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = next_node_info.height; current_node_info->left_balance = 0; current_node_info->right_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->left; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = next_node_info.height-other_node_info.height; current_node_info->left_balance = other_node_info.balance; current_node_info->right_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } else { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->left; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->left = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->right==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = -next_node_info.height; current_node_info->right_balance = 0; current_node_info->left_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->right; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = other_node_info.height-next_node_info.height; current_node_info->right_balance = other_node_info.balance; current_node_info->left_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove_node(int* current_index,const stringT & string,const size_t current_position) { tst_node<charT,valueT>* current_node = storage->get(*current_index); int diff,*next_index; if(current_node->c==0) { return; } else { diff=string[current_position]-(current_node->c); } if(diff==0) { if(current_position+1<string.size()) { next_index = &(current_node->next); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position+1); } } else { current_node->store(default_value); } } else if(diff>0) { next_index = &(current_node->right); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } else { next_index = &(current_node->left); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } current_node=storage->get(*current_index); if( current_node->data==default_value && current_node->next==UNDEFINED_INDEX && current_node->right==UNDEFINED_INDEX && current_node->left==UNDEFINED_INDEX) { storage->delete_node(*current_index); *current_index=UNDEFINED_INDEX; } else { node_info<charT,valueT> current_node_info; current_node_info.index=*current_index; current_node_info.node=current_node; current_node_info.height=-1; balance_node(&current_node_info); *current_index = current_node_info.index; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::balance_node(node_info<charT,valueT>* bal) { if(bal->height==-1) { compute_height_and_balance(bal); } bal->balance_performed=0; if(bal->balance>1) { if(bal->right_balance>0) { rr(bal); } else { rl(bal); } bal->balance_performed=1; } else if(bal->balance<-1) { if(bal->left_balance<0) { ll(bal); } else { lr(bal); } bal->balance_performed=1; } assert(abs(bal->balance)<2); assert(abs(bal->right_balance)<2); assert(abs(bal->left_balance)<2); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::ll(node_info<charT,valueT>* bal) { int left_index=bal->node->left; tst_node<charT,valueT>* left_node=storage->get(left_index); int left_right_index=left_node->right; bal->node->left=left_right_index; left_node->right=bal->index; bal->index=left_index; bal->node=storage->get(left_index); bal->height=bal->height-1; bal->balance=0; bal->right_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rr(node_info<charT,valueT>* bal) { int right_index=bal->node->right; tst_node<charT,valueT>* right_node=storage->get(right_index); int right_left_index=right_node->left; bal->node->right=right_left_index; right_node->left=bal->index; bal->index=right_index; bal->node=storage->get(right_index); bal->height=bal->height-1; bal->balance=0; bal->left_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::lr(node_info<charT,valueT>* bal) { node_info<charT,valueT> left; left.index = bal->node->left; left.node = storage->get(left.index); rr(&left); bal->node->left=left.index; ll(bal); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rl(node_info<charT,valueT>* bal) { node_info<charT,valueT> right; right.index = bal->node->right; right.node = storage->get(right.index); ll(&right); bal->node->right=right.index; rr(bal); } diff --git a/python/setup.py b/python/setup.py index b3b5a66..eafc9bd 100644 --- a/python/setup.py +++ b/python/setup.py @@ -1,49 +1,49 @@ # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from distutils.core import setup, Extension import sys extra_compile_args = [] setup( name = "pytst", - version = "1.17-dev", + version = "1.17", author = "Nicolas Lehuen", author_email = "nicolas@lehuen.com", url = "http://nicolas.lehuen.com/index.php/category/Pytst", description = "An implementation of a Ternary Search Tree (TST) in C++ with Python bindings", py_modules = ["tst"], ext_modules = [ Extension( "_tst", ["tst_wrap.cxx"], include_dirs=['../include'], extra_compile_args = extra_compile_args, define_macros=[('SCANNER', None),], ) ], download_url = "http://nicolas.lehuen.com/download/pytst/", classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: C++', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Scientific/Engineering :: Information Analysis', ] )
nlehuen/pytst
eb62863662789676547e2be0abb91fa2210f5e20
Removed dependencies to the 'tcc' module.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3076e6d --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.pyc +python/dist +python/test/test.tst diff --git a/python/test/distance.py b/python/test/distance.py new file mode 100644 index 0000000..6389558 --- /dev/null +++ b/python/test/distance.py @@ -0,0 +1,50 @@ +try: + from Levenshtein import distance as _levenshtein + def levenshtein(a,b): + if (a is None) or (b is None): + return 999999 + return _levenshtein(a,b) +except ImportError: + def levenshtein(a,b): + """ + Calculates the Levenshtein distance between a and b. + Optimized version (fewer object allocations and array subscriptions) from : + http://hetland.org/python/distance.py + """ + if (a is None) or (b is None): + return 999999 + + n, m = len(a), len(b) + if n > m: + # Make sure n <= m, to use O(min(n,m)) space + a,b = b,a + n,m = m,n + + previous = range(n+1) + current = range(n+1) + rangen = range(1,n+1) + for i in xrange(1,m+1): + temp = previous + previous = current + current = temp + current[0]=i + + p0p = previous[0] + p0c = i + b0c = b[i-1] + for j in rangen: + p1p = previous[j] + add = p1p+1 + delete = p0c+1 + change = p0p + if a[j-1] != b0c: + change += 1 + if add < change: + change = add + if delete < change: + change = delete + current[j] = change + p0c=change + p0p=p1p + + return change diff --git a/python/test/stats.csv b/python/test/stats.csv index e06d866..1b1aead 100644 --- a/python/test/stats.csv +++ b/python/test/stats.csv @@ -1,23 +1,24 @@ date;version;comment;build_big:min;build_big:med;build_big:avg;build_big:max;build_big/10:min;build_big/10:med;build_big/10:avg;build_big/10:max;check_delete_big:min;check_delete_big:med;check_delete_big:avg;check_delete_big:max;check_update_big:min;check_update_big:med;check_update_big:avg;check_update_big:max;close_match:min;close_match:med;close_match:avg;close_match:max;delete_big/10:min;delete_big/10:med;delete_big/10:avg;delete_big/10:max;delete_full:min;delete_full:med;delete_full:avg;delete_full:max;pack/10:min;pack/10:med;pack/10:avg;pack/10:max;read_big:min;read_big:med;read_big:avg;read_big:max;refill_post_pack/10:min;refill_post_pack/10:med;refill_post_pack/10:avg;refill_post_pack/10:max;refill_pre_pack/10:min;refill_pre_pack/10:med;refill_pre_pack/10:avg;refill_pre_pack/10:max;scan:min;scan:med;scan:avg;scan:max;scan_stop_chars:min;scan_stop_chars:med;scan_stop_chars:avg;scan_stop_chars:max;update_big/10:min;update_big/10:med;update_big/10:avg;update_big/10:max;walk:min;walk:med;walk:avg;walk:max;walk_root:min;walk_root:med;walk_root:avg;walk_root:max;write_big:min;write_big:med;write_big:avg;write_big:max 05/03/2006 10:40:31;1.07;SWIG1.3.27; 0,2876; 0,2910; 0,2922; 0,3103; 0,3573; 0,3624; 0,3621; 0,3667; 0,6739; 0,6806; 0,6820; 0,6916; 0,0654; 0,0665; 0,0665; 0,0675; 0,0014; 0,0065; 0,0062; 0,0131; 0,9429; 0,9608; 0,9657; 1,0311; 0,9200; 0,9209; 0,9219; 0,9249; 0,3298; 0,3307; 0,3352; 0,3451; 0,6526; 0,6686; 0,6665; 0,6762; 0,8340; 0,9933; 0,9992; 1,1808; 0,9362; 0,9506; 0,9471; 0,9544; 1,4404; 1,4453; 1,4474; 1,4565; 2,3461; 2,3549; 2,3524; 2,3563; 0,9992; 1,0072; 1,0070; 1,0146; 0,0254; 0,0263; 0,0260; 0,0264; 0,0087; 0,0094; 0,0093; 0,0097; 0,8701; 0,8797; 0,8869; 0,9273 05/03/2006 10:41:37;1.07-Boost.Python;; 0,2855; 0,2910; 0,2909; 0,2953; 0,3573; 0,3629; 0,3626; 0,3675; 0,4930; 0,4932; 0,4936; 0,4946; 0,0490; 0,0491; 0,0496; 0,0509; 0,0032; 0,0145; 0,0140; 0,0323; 0,8914; 0,9360; 0,9296; 0,9666; 0,7600; 0,7679; 0,7701; 0,7824; 0,3342; 0,3381; 0,3421; 0,3539; 0,4818; 0,4850; 0,4868; 0,4988; 0,4525; 0,6169; 0,6204; 0,8002; 0,5615; 0,5625; 0,5632; 0,5656; 0,2558; 0,2567; 0,2915; 0,3622; 0,5826; 0,5827; 0,5831; 0,5841; 0,6620; 0,6654; 0,6654; 0,6689; 0,0271; 0,0279; 0,0277; 0,0281; 0,0030; 0,0037; 0,0037; 0,0044; 0,4879; 0,4944; 0,4937; 0,5004 05/03/2006 10:45:57;1.07;SWIG1.3.28; 0,2863; 0,2935; 0,2983; 0,3391; 0,3594; 0,3609; 0,3627; 0,3676; 0,5059; 0,5136; 0,5214; 0,5447; 0,0496; 0,0498; 0,0499; 0,0502; 0,0014; 0,0064; 0,0062; 0,0101; 0,7894; 0,8005; 0,8110; 0,9065; 0,7670; 0,7675; 0,7683; 0,7705; 0,3351; 0,3445; 0,3439; 0,3520; 0,4831; 0,4963; 0,4983; 0,5282; 0,6272; 0,7881; 0,7961; 0,9719; 0,7319; 0,7429; 0,7398; 0,7445; 0,6446; 0,6507; 0,6493; 0,6526; 1,0995; 1,1185; 1,1126; 1,1199; 0,8250; 0,8345; 0,8328; 0,8389; 0,0215; 0,0216; 0,0217; 0,0221; 0,0045; 0,0053; 0,0051; 0,0054; 0,6635; 0,6761; 0,6783; 0,6938 05/03/2006 11:16:51;1.08;SWIG-1.3.28-O; 0,2841; 0,2917; 0,2932; 0,3178; 0,3426; 0,3582; 0,3545; 0,3626; 0,4198; 0,4264; 0,4262; 0,4325; 0,0406; 0,0418; 0,0416; 0,0423; 0,0013; 0,0064; 0,0061; 0,0264; 0,6883; 0,7258; 0,7205; 0,7331; 0,6870; 0,6895; 0,6899; 0,6931; 0,3295; 0,3423; 0,3381; 0,3425; 0,3970; 0,4177; 0,4145; 0,4199; 0,5512; 0,7105; 0,7210; 0,9085; 0,6730; 0,6816; 0,6805; 0,6869; 0,3630; 0,3772; 0,3742; 0,3823; 0,6940; 0,6991; 0,6994; 0,7051; 0,7273; 0,7384; 0,7396; 0,7529; 0,0199; 0,0199; 0,0200; 0,0201; 0,0029; 0,0036; 0,0035; 0,0041; 0,5707; 0,6062; 0,6034; 0,6232 21/03/2006 22:00:12;1.09;; 0,3403; 0,5267; 0,5482; 0,9287; 0,4369; 0,6031; 0,6187; 0,8161; 0,8313; 0,8352; 0,8905; 1,0051; 0,0570; 0,0804; 0,0759; 0,0904; 0,0024; 0,0082; 0,0087; 0,0196; 1,1651; 1,2745; 1,3322; 1,5531; 1,2418; 1,2455; 1,4362; 1,8211; 0,5143; 0,5426; 0,5609; 0,6258; 0,5183; 0,8011; 0,8027; 0,9959; 1,0040; 1,5180; 1,6720; 3,1133; 1,0664; 1,4002; 1,3073; 1,4554; 0,4371; 0,6371; 0,6216; 0,7907; 0,8122; 1,1103; 1,0315; 1,1719; 0,9315; 1,3021; 1,3037; 1,6775; 0,0303; 0,0432; 0,0452; 0,0621; 0,0028; 0,0040; 0,0082; 0,0178; 0,7817; 1,1396; 1,1857; 1,6129 21/03/2006 22:01:46;1.09;; 0,3476; 0,5330; 0,5089; 0,7775; 0,4448; 0,5442; 0,5551; 0,6762; 0,5379; 0,8215; 0,7723; 0,9574; 0,0531; 0,0807; 0,0786; 0,1020; 0,0014; 0,0103; 0,0106; 0,0832; 0,8000; 1,3683; 1,3774; 2,1843; 0,8521; 1,4001; 1,2417; 1,4729; 0,4217; 0,6061; 0,5447; 0,6062; 0,5114; 0,8444; 0,7765; 0,9723; 0,7859; 1,3237; 1,4121; 2,1398; 0,7973; 1,2312; 1,1129; 1,3102; 0,4554; 0,7201; 0,6591; 0,8017; 0,8707; 1,4206; 1,2475; 1,4513; 0,8821; 1,3371; 1,2254; 1,4569; 0,0240; 0,0336; 0,0388; 0,0586; 0,0038; 0,0072; 0,0064; 0,0082; 0,7424; 1,2504; 1,1364; 1,4142 21/03/2006 22:10:03;1.09-Boost.Python;; 0,5082; 0,5422; 0,5583; 0,6411; 0,5990; 0,6178; 0,6255; 0,6597; 0,9936; 1,0005; 1,0109; 1,0388; 0,0838; 0,1197; 0,1137; 0,1375; 0,0060; 0,0263; 0,0263; 0,0858; 1,5500; 1,8875; 1,8709; 2,4736; 1,5677; 1,6472; 1,6484; 1,7304; 0,6125; 0,6756; 0,6579; 0,6855; 0,8667; 0,9704; 0,9790; 1,0785; 0,8156; 1,1671; 1,2322; 1,6069; 0,9716; 1,0109; 1,0545; 1,1810; 0,4838; 0,5086; 0,5009; 0,5101; 1,0844; 1,1047; 1,1109; 1,1435; 1,2288; 1,2712; 1,3041; 1,4124; 0,0417; 0,0482; 0,0470; 0,0511; 0,0028; 0,0083; 0,0085; 0,0143; 0,9182; 1,0185; 1,0069; 1,1103 05/05/2006 15:11:35;1.13-Boost.Python;; 0,2831; 0,2886; 0,2933; 0,3250; 0,3183; 0,3228; 0,3231; 0,3281; 0,4344; 0,4354; 0,4375; 0,4427; 0,0415; 0,0426; 0,0425; 0,0434; 0,0047; 0,0248; 0,0235; 0,0323; 0,7687; 0,8004; 0,8044; 0,8549; 0,6625; 0,6718; 0,6734; 0,6859; 0,3568; 0,3637; 0,3670; 0,3807; 0,4200; 0,4272; 0,4283; 0,4379; 0,4127; 0,5902; 0,5968; 0,7842; 0,5092; 0,5404; 0,5424; 0,5776; 0,2319; 0,2332; 0,2363; 0,2438; 0,5673; 0,5676; 0,5688; 0,5713; 0,6043; 0,6104; 0,6124; 0,6223; 0,0369; 0,0387; 0,0382; 0,0388; 0,0034; 0,0042; 0,0043; 0,0053; 0,4554; 0,4638; 0,4677; 0,4985 05/05/2006 15:12:33;1.12;; 0,2788; 0,2878; 0,2875; 0,3028; 0,3205; 0,3263; 0,3286; 0,3390; 0,3527; 0,3587; 0,3633; 0,3786; 0,0326; 0,0336; 0,0337; 0,0348; 0,0011; 0,0055; 0,0053; 0,0120; 0,5764; 0,5853; 0,5985; 0,7082; 0,5500; 0,5554; 0,5556; 0,5614; 0,3459; 0,3629; 0,3574; 0,3635; 0,3341; 0,3478; 0,3491; 0,3707; 0,4328; 0,6176; 0,6183; 0,8054; 0,5508; 0,5562; 0,5591; 0,5703; 0,1636; 0,1641; 0,1644; 0,1655; 0,3483; 0,3508; 0,3516; 0,3557; 0,6352; 0,6442; 0,6423; 0,6475; 0,0161; 0,0165; 0,0168; 0,0177; 0,0017; 0,0022; 0,0021; 0,0025; 0,4883; 0,4994; 0,5031; 0,5280 05/05/2006 15:13:29;1.13;; 0,2818; 0,2865; 0,2872; 0,2945; 0,3161; 0,3193; 0,3233; 0,3346; 0,4056; 0,4061; 0,4102; 0,4188; 0,0376; 0,0389; 0,0388; 0,0399; 0,0035; 0,0189; 0,0178; 0,0301; 0,6144; 0,6238; 0,6327; 0,6808; 0,5885; 0,5955; 0,6001; 0,6163; 0,3462; 0,3515; 0,3738; 0,4238; 0,3857; 0,3879; 0,3891; 0,3940; 0,5014; 0,6780; 0,6797; 0,8700; 0,5968; 0,6048; 0,6040; 0,6104; 0,1703; 0,1731; 0,1724; 0,1738; 0,4469; 0,4479; 0,4476; 0,4480; 0,6780; 0,6785; 0,7012; 0,7469; 0,0281; 0,0281; 0,0284; 0,0290; 0,0029; 0,0032; 0,0033; 0,0039; 0,5392; 0,5434; 0,5458; 0,5586 05/05/2006 16:52:04;1.14;; 0,2840; 0,2909; 0,2930; 0,3032; 0,3218; 0,3378; 0,3378; 0,3540; 0,3874; 0,3898; 0,3921; 0,3992; 0,0372; 0,0381; 0,0384; 0,0400; 0,0014; 0,0070; 0,0069; 0,0392; 0,6240; 0,6367; 0,6404; 0,6589; 0,5959; 0,5974; 0,6017; 0,6117; 0,3461; 0,3626; 0,3590; 0,3683; 0,3632; 0,3735; 0,3750; 0,3994; 0,4767; 0,6774; 0,6714; 0,8727; 0,5815; 0,5882; 0,5936; 0,6110; 0,1708; 0,1712; 0,1715; 0,1725; 0,3525; 0,3541; 0,3561; 0,3617; 0,6506; 0,6522; 0,6556; 0,6641; 0,0172; 0,0177; 0,0175; 0,0177; 0,0020; 0,0025; 0,0024; 0,0028; 0,5275; 0,5364; 0,5379; 0,5548 22/10/2007 20:59:06;1.14;; 0,1492; 0,1734; 0,1705; 0,2168; 0,1868; 0,1920; 0,2104; 0,2525; 0,2479; 0,2711; 0,2645; 0,2745; 0,0227; 0,0230; 0,0252; 0,0300; 0,0050; 0,0193; 0,0184; 0,0319; 0,4393; 0,5661; 0,5436; 0,6571; 0,4480; 0,4892; 0,5077; 0,5860; 0,2742; 0,2822; 0,2803; 0,2846; 0,2191; 0,2403; 0,2433; 0,2831; 0,4001; 0,5068; 0,5619; 0,9638; 0,3730; 0,3877; 0,4350; 0,5443; 0,1153; 0,1197; 0,1185; 0,1205; 0,2424; 0,2593; 0,2557; 0,2654; 0,4689; 0,5121; 0,5264; 0,5980; 0,0237; 0,0242; 0,0241; 0,0246; 0,0020; 0,0025; 0,0026; 0,0032; 0,3557; 0,3988; 0,4080; 0,5443 01/04/2008 22:16:06;1.15;; 0,1487; 0,1583; 0,1624; 0,1945; 0,1855; 0,1907; 0,1975; 0,2163; 0,2410; 0,2417; 0,2524; 0,2744; 0,0243; 0,0252; 0,0257; 0,0277; 0,0055; 0,0201; 0,0194; 0,0552; 0,4397; 0,4848; 0,4848; 0,5685; 0,4547; 0,4785; 0,4749; 0,4916; 0,2191; 0,2308; 0,2362; 0,2587; 0,2200; 0,2336; 0,2519; 0,3807; 0,3195; 0,4481; 0,4711; 0,7152; 0,3742; 0,3873; 0,4133; 0,4783; 0,1052; 0,1109; 0,1137; 0,1252; 0,2486; 0,2503; 0,2625; 0,2886; 0,4335; 0,4782; 0,4684; 0,4935; 0,0227; 0,0228; 0,0240; 0,0266; 0,0020; 0,0026; 0,0027; 0,0036; 0,3479; 0,3806; 0,4042; 0,5924 01/04/2008 22:26:12;1.15;; 0,1629; 0,1762; 0,1862; 0,2507; 0,2005; 0,2009; 0,2052; 0,2142; 0,2583; 0,2632; 0,2622; 0,2652; 0,0238; 0,0254; 0,0262; 0,0293; 0,0000; 0,0005; 0,0109; 0,1247; 0,4447; 0,5251; 0,5458; 0,7612; 0,4934; 0,5006; 0,5177; 0,5591; 0,2126; 0,2230; 0,2525; 0,3218; 0,2268; 0,2603; 0,2736; 0,3309; 0,3419; 0,5427; 0,6768; 1,7221; 0,3815; 0,4084; 0,4050; 0,4252; 0,1124; 0,1205; 0,1221; 0,1334; 0,2791; 0,2824; 0,2874; 0,3006; 0,4684; 0,5076; 0,7429; 1,2526; 0,0236; 0,0240; 0,0242; 0,0250; 0,0017; 0,0022; 0,0021; 0,0024; 0,3809; 0,4326; 0,4333; 0,4963 01/04/2008 22:27:18;1.15;; 0,1554; 0,1773; 0,1938; 0,2599; 0,1902; 0,2011; 0,2017; 0,2138; 0,2440; 0,3246; 0,3023; 0,3382; 0,0232; 0,0240; 0,0240; 0,0249; 0,0000; 0,0007; 0,0107; 0,1162; 0,4422; 0,5197; 0,5804; 1,1199; 0,4693; 0,5618; 0,5311; 0,5622; 0,2186; 0,2365; 0,2410; 0,2679; 0,2314; 0,2465; 0,2462; 0,2592; 0,3299; 0,4639; 0,4735; 0,6245; 0,4065; 0,4182; 0,4682; 0,5799; 0,1148; 0,1178; 0,1200; 0,1274; 0,2616; 0,2733; 0,2733; 0,2852; 0,4711; 0,5240; 0,5127; 0,5432; 0,0228; 0,0242; 0,0241; 0,0254; 0,0019; 0,0021; 0,0022; 0,0025; 0,3662; 0,4144; 0,4172; 0,4754 01/04/2008 22:28:44;1.15;; 0,1520; 0,1664; 0,1665; 0,1870; 0,1875; 0,1948; 0,2709; 0,4302; 0,2345; 0,2366; 0,2378; 0,2422; 0,0232; 0,0238; 0,0277; 0,0360; 0,0052; 0,0200; 0,0196; 0,0601; 0,4423; 0,4674; 0,5125; 0,6245; 0,4413; 0,4551; 0,4555; 0,4702; 0,2118; 0,2246; 0,2275; 0,2461; 0,0000; 0,0000; 0,0000; 0,0008; 0,2277; 0,2459; 0,2442; 0,2791; 0,3259; 0,4308; 0,4489; 0,6220; 0,4168; 0,5018; 0,4975; 0,5739; 0,1099; 0,1109; 0,1128; 0,1177; 0,2499; 0,2595; 0,2586; 0,2665; 0,4649; 0,4981; 0,4889; 0,5038; 0,0219; 0,0225; 0,0227; 0,0235; 0,0022; 0,0025; 0,0032; 0,0049; 0,3522; 0,3753; 0,3809; 0,4444 02/04/2008 01:20:25;1.15;; 0,1527; 0,1586; 0,1600; 0,1714; 0,1743; 0,1780; 0,1792; 0,1852; 0,2239; 0,2408; 0,2401; 0,2555; 0,0228; 0,0238; 0,0238; 0,0250; 0,0050; 0,0197; 0,0190; 0,0398; 0,4479; 0,4802; 0,4853; 0,5665; 0,4309; 0,4505; 0,4457; 0,4556; 0,2121; 0,2263; 0,2290; 0,2486; 0,0000; 0,0000; 0,0000; 0,0010; 0,2213; 0,2266; 0,2291; 0,2417; 0,3189; 0,4268; 0,4367; 0,5752; 0,3756; 0,4048; 0,3991; 0,4171; 0,1105; 0,1127; 0,1296; 0,1655; 0,2486; 0,2560; 0,2557; 0,2625; 0,4543; 0,5008; 0,4879; 0,5088; 0,0219; 0,0231; 0,0237; 0,0262; 0,0017; 0,0024; 0,0022; 0,0024; 0,3436; 0,3684; 0,3701; 0,4352 04/02/2009 22:18:56;1.16;; 0,1213; 0,1242; 0,1267; 0,1434; 0,1680; 0,1795; 0,1758; 0,1800; 0,2148; 0,2162; 0,2191; 0,2263; 0,0219; 0,0225; 0,0224; 0,0228; 0,0064; 0,0262; 0,0248; 0,0348; 0,4808; 0,4941; 0,5027; 0,5667; 0,4771; 0,4772; 0,4810; 0,4887; 0,2133; 0,2174; 0,2257; 0,2465; 0,0000; 0,0000; 0,0001; 0,0006; 0,2090; 0,2127; 0,2237; 0,2896; 0,3298; 0,4251; 0,4302; 0,5428; 0,3790; 0,3845; 0,3873; 0,3984; 0,1116; 0,1145; 0,1137; 0,1149; 0,2434; 0,2480; 0,2472; 0,2502; 0,4451; 0,4750; 0,4671; 0,4813; 0,0269; 0,0274; 0,0277; 0,0288; 0,0021; 0,0028; 0,0026; 0,0029; 0,3523; 0,3586; 0,3627; 0,3745 04/02/2009 23:05:33;1.16;; 0,1322; 0,1444; 0,1437; 0,1522; 0,1745; 0,2063; 0,1993; 0,2172; 0,2598; 0,2615; 0,2612; 0,2625; 0,0227; 0,0231; 0,0243; 0,0271; 0,0062; 0,0290; 0,0276; 0,0414; 0,5304; 0,6019; 0,6171; 0,7859; 0,5662; 0,5716; 0,5730; 0,5813; 0,2327; 0,2481; 0,2472; 0,2607; 0,0000; 0,0000; 0,0001; 0,0028; 0,2258; 0,2438; 0,2551; 0,3440; 0,3516; 0,5399; 0,5309; 0,6787; 0,4224; 0,4830; 0,4738; 0,5159; 0,1231; 0,1246; 0,1254; 0,1286; 0,2498; 0,2703; 0,2655; 0,2762; 0,4567; 0,4971; 0,5161; 0,5944; 0,0278; 0,0287; 0,0288; 0,0300; 0,0023; 0,0026; 0,0026; 0,0030; 0,3868; 0,4247; 0,4213; 0,4354 04/02/2009 23:13:58;1.16RC;; 0,1307; 0,1358; 0,1353; 0,1388; 0,1835; 0,1865; 0,1860; 0,1881; 0,2364; 0,2372; 0,2380; 0,2402; 0,0226; 0,0232; 0,0231; 0,0234; 0,0062; 0,0278; 0,0265; 0,0498; 0,5378; 0,5604; 0,5839; 0,6609; 0,5300; 0,5316; 0,5323; 0,5353; 0,2275; 0,2393; 0,2377; 0,2463; 0,0000; 0,0000; 0,0001; 0,0008; 0,2279; 0,2306; 0,2428; 0,3299; 0,3531; 0,4730; 0,4719; 0,5868; 0,4526; 0,4775; 0,4789; 0,5068; 0,1172; 0,1180; 0,1177; 0,1180; 0,2528; 0,2560; 0,2552; 0,2569; 0,4857; 0,4939; 0,5014; 0,5247; 0,0284; 0,0285; 0,0289; 0,0298; 0,0026; 0,0027; 0,0028; 0,0031; 0,3905; 0,3970; 0,3989; 0,4185 05/02/2009 08:04:58;1.16-RC1;; 0,1566; 0,1586; 0,1599; 0,1661; 0,1935; 0,2057; 0,2034; 0,2110; 0,2385; 0,2454; 0,2557; 0,2833; 0,0233; 0,0237; 0,0237; 0,0241; 0,0066; 0,0282; 0,0268; 0,0482; 0,5083; 0,5207; 0,5248; 0,5494; 0,4975; 0,5042; 0,5142; 0,5408; 0,2095; 0,2119; 0,2113; 0,2127; 0,0000; 0,0000; 0,0001; 0,0008; 0,2294; 0,2345; 0,2390; 0,2634; 0,3435; 0,4447; 0,5222; 0,9899; 0,4013; 0,4105; 0,4112; 0,4218; 0,1143; 0,1168; 0,1164; 0,1182; 0,2598; 0,2637; 0,2664; 0,2757; 0,4684; 0,4939; 0,4999; 0,5373; 0,0285; 0,0286; 0,0293; 0,0306; 0,0022; 0,0028; 0,0027; 0,0031; 0,3619; 0,3688; 0,3709; 0,3898 05/02/2009 08:13:52;1.16-RC1;; 0,1532; 0,1563; 0,1566; 0,1598; 0,1677; 0,1692; 0,1706; 0,1750; 0,2453; 0,2458; 0,2472; 0,2506; 0,0250; 0,0254; 0,0256; 0,0263; 0,0064; 0,0278; 0,0264; 0,0329; 0,4955; 0,5140; 0,5209; 0,5785; 0,4838; 0,4910; 0,4916; 0,5000; 0,2015; 0,2147; 0,2115; 0,2183; 0,0000; 0,0000; 0,0001; 0,0009; 0,2328; 0,2349; 0,2359; 0,2413; 0,3457; 0,5293; 0,4841; 0,5787; 0,4112; 0,4160; 0,4210; 0,4357; 0,1132; 0,1135; 0,1136; 0,1141; 0,2604; 0,2681; 0,2657; 0,2686; 0,4722; 0,4879; 0,4900; 0,5097; 0,0286; 0,0288; 0,0292; 0,0303; 0,0022; 0,0028; 0,0027; 0,0033; 0,3591; 0,3625; 0,3639; 0,3734 +01/04/2009 23:32:06;1.17-dev;; 0,1256; 0,1273; 0,1270; 0,1282; 0,1734; 0,1741; 0,1755; 0,1789; 0,2207; 0,2246; 0,2234; 0,2249; 0,0221; 0,0224; 0,0224; 0,0227; 0,0062; 0,0268; 0,0255; 0,0426; 0,4982; 0,5191; 0,5167; 0,5380; 0,4914; 0,4921; 0,4930; 0,4954; 0,2025; 0,2196; 0,2142; 0,2204; 0,0000; 0,0000; 0,0001; 0,0005; 0,2126; 0,2143; 0,2154; 0,2188; 0,3370; 0,4388; 0,4391; 0,5541; 0,3969; 0,3974; 0,4010; 0,4087; 0,1130; 0,1134; 0,1134; 0,1136; 0,2501; 0,2545; 0,2536; 0,2561; 0,4440; 0,4555; 0,4569; 0,4713; 0,0276; 0,0279; 0,0283; 0,0294; 0,0021; 0,0027; 0,0026; 0,0030; 0,3608; 0,3651; 0,3652; 0,3721 diff --git a/python/test/test.py b/python/test/test.py index fd6dcc2..dacbd5e 100644 --- a/python/test/test.py +++ b/python/test/test.py @@ -1,535 +1,534 @@ # -*- coding: iso-8859-1 -*- import sys # sys.path.insert(0,r"D:\projets\tst\python\Debug") import unittest import os import random import string import datetime from time import time from itertools import izip from tst import * random.seed(0) def random_string(length): return ''.join([random.choice(string.letters) for x in xrange(length)]) -# Where does tcc live? -from tcc.timer import Timer -from tcc.util import levenshtein +from timer import Timer +from distance import levenshtein timers = {} def timer_start(name): timers.setdefault(name,Timer()).start() def timer_end(name,normalize=1.0): timers.setdefault(name,Timer()).stop(normalize) def print_timers(comment): keys = timers.keys() keys.sort() for name in keys: print '%16s : %s'%(name,timers[name]) statsfilename = os.path.join(os.path.dirname(__file__),'stats.csv') if os.path.isfile(statsfilename): statsfile = file(statsfilename,'ab') else: statsfile = file(statsfilename,'wb') header = [ 'date', 'version', 'comment' ] for key in keys: header.append('%s:min'%key) header.append('%s:med'%key) header.append('%s:avg'%key) header.append('%s:max'%key) statsfile.write(';'.join(header)) statsfile.write('\n') row = [ datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S'), TST_VERSION, comment, ] for key in keys: timer = timers[key] row.append(('%7.4f'%timer.min).replace('.',',')) row.append(('%7.4f'%timer.med).replace('.',',')) row.append(('%7.4f'%timer.avg).replace('.',',')) row.append(('%7.4f'%timer.max).replace('.',',')) statsfile.write(';'.join(row)) statsfile.write('\n') class TestRefCount(unittest.TestCase): def setUp(self): self.a = 'toto' self.rc_a = sys.getrefcount(self.a) self.rc_None = sys.getrefcount(None) self.tree=TST() def testSetup(self): self.assertEqual(sys.getrefcount(None),self.rc_None+17) self.assertEqual(sys.getrefcount(self.a),self.rc_a) def testStore(self): self.tree[self.a]=self.a self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) def testOverwrite(self): self.tree[self.a]=self.a a2 = self.tree.put(self.a,'coucou') self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) del(a2) self.assertEqual(sys.getrefcount(self.a),self.rc_a) def testWalkList(self): l=self.tree.walk(None,ListAction()) self.assertEqual(sys.getrefcount(self.a),self.rc_a) self.tree[self.a]=self.a self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) l=self.tree.walk(None,ListAction()) self.assertEqual(sys.getrefcount(self.a),self.rc_a+2) del(l) self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) def testWalkDict(self): self.tree[self.a]=self.a self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) d=self.tree.walk(None,DictAction()) self.assertEqual(sys.getrefcount(self.a),self.rc_a+2) del(d) self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) del self.tree[self.a] self.assertEqual(sys.getrefcount(self.a),self.rc_a) def testRemove(self): del(self.tree) self.assertEqual(sys.getrefcount(None),self.rc_None) self.assertEqual(sys.getrefcount(self.a),self.rc_a) class TestCollectors(unittest.TestCase): def setUp(self): self.tree = TST() self.keys = dict( a = 1, ab = 2, abc = 3, b = 4 ) for k,v in self.keys.iteritems(): self.tree[k] = v def testListAction(self): l = self.tree.walk(None,ListAction()) self.assertEqual(l,[1,2,3,4]) def testTupleListAction(self): l = self.tree.walk(None,TupleListAction()) self.assertEqual(l,[('a',0,1),('ab',0,2),('abc',0,3),('b',0,4)]) def testDictAction(self): l = self.tree.walk(None,DictAction()) self.assertEqual(l,dict(a=(0,1),ab=(0,2),abc=(0,3),b=(0,4))) def skey(): format = '%%.%if'%random.randint(1,10) return format%random.random() class TestBasics(unittest.TestCase): def setUp(self): self.tree = TST() self.keys = dict([ (skey(),random.random()) for x in xrange(250) ]) for k,v in self.keys.iteritems(): self.tree[k] = v def testGet(self): for k,v in self.keys.iteritems(): self.assertEqual(self.tree[k],v) def testWithRemove(self): for k in random.sample(self.keys,len(self.keys)/8): del self.keys[k] del self.tree[k] self.tree.pack() self.testGet() def testWithUpdate(self): for k in random.sample(self.keys,len(self.keys)/8): v = self.keys[k] nv = random.random() self.keys[k] = nv self.assertEqual(self.tree.put(k,nv),v) self.testGet() def testWalk(self): timer_start("walk") for i in xrange(100): d = self.tree.walk(None,DictAction()) timer_end("walk") for k,v in d.iteritems(): self.assertEquals(self.tree[k],v[1]) def testWalkWithRoot(self): ref = self.tree.walk(None,DictAction()) timer_start("walk_root") for i in xrange(100): d = self.tree.walk(None,DictAction(),'0.1') timer_end("walk_root") for k, v in ref.iteritems(): if k.startswith('0.1'): self.assert_(k in d) self.assertEquals(v,d[k]) for k, v in d.iteritems(): self.assert_(k.startswith('0.1')) self.assertEquals(self.tree[k],v[1]) def testCloseMatch(self): for k1 in self.keys.iterkeys(): timer_start("close_match") d = self.tree.close_match(k1,4,None,DictAction()) timer_end("close_match") for k2 in self.keys.iterkeys(): distance = levenshtein(k1,k2) if distance<=4: self.assert_(k2 in d,"Match manquant pour %s : %s (distance = %i)"%( k1, k2, distance, )) self.assert_(k2 in d and d[k2][0]==distance,"Mauvaise distance pour %s et %s : %i != %s"%( k1, k2, distance, d.get(k2)[0] )) else: self.assert_(k2 not in d,"Mauvaise distance pour %s et %s : %i > 4 mais trouvé %s"%( k1, k2, distance, d.get(k2) )) def testPrefixMatch(self): for k1 in self.keys.iterkeys(): timer_start("prefix_match") d = self.tree.prefix_match(k1[:len(k1)/2],None,DictAction()) timer_end("prefix_match") self.assert_(k1 in d,"Une cle manque dans un prefix_match pour %s"%(k1,)) k2 = k1 + k1 timer_start("prefix_match") d = self.tree.prefix_match(k2,None,DictAction()) timer_end("prefix_match") self.assert_(k2 not in d,"Une cle manque dans un prefix_match pour %s"%(k1,)) def testWriteRead(self): self.tree.write_to_file('test.tst') self.tree = TST() self.tree.read_from_file('test.tst') self.testGet() class TestMatch(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['abc'] = 'abc' self.tree['ab'] = 'ab' self.tree['a'] = 'a' self.tree['bbc'] = 'bbc' self.tree['efgfjhny'] = 'ok' def testJoker1(self): d = self.tree.match("a?c",None,DictAction()) self.assertEquals(d,dict(abc=(0,"abc"))) def testJoker2(self): d = self.tree.match("???",None,DictAction()) self.assertEquals(d,{'abc': (0, 'abc'), 'bbc': (0, 'bbc')}) def testJoker3(self): d = self.tree.match("??",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab')}) def testStar1(self): d = self.tree.match("a*c",None,DictAction()) self.assertEquals(d,dict(abc=(0,"abc"))) def testStar2(self): d = self.tree.match("a*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'abc': (0, 'abc')}) def testStar2_1(self): d = self.tree.match("ab*",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab'), 'abc': (0, 'abc')}) def testStar2_2(self): d = self.tree.match("*b",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab')}) d = self.tree.match("*bbc",None,DictAction()) self.assertEquals(d,{'bbc': (0, 'bbc')}) def testStar3(self): d = self.tree.match("*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) d = self.tree.match("*?*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) def testStar3_1(self): d = self.tree.match("**",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) d = self.tree.match("***",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) def testStar4(self): d = self.tree.match("e*ny",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar5(self): d = self.tree.match("*****y",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar6(self): d = self.tree.match("????*",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar7(self): d = self.tree.match("ef?f*n?",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) class TestIterators(unittest.TestCase): def setUp(self): self.tree = TST() self.keys = dict( titi = 1, toto = 2, tati = 3, a = 5 ) for k, v in self.keys.iteritems(): self.tree[k] = v def testLexical1(self): d = {} for k, v in self.tree: d[k] = v self.assertEqual(d,self.keys) def testLexical2(self): d = {} for k, v in self.tree.iterator('t'): d[k] = v self.keys.pop('a') self.assertEqual(d,self.keys) def testCloseMatch(self): d = {} for k, v in self.tree.close_match_iterator('t',1): d[k] = v self.assertEqual(d,dict( a = 5 )) d = {} for k, v in self.tree.close_match_iterator('tito',1): d[k] = v self.assertEqual(d,dict( titi = 1, toto = 2 )) d = {} for k, v in self.tree.close_match_iterator('tuto',1): d[k] = v self.assertEqual(d,dict( toto = 2 )) class TestCallableAction(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['foo'] = 'bar' def testCA1(self): res = {} def callback(key, length, obj): res[key] = obj def result(): res['hello'] = 'world' return res self.assertEqual( self.tree.walk(None, CallableAction(callback, result)), {'foo':'bar', 'hello':'world'} ) def testCA2(self): res = {} def callback(key, length, obj): # Provoke an exception print 0 / 0 res[key] = obj def result(): return res try: self.tree.walk(None, CallableAction(callback, result)), self.fail("Should have raised an exception") except ZeroDivisionError: pass def testCA3(self): res = {} def callback(key, length, obj): res[key] = obj def result(): # Provoke an exception return 0/0 try: self.tree.walk(None, CallableAction(callback, result)), self.fail("Should have raised an exception") except ZeroDivisionError: pass class TestCallableFilter(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['foo'] = 'bar' self.tree['bar'] = 'foo' def testCF1(self): res = {} def cfilter(key, length, obj): res[key] = obj return obj self.tree.walk(CallableFilter(cfilter),None) self.assertEqual( res, {'foo':'bar', 'bar':'foo'} ) def testCF2(self): def cfilter(key, length, obj): if key=='foo': return 'boo' else: return obj self.assertEqual( self.tree.walk(CallableFilter(cfilter),DictAction()), {'foo':(0,'boo'),'bar':(0,'foo')} ) def testCF3(self): def cfilter(key, length, obj): if key=='foo': # raises an exception return 0 / 0 else: return obj try: self.tree.walk(CallableFilter(cfilter),DictAction()), self.fail("Should have raised an exception") except ZeroDivisionError: pass class TestHighCapacity(unittest.TestCase): def setUp(self): tree = TST() timer_start('build_big') keys = map(str,xrange(100000)) random.shuffle(keys) timer_end('build_big') timer_start('write_big') for k in keys: tree[k] = k timer_end('write_big') self.keys, self.tree = keys, tree def testGet(self): timer_start('read_big') for k in self.keys: self.assertEqual(self.tree[k],k) timer_end('read_big') def testFullPack(self): timer_start('delete_full') for k in self.keys: del self.tree[k] timer_end('delete_full') self.tree.pack() for k in self.keys: self.assertEqual(self.tree[k],None) sample = random.sample(self.keys,len(self.keys)/10) random.shuffle(sample) timer_start('refill_post_pack/10') for k in sample: self.tree[k] = k timer_end('refill_post_pack/10',10) for k in sample: self.assertEqual(self.tree[k],k) del self.tree[k] self.tree.pack() for k in self.keys: self.assertEqual(self.tree[k],None) self.tree.write_to_file('test.tst') def testDelete(self): sample = random.sample(self.keys,len(self.keys)/10) random.shuffle(sample) timer_start('delete_big/10') for k in sample: del self.tree[k] timer_end('delete_big/10',10) random.shuffle(sample) timer_start('refill_pre_pack/10') for k in sample: self.tree[k] = k timer_end('refill_pre_pack/10',10) self.testGet() random.shuffle(sample) timer_start('delete_big/10') for k in sample: del self.tree[k] timer_end('delete_big/10',10) self.tree.pack() diff --git a/python/test/timer.py b/python/test/timer.py new file mode 100644 index 0000000..c24cb83 --- /dev/null +++ b/python/test/timer.py @@ -0,0 +1,46 @@ +from time import clock +clock() # initialise l'horloge + +class Timer(object): + def __init__(self): + object.__init__(self) + self.timings = [] + self.stopped = True + self.need_computations = True + + def start(self): + assert self.stopped, "This timer has already started" + self._start = clock() + self.stopped = False + + def stop(self,normalize=1.0): + assert not self.stopped, "This timer is already stopped" + timing = (clock() - self._start)*normalize + self.stopped = True + self.timings.append(timing) + self.need_computations = True + return timing + + def update_computations(self): + if self.timings and self.need_computations: + st = sorted(self.timings) + self.min = st[0] + self.max = st[-1] + self.avg = sum(st)/len(st) + + if len(st)%2: + self.med = st[len(st)/2] + else: + self.med = (st[len(st)/2]+st[len(st)/2-1])/2.0 + self.need_computations = False + + def __str__(self): + self.update_computations() + return '(count=%3i,min=%7.4f,med=%7.4f,avg=%7.4f,max=%7.4f)'%( + len(self.timings), + self.min, + self.med, + self.avg, + self.max + ) +
nlehuen/pytst
3996cafd73fbb4387e89531733511e1ddb2429ab
64-bit fix fromThomas Brox Røst.
diff --git a/include/tst.h b/include/tst.h index 478138a..a795499 100644 --- a/include/tst.h +++ b/include/tst.h @@ -1,534 +1,534 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __TST__H_INCLUDED__ #define __TST__H_INCLUDED__ -const char* const TST_VERSION = "1.16"; +const char* const TST_VERSION = "1.17-dev"; #include "debug.h" #include <iostream> #ifdef __PYTHON__BUILD__ #include "Python.h" #define tst_malloc PyMem_Malloc #define tst_realloc PyMem_Realloc #define tst_free PyMem_Free // Pour ajouter/supprimer les fonctions de scanning. // #define SCANNER #else #include "stdlib.h" #define tst_malloc malloc #define tst_realloc realloc #define tst_free free // Pour ajouter/supprimer les fonctions de scanning. // #define SCANNER #endif template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst; #include "fundamentals.h" #include "memory_storage.h" #include "iterators.h" template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst { public: friend class lexical_iterator<charT,valueT,storageT,serializerT,stringT>; friend class match_iterator<charT,valueT,storageT,serializerT,stringT>; typedef charT character_type; typedef valueT value_type; typedef storageT storage_type; typedef serializerT serializer_type; tst(); virtual ~tst() { delete storage; } void pack() { storage->pack(root); } valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,const stringT & string) const; valueT close_match(const stringT & string,int maximum_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT prefix_match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT get(const stringT & string) const; valueT get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory); valueT put(const stringT & string,valueT data); void remove(const stringT & string); bool contains(const stringT & string) const; void write(std::ostream &file) const; void read(std::istream &file); lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator() const { stringT key; return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,key,root); } lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; find_node(&current_index,&best_node,string); return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,string.substr(0,string.size()-1),current_index); } match_iterator<charT,valueT,storageT,serializerT,stringT> close_match_iterator(const stringT & string,int distance) const { return match_iterator<charT,valueT,storageT,serializerT,stringT>(this,string,distance,root); } int get_number_of_nodes() const { return storage->size(); } valueT get_default_value() const { return default_value; } #ifdef SCANNER valueT scan(const stringT & string,tst_action<charT,valueT,stringT>* to_perform); valueT scan_with_stop_chars(const stringT & string,const stringT& stop_chars,tst_action<charT,valueT,stringT>* to_perform) const; #endif protected: void set_storage(storageT* new_storage) { delete storage; storage = new_storage; } private: storageT* storage; valueT default_value; int root; void walk_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void close_match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,const size_t position, const int distance, const int remaining_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_joker_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_star_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; int build_node(node_info<charT,valueT>* current_node,const stringT & string,size_t current_position); void remove_node(int* current_index,const stringT & string,const size_t position); tst_node<charT,valueT>* find_node(int* current_index,int* best_node, const stringT & string) const; void balance_node(node_info<charT,valueT>* bal); void ll(node_info<charT,valueT>* bal); void rr(node_info<charT,valueT>* bal); void lr(node_info<charT,valueT>* bal); void rl(node_info<charT,valueT>* bal); void compute_height_and_balance(node_info<charT,valueT>* current_node_info) const; void write_node(std::ostream& file,serializerT* writer,int index) const; int read_node(std::istream& file,serializerT* reader,int depth); #ifdef SCANNER void compute_backtrack(tst_node<charT,valueT> *current_node,const stringT & string,int si_match_start,int si_match_end); #endif }; template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst<charT,valueT,storageT,serializerT,stringT>::tst() : storage(new storage_type(16)), default_value() { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } /*************************** high-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return current_node->data; } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> bool tst<charT,valueT,storageT,serializerT,stringT>::contains(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return true; } else { return false; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::put(const stringT & string,valueT data) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; return storage->get(node_index)->store(data); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; tst_node<charT,valueT>* current_node=storage->get(node_index); valueT data = current_node->data; if(data==default_value) { data=factory->perform(string,0,current_node->data); current_node->store(data); return data; } else { return data; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove(const stringT & string) { remove_node(&root,string,0); if(root==UNDEFINED_INDEX) { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } } /**************************** low-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst_node<charT,valueT>* tst<charT,valueT,storageT,serializerT,stringT>::find_node(int* current_index,int* best_node,const stringT & string) const { tst_node<charT,valueT>* current_node; int diff; size_t pos=0; while(*current_index!=UNDEFINED_INDEX) { current_node=storage->get(*current_index); if(current_node->c==0) { *current_index=UNDEFINED_INDEX; return 0; } else { diff=string[pos]-(current_node->c); } if(diff==0) { if(current_node->data!=default_value) { *best_node=*current_index; } ++pos; if(pos<string.size()) { *current_index = current_node->next; } else { return current_node; } } else if(diff>0) { *current_index=current_node->right; } else { *current_index=current_node->left; } } return 0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> int tst<charT,valueT,storageT,serializerT,stringT>::build_node(node_info<charT,valueT>* current_node_info,const stringT & string,size_t current_position) { int diff,result; if(current_node_info->node->c==0) { current_node_info->node->c=string[current_position]; #ifdef SCANNER current_node_info->node->position=current_position; #endif diff=0; } else { diff=string[current_position]-(current_node_info->node->c); } current_node_info->height=-1; current_node_info->balance_performed=0; if(diff==0) { ++current_position; compute_height_and_balance(current_node_info); // TODO : est-ce bien necessaire ? if(current_position<string.size()) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->next; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->next = next_node_info.index; return result; } else { return current_node_info->index; } } else if(diff>0) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->right; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->right = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->left==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = next_node_info.height; current_node_info->left_balance = 0; current_node_info->right_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->left; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = next_node_info.height-other_node_info.height; current_node_info->left_balance = other_node_info.balance; current_node_info->right_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } else { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->left; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->left = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->right==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = -next_node_info.height; current_node_info->right_balance = 0; current_node_info->left_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->right; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = other_node_info.height-next_node_info.height; current_node_info->right_balance = other_node_info.balance; current_node_info->left_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove_node(int* current_index,const stringT & string,const size_t current_position) { tst_node<charT,valueT>* current_node = storage->get(*current_index); int diff,*next_index; if(current_node->c==0) { return; } else { diff=string[current_position]-(current_node->c); } if(diff==0) { if(current_position+1<string.size()) { next_index = &(current_node->next); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position+1); } } else { current_node->store(default_value); } } else if(diff>0) { next_index = &(current_node->right); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } else { next_index = &(current_node->left); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } current_node=storage->get(*current_index); if( current_node->data==default_value && current_node->next==UNDEFINED_INDEX && current_node->right==UNDEFINED_INDEX && current_node->left==UNDEFINED_INDEX) { storage->delete_node(*current_index); *current_index=UNDEFINED_INDEX; } else { node_info<charT,valueT> current_node_info; current_node_info.index=*current_index; current_node_info.node=current_node; current_node_info.height=-1; balance_node(&current_node_info); *current_index = current_node_info.index; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::balance_node(node_info<charT,valueT>* bal) { if(bal->height==-1) { compute_height_and_balance(bal); } bal->balance_performed=0; if(bal->balance>1) { if(bal->right_balance>0) { rr(bal); } else { rl(bal); } bal->balance_performed=1; } else if(bal->balance<-1) { if(bal->left_balance<0) { ll(bal); } else { lr(bal); } bal->balance_performed=1; } assert(abs(bal->balance)<2); assert(abs(bal->right_balance)<2); assert(abs(bal->left_balance)<2); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::ll(node_info<charT,valueT>* bal) { int left_index=bal->node->left; tst_node<charT,valueT>* left_node=storage->get(left_index); int left_right_index=left_node->right; bal->node->left=left_right_index; left_node->right=bal->index; bal->index=left_index; bal->node=storage->get(left_index); bal->height=bal->height-1; bal->balance=0; bal->right_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rr(node_info<charT,valueT>* bal) { int right_index=bal->node->right; tst_node<charT,valueT>* right_node=storage->get(right_index); int right_left_index=right_node->left; bal->node->right=right_left_index; right_node->left=bal->index; bal->index=right_index; bal->node=storage->get(right_index); bal->height=bal->height-1; bal->balance=0; bal->left_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::lr(node_info<charT,valueT>* bal) { node_info<charT,valueT> left; left.index = bal->node->left; left.node = storage->get(left.index); rr(&left); bal->node->left=left.index; ll(bal); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rl(node_info<charT,valueT>* bal) { node_info<charT,valueT> right; right.index = bal->node->right; right.node = storage->get(right.index); ll(&right); bal->node->right=right.index; rr(bal); } diff --git a/python/pythonTST.h b/python/pythonTST.h index fb20778..8e0574c 100644 --- a/python/pythonTST.h +++ b/python/pythonTST.h @@ -1,340 +1,340 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define __PYTHON__BUILD__ #include "tst.h" #include "Python.h" #include "PythonReference.h" #include "qad_string.h" #include <iostream> #include <fstream> #ifdef ZIPPED_TREE #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/zlib.hpp> #endif typedef qad_string<char> string_type; class CallableAction : public tst_action<char,PythonReference,string_type > { public: CallableAction(PythonReference perform,PythonReference result) : _perform(perform), _result(result) { } virtual ~CallableAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { if(_perform.get()==Py_None) { return; } PythonReference tuple(Py_BuildValue("s#iO",string.data(),string.size(),remaining_distance,data.get()),0); PyObject* result = PyObject_CallObject(_perform.get(),tuple.get()); if(result) { Py_DECREF(result); } else { throw PythonException("An exception was raised in a Python callback"); } } virtual PythonReference result() { if(_result.get()==Py_None) { return PythonReference(); } else { PyObject* result = PyObject_CallObject(_result.get(),0); if(result) { return PythonReference(result,0); } else { throw PythonException("An exception was raised in a Python callback"); } } } private: PythonReference _perform,_result; }; class CallableFilter : public tst_filter<char,PythonReference,string_type > { public: CallableFilter(PythonReference _callable) : callable(_callable) { } virtual ~CallableFilter() { } virtual PythonReference perform(const string_type& string,int remaining_distance,PythonReference data) { PythonReference tuple(Py_BuildValue("s#iO",string.data(),string.size(),remaining_distance,data.get()),0); PyObject* result = PyObject_CallObject(callable.get(),tuple.get()); if(result) { return PythonReference(result,0); } else { throw PythonException("An exception was raised in a Python callback"); } } private: PythonReference callable; }; class DictAction : public tst_action<char,PythonReference,string_type > { public: DictAction() : dict(PyDict_New(),0) { } virtual ~DictAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { PythonReference key(Py_BuildValue("s#",string.data(),string.size()),0); PyObject* old_tuple=PyDict_GetItem(dict.get(),key.get()); if(old_tuple!=0) { long value=PyInt_AsLong(PyTuple_GetItem(old_tuple,0)); if(value<remaining_distance) { return; } } PythonReference tuple(Py_BuildValue("iO",remaining_distance,data.get()),0); PyDict_SetItem(dict.get(),key.get(),tuple.get()); }; virtual PythonReference result() { return dict; } private: PythonReference dict; }; class ListAction : public tst_action<char,PythonReference,string_type > { public: ListAction() : list(PyList_New(0),0) { } virtual ~ListAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { PyList_Append(list.get(),data.get()); } virtual PythonReference result() { return list; } private: PythonReference list; }; class TupleListAction : public tst_action<char,PythonReference,string_type > { public: TupleListAction() : list(PyList_New(0),0){ } virtual ~TupleListAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { PythonReference tuple(Py_BuildValue("s#iO",string.data(),string.size(),remaining_distance,data.get()),0); PyList_Append(list.get(),tuple.get()); } virtual PythonReference result() { return list; } private: PythonReference list; }; class ObjectSerializer { public: ObjectSerializer(); void write(std::ostream& file,PythonReference data); PythonReference read(std::istream& file); private: PythonReference dumps,loads; }; ObjectSerializer::ObjectSerializer() { PythonReference name(PyString_FromString("cPickle"),0); PythonReference cPickle(PyImport_Import(name.get()),0); dumps = PythonReference(PyObject_GetAttrString(cPickle.get(),"dumps"),0); loads = PythonReference(PyObject_GetAttrString(cPickle.get(),"loads"),0); } void ObjectSerializer::write(std::ostream& file,PythonReference data) { PythonReference call(Py_BuildValue("Oi",data.get(),2),0); PythonReference result(PyObject_CallObject(dumps.get(),call.get()),0); char *string; - int length; + Py_ssize_t length; PyString_AsStringAndSize(result.get(),&string,&length); - file.write((char*)(&length),sizeof(int)); + file.write((char*)(&length),sizeof(Py_ssize_t)); file.write(string,length); } PythonReference ObjectSerializer::read(std::istream& file) { - int length; - file.read((char*)(&length),sizeof(int)); + Py_ssize_t length; + file.read((char*)(&length),sizeof(Py_ssize_t)); char* string=(char*)tst_malloc(length); file.read(string,length); PythonReference dumped(PyString_FromStringAndSize(string,length),0); PythonReference call(Py_BuildValue("(O)",dumped.get()),0); PythonReference result(PyObject_CallObject(loads.get(),call.get()),0); tst_free(string); return result; } class TST; template <typename iterator_type> class TSTIterator { public: friend class TST; TSTIterator __iter__() { return *this; } PyObject* next() { typename iterator_type::value_type v(iterator.next()); if(v.second) { return Py_BuildValue("s#O",v.first.data(),v.first.size(),v.second->get()); } else { PythonReference exceptions(PyImport_ImportModule("exceptions"),0); PythonReference stop_iteration = exceptions.getattr("StopIteration"); PyErr_SetNone(stop_iteration.get()); return 0; } } private: TSTIterator(iterator_type i) : iterator(i) { } iterator_type iterator; }; typedef TSTIterator<lexical_iterator<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > > TSTLexicalIterator; typedef TSTIterator<match_iterator<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > > TSTCloseMatchIterator; class TST : public tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > { public: TST() : tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >() { } virtual ~TST() { } virtual PythonReference write_to_file(PythonReference file) { if(!PyString_CheckExact(file.get())) { throw PythonException("Argument of write_to_file() must be a string object"); } std::ofstream out(PyString_AsString(file.get()),std::ofstream::binary|std::ofstream::out|std::ofstream::trunc); out.exceptions(std::ofstream::eofbit | std::ofstream::failbit | std::ofstream::badbit); #ifdef ZIPPED_TREE boost::iostreams::filtering_ostream fout; fout.push(boost::iostreams::zlib_compressor()); fout.push(out); this->write(fout); fout.strict_sync(); #else this->write(out); #endif out.close(); return PythonReference(); } virtual PythonReference read_from_file(PythonReference file) { if(!PyString_CheckExact(file.get())) { throw PythonException("Argument of read_from_file() must be a string object"); } std::ifstream in(PyString_AsString(file.get()),std::ifstream::binary|std::ifstream::in); in.exceptions(std::ifstream::eofbit | std::ifstream::failbit | std::ifstream::badbit); #ifdef ZIPPED_TREE boost::iostreams::filtering_istream fin; fin.push(boost::iostreams::zlib_decompressor()); fin.push(in); this->read(fin); #else this->read(in); #endif in.close(); return PythonReference(); } PythonReference __getitem__(const string_type& string) { return get(string); } PythonReference __setitem__(const string_type& string,PythonReference data) { return put(string,data); } void __delitem__(const string_type& string) { remove(string); } PythonReference __contains__(const string_type& string) { if(contains(string)) { return PythonReference(Py_False); } else { return PythonReference(Py_True); } } TSTLexicalIterator __iter__() { return TSTLexicalIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::iterator()); } TSTLexicalIterator iterator() { return TSTLexicalIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::iterator()); } TSTLexicalIterator iterator(const string_type& string) { return TSTLexicalIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::iterator(string)); } TSTCloseMatchIterator close_match_iterator(const string_type& string, int distance) { return TSTCloseMatchIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::close_match_iterator(string,distance)); } using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::put; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::get; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::pack; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::walk; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::close_match; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::match; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::scan; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::scan_with_stop_chars; }; diff --git a/python/setup.py b/python/setup.py index e76e03e..b3b5a66 100644 --- a/python/setup.py +++ b/python/setup.py @@ -1,49 +1,49 @@ # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from distutils.core import setup, Extension import sys extra_compile_args = [] setup( name = "pytst", - version = "1.16", + version = "1.17-dev", author = "Nicolas Lehuen", author_email = "nicolas@lehuen.com", url = "http://nicolas.lehuen.com/index.php/category/Pytst", description = "An implementation of a Ternary Search Tree (TST) in C++ with Python bindings", py_modules = ["tst"], ext_modules = [ Extension( "_tst", ["tst_wrap.cxx"], include_dirs=['../include'], extra_compile_args = extra_compile_args, define_macros=[('SCANNER', None),], ) ], download_url = "http://nicolas.lehuen.com/download/pytst/", classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: C++', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Scientific/Engineering :: Information Analysis', ] ) diff --git a/python/tst.i b/python/tst.i index 51fa8e2..262ebbc 100644 --- a/python/tst.i +++ b/python/tst.i @@ -1,83 +1,83 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ %module tst %feature("autodoc", "1"); %typemap(in) PythonReference { $1 = PythonReference($input); } %typemap(out) PythonReference { $result = $1.lend(); } %typemap(in) const string_type&, string_type& { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize($input,&buffer,&size); $1 = new string_type(buffer,size); } %typemap(freearg) const string_type&, string_type& { delete $1; } %typemap(out) const string_type&, string_type& { $result = PyString_FromStringAndSize($1.data(),$1.size()); } %typemap(ret) const string_type&, string_type& { delete $1; } %exception { try { $action } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } #define __PYTHON__BUILD__ %include "tst.h" %include "fundamentals.h" %include "iterators.h" %include "memory_storage.h" %template(_TST) tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >; %template(_Action) tst_action<char,PythonReference,string_type >; %template(_Filter) tst_filter<char,PythonReference,string_type >; %include "pythonTST.h" %template(_lexical_iterator_type) lexical_iterator<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >; %template(_close_match_iterator_type) match_iterator<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >; %template(TSTLexicalIterator) TSTIterator<lexical_iterator<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > >; %template(TSTCloseMatchIterator) TSTIterator<match_iterator<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > >; %{ #include "pythonTST.h" %} diff --git a/python/tst_wrap.cxx b/python/tst_wrap.cxx index 13a461c..23fdb6b 100644 --- a/python/tst_wrap.cxx +++ b/python/tst_wrap.cxx @@ -2882,3892 +2882,3892 @@ SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc) } else { swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); if (pchar_descriptor) { void* vptr = 0; if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { if (cptr) *cptr = (char *) vptr; if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; if (alloc) *alloc = SWIG_OLDOBJ; return SWIG_OK; } } } return SWIG_TypeError; } #include <limits.h> #if !defined(SWIG_NO_LLONG_MAX) # if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) # define LLONG_MAX __LONG_LONG_MAX__ # define LLONG_MIN (-LLONG_MAX - 1LL) # define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) # endif #endif SWIGINTERN int SWIG_AsVal_double (PyObject *obj, double *val) { int res = SWIG_TypeError; if (PyFloat_Check(obj)) { if (val) *val = PyFloat_AsDouble(obj); return SWIG_OK; } else if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { double v = PyLong_AsDouble(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; double d = PyFloat_AsDouble(obj); if (!PyErr_Occurred()) { if (val) *val = d; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_AddCast(SWIG_OK)); } else { PyErr_Clear(); } } } #endif return res; } #include <float.h> #include <math.h> SWIGINTERNINLINE int SWIG_CanCastAsInteger(double *d, double min, double max) { double x = *d; if ((min <= x && x <= max)) { double fx = floor(x); double cx = ceil(x); double rd = ((x - fx) < 0.5) ? fx : cx; /* simple rint */ if ((errno == EDOM) || (errno == ERANGE)) { errno = 0; } else { double summ, reps, diff; if (rd < x) { diff = x - rd; } else if (rd > x) { diff = rd - x; } else { return 1; } summ = rd + x; reps = diff/summ; if (reps < 8*DBL_EPSILON) { *d = rd; return 1; } } } return 0; } SWIGINTERN int SWIG_AsVal_long (PyObject *obj, long* val) { if (PyInt_Check(obj)) { if (val) *val = PyInt_AsLong(obj); return SWIG_OK; } else if (PyLong_Check(obj)) { long v = PyLong_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_OK; } else { PyErr_Clear(); } } #ifdef SWIG_PYTHON_CAST_MODE { int dispatch = 0; long v = PyInt_AsLong(obj); if (!PyErr_Occurred()) { if (val) *val = v; return SWIG_AddCast(SWIG_OK); } else { PyErr_Clear(); } if (!dispatch) { double d; int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d)); if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) { if (val) *val = (long)(d); return res; } } } #endif return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_int (PyObject * obj, int *val) { long v; int res = SWIG_AsVal_long (obj, &v); if (SWIG_IsOK(res)) { if ((v < INT_MIN || v > INT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = static_cast< int >(v); } } return res; } SWIGINTERNINLINE PyObject* SWIG_From_bool (bool value) { return PyBool_FromLong(value ? 1 : 0); } #include "pythonTST.h" #ifdef __cplusplus extern "C" { #endif SWIGINTERN int Swig_var_TST_VERSION_set(PyObject *) { SWIG_Error(SWIG_AttributeError,"Variable TST_VERSION is read-only."); return 1; } SWIGINTERN PyObject *Swig_var_TST_VERSION_get(void) { PyObject *pyobj = 0; pyobj = SWIG_FromCharPtr(TST_VERSION); return pyobj; } SWIGINTERN int Swig_var_UNDEFINED_INDEX_set(PyObject *) { SWIG_Error(SWIG_AttributeError,"Variable UNDEFINED_INDEX is read-only."); return 1; } SWIGINTERN PyObject *Swig_var_UNDEFINED_INDEX_get(void) { PyObject *pyobj = 0; pyobj = SWIG_From_int(static_cast< int >(UNDEFINED_INDEX)); return pyobj; } SWIGINTERN PyObject *_wrap_new_TSTException(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; char *arg1 = (char *) 0 ; int res1 ; char *buf1 = 0 ; int alloc1 = 0 ; PyObject *swig_obj[1] ; TSTException *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_AsCharPtrAndSize(swig_obj[0], &buf1, NULL, &alloc1); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_TSTException" "', argument " "1"" of type '" "char const *""'"); } arg1 = reinterpret_cast< char * >(buf1); { try { result = (TSTException *)new TSTException((char const *)arg1); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_TSTException, SWIG_POINTER_NEW | 0 ); if (alloc1 == SWIG_NEWOBJ) delete[] buf1; return resultobj; fail: if (alloc1 == SWIG_NEWOBJ) delete[] buf1; return NULL; } SWIGINTERN PyObject *_wrap_TSTException_what(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTException *arg1 = (TSTException *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; char *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TSTException, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TSTException_what" "', argument " "1"" of type '" "TSTException *""'"); } arg1 = reinterpret_cast< TSTException * >(argp1); { try { result = (char *)(arg1)->what(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_FromCharPtr((const char *)result); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_TSTException(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTException *arg1 = (TSTException *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TSTException, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_TSTException" "', argument " "1"" of type '" "TSTException *""'"); } arg1 = reinterpret_cast< TSTException * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *TSTException_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_TSTException, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *TSTException_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { return SWIG_Python_InitShadowInstance(args); } SWIGINTERN PyObject *_wrap_new__TST(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *result = 0 ; if (!SWIG_Python_UnpackTuple(args,"new__TST",0,0,0)) SWIG_fail; { try { result = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *)new tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete__TST(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete__TST" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_pack(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_pack" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { (arg1)->pack(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_walk__SWIG_0(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; tst_filter< char,PythonReference,string_type > *arg2 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg3 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; PythonReference result; if ((nobjs < 3) || (nobjs > 3)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_walk" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &argp2,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "_TST_walk" "', argument " "2"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg2 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp2); res3 = SWIG_ConvertPtr(swig_obj[2], &argp3,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "_TST_walk" "', argument " "3"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp3); { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->walk(arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_walk__SWIG_1(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; tst_filter< char,PythonReference,string_type > *arg2 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg3 = (tst_action< char,PythonReference,string_type > *) 0 ; string_type *arg4 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; PythonReference result; if ((nobjs < 4) || (nobjs > 4)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_walk" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &argp2,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "_TST_walk" "', argument " "2"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg2 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp2); res3 = SWIG_ConvertPtr(swig_obj[2], &argp3,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "_TST_walk" "', argument " "3"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp3); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[3],&buffer,&size); arg4 = new string_type(buffer,size); } { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->walk(arg2,arg3,(string_type const &)*arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg4; } return resultobj; fail: { delete arg4; } return NULL; } SWIGINTERN PyObject *_wrap__TST_walk(PyObject *self, PyObject *args) { int argc; PyObject *argv[5]; if (!(argc = SWIG_Python_UnpackTuple(args,"_TST_walk",0,4,argv))) SWIG_fail; --argc; if (argc == 3) { return _wrap__TST_walk__SWIG_0(self, argc, argv); } if (argc == 4) { return _wrap__TST_walk__SWIG_1(self, argc, argv); } fail: SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function '_TST_walk'.\n" " Possible C/C++ prototypes are:\n" " walk(tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *,tst_filter< char,PythonReference,string_type > *,tst_action< char,PythonReference,string_type > *)\n" " walk(tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *,tst_filter< char,PythonReference,string_type > *,tst_action< char,PythonReference,string_type > *,string_type const &)\n"); return NULL; } SWIGINTERN PyObject *_wrap__TST_close_match(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; int arg3 ; tst_filter< char,PythonReference,string_type > *arg4 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg5 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int val3 ; int ecode3 = 0 ; void *argp4 = 0 ; int res4 = 0 ; void *argp5 = 0 ; int res5 = 0 ; PyObject *swig_obj[5] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"_TST_close_match",5,5,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_close_match" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "_TST_close_match" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); res4 = SWIG_ConvertPtr(swig_obj[3], &argp4,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "_TST_close_match" "', argument " "4"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg4 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp4); res5 = SWIG_ConvertPtr(swig_obj[4], &argp5,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res5)) { SWIG_exception_fail(SWIG_ArgError(res5), "in method '" "_TST_close_match" "', argument " "5"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg5 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp5); { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->close_match((string_type const &)*arg2,arg3,arg4,arg5); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_prefix_match(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; tst_filter< char,PythonReference,string_type > *arg3 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg4 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp3 = 0 ; int res3 = 0 ; void *argp4 = 0 ; int res4 = 0 ; PyObject *swig_obj[4] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"_TST_prefix_match",4,4,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_prefix_match" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } res3 = SWIG_ConvertPtr(swig_obj[2], &argp3,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "_TST_prefix_match" "', argument " "3"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp3); res4 = SWIG_ConvertPtr(swig_obj[3], &argp4,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "_TST_prefix_match" "', argument " "4"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg4 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp4); { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->prefix_match((string_type const &)*arg2,arg3,arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_match(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; tst_filter< char,PythonReference,string_type > *arg3 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg4 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp3 = 0 ; int res3 = 0 ; void *argp4 = 0 ; int res4 = 0 ; PyObject *swig_obj[4] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"_TST_match",4,4,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_match" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } res3 = SWIG_ConvertPtr(swig_obj[2], &argp3,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "_TST_match" "', argument " "3"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp3); res4 = SWIG_ConvertPtr(swig_obj[3], &argp4,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "_TST_match" "', argument " "4"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg4 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp4); { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->match((string_type const &)*arg2,arg3,arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[2] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"_TST_get",2,2,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_get" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->get((string_type const &)*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_get_or_build(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; tst_filter< char,PythonReference,string_type > *arg3 = (tst_filter< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp3 = 0 ; int res3 = 0 ; PyObject *swig_obj[3] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"_TST_get_or_build",3,3,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_get_or_build" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } res3 = SWIG_ConvertPtr(swig_obj[2], &argp3,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "_TST_get_or_build" "', argument " "3"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp3); { try { result = (arg1)->get_or_build((string_type const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_put(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; PythonReference arg3 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[3] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"_TST_put",3,3,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_put" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { arg3 = PythonReference(swig_obj[2]); } { try { result = (arg1)->put((string_type const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_remove(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[2] ; if (!SWIG_Python_UnpackTuple(args,"_TST_remove",2,2,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_remove" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { try { (arg1)->remove((string_type const &)*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_contains(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[2] ; bool result; if (!SWIG_Python_UnpackTuple(args,"_TST_contains",2,2,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_contains" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { try { result = (bool)((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->contains((string_type const &)*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_From_bool(static_cast< bool >(result)); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_write(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; std::ostream *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject *swig_obj[2] ; if (!SWIG_Python_UnpackTuple(args,"_TST_write",2,2,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_write" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_std__ostream, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "_TST_write" "', argument " "2"" of type '" "std::ostream &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "_TST_write" "', argument " "2"" of type '" "std::ostream &""'"); } arg2 = reinterpret_cast< std::ostream * >(argp2); { try { ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->write(*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_read(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; std::istream *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject *swig_obj[2] ; if (!SWIG_Python_UnpackTuple(args,"_TST_read",2,2,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_read" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_std__istream, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "_TST_read" "', argument " "2"" of type '" "std::istream &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "_TST_read" "', argument " "2"" of type '" "std::istream &""'"); } arg2 = reinterpret_cast< std::istream * >(argp2); { try { (arg1)->read(*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_iterator__SWIG_0(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; SwigValueWrapper< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > result; if ((nobjs < 1) || (nobjs > 1)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_iterator" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->iterator(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >(static_cast< const lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >& >(result))), SWIGTYPE_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_iterator__SWIG_1(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; SwigValueWrapper< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > result; if ((nobjs < 2) || (nobjs > 2)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_iterator" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->iterator((string_type const &)*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >(static_cast< const lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >& >(result))), SWIGTYPE_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_OWN | 0 ); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_iterator(PyObject *self, PyObject *args) { int argc; PyObject *argv[3]; if (!(argc = SWIG_Python_UnpackTuple(args,"_TST_iterator",0,2,argv))) SWIG_fail; --argc; if (argc == 1) { return _wrap__TST_iterator__SWIG_0(self, argc, argv); } if (argc == 2) { return _wrap__TST_iterator__SWIG_1(self, argc, argv); } fail: SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function '_TST_iterator'.\n" " Possible C/C++ prototypes are:\n" " iterator(tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)\n" " iterator(tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *,string_type const &)\n"); return NULL; } SWIGINTERN PyObject *_wrap__TST_close_match_iterator(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; int arg3 ; void *argp1 = 0 ; int res1 = 0 ; int val3 ; int ecode3 = 0 ; PyObject *swig_obj[3] ; SwigValueWrapper< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > result; if (!SWIG_Python_UnpackTuple(args,"_TST_close_match_iterator",3,3,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_close_match_iterator" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "_TST_close_match_iterator" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->close_match_iterator((string_type const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >(static_cast< const match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >& >(result))), SWIGTYPE_p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_OWN | 0 ); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_get_number_of_nodes(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; int result; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_get_number_of_nodes" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { result = (int)((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->get_number_of_nodes(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_From_int(static_cast< int >(result)); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_get_default_value(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; PythonReference result; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_get_default_value" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->get_default_value(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__TST_scan(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; tst_action< char,PythonReference,string_type > *arg3 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp3 = 0 ; int res3 = 0 ; PyObject *swig_obj[3] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"_TST_scan",3,3,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_scan" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } res3 = SWIG_ConvertPtr(swig_obj[2], &argp3,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "_TST_scan" "', argument " "3"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp3); { try { result = (arg1)->scan((string_type const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__TST_scan_with_stop_chars(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; string_type *arg2 = 0 ; string_type *arg3 = 0 ; tst_action< char,PythonReference,string_type > *arg4 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp4 = 0 ; int res4 = 0 ; PyObject *swig_obj[4] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"_TST_scan_with_stop_chars",4,4,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_TST_scan_with_stop_chars" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[2],&buffer,&size); arg3 = new string_type(buffer,size); } res4 = SWIG_ConvertPtr(swig_obj[3], &argp4,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "_TST_scan_with_stop_chars" "', argument " "4"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg4 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp4); { try { result = ((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > const *)arg1)->scan_with_stop_chars((string_type const &)*arg2,(string_type const &)*arg3,arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } { delete arg3; } return resultobj; fail: { delete arg2; } { delete arg3; } return NULL; } SWIGINTERN PyObject *_TST_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_TST_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { return SWIG_Python_InitShadowInstance(args); } SWIGINTERN PyObject *_wrap_delete__Action(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst_action< char,PythonReference,string_type > *arg1 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete__Action" "', argument " "1"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg1 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__Action_perform(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst_action< char,PythonReference,string_type > *arg1 = (tst_action< char,PythonReference,string_type > *) 0 ; string_type *arg2 = 0 ; int arg3 ; PythonReference arg4 ; void *argp1 = 0 ; int res1 = 0 ; int val3 ; int ecode3 = 0 ; PyObject *swig_obj[4] ; if (!SWIG_Python_UnpackTuple(args,"_Action_perform",4,4,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_Action_perform" "', argument " "1"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg1 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "_Action_perform" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); { arg4 = PythonReference(swig_obj[3]); } { try { (arg1)->perform((string_type const &)*arg2,arg3,arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap__Action_result(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst_action< char,PythonReference,string_type > *arg1 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; PythonReference result; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_Action_result" "', argument " "1"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg1 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp1); { try { result = (arg1)->result(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_Action_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_delete__Filter(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst_filter< char,PythonReference,string_type > *arg1 = (tst_filter< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete__Filter" "', argument " "1"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg1 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__Filter_perform(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst_filter< char,PythonReference,string_type > *arg1 = (tst_filter< char,PythonReference,string_type > *) 0 ; string_type *arg2 = 0 ; int arg3 ; PythonReference arg4 ; void *argp1 = 0 ; int res1 = 0 ; int val3 ; int ecode3 = 0 ; PyObject *swig_obj[4] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"_Filter_perform",4,4,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_Filter_perform" "', argument " "1"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg1 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "_Filter_perform" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); { arg4 = PythonReference(swig_obj[3]); } { try { result = (arg1)->perform((string_type const &)*arg2,arg3,arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_Filter_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_new_CallableAction(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; PythonReference arg1 ; PythonReference arg2 ; PyObject *swig_obj[2] ; CallableAction *result = 0 ; if (!SWIG_Python_UnpackTuple(args,"new_CallableAction",2,2,swig_obj)) SWIG_fail; { arg1 = PythonReference(swig_obj[0]); } { arg2 = PythonReference(swig_obj[1]); } { try { result = (CallableAction *)new CallableAction(arg1,arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_CallableAction, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_CallableAction(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; CallableAction *arg1 = (CallableAction *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_CallableAction, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_CallableAction" "', argument " "1"" of type '" "CallableAction *""'"); } arg1 = reinterpret_cast< CallableAction * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *CallableAction_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_CallableAction, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *CallableAction_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { return SWIG_Python_InitShadowInstance(args); } SWIGINTERN PyObject *_wrap_new_CallableFilter(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; PythonReference arg1 ; PyObject *swig_obj[1] ; CallableFilter *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; { arg1 = PythonReference(swig_obj[0]); } { try { result = (CallableFilter *)new CallableFilter(arg1); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_CallableFilter, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_CallableFilter(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; CallableFilter *arg1 = (CallableFilter *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_CallableFilter, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_CallableFilter" "', argument " "1"" of type '" "CallableFilter *""'"); } arg1 = reinterpret_cast< CallableFilter * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *CallableFilter_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_CallableFilter, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *CallableFilter_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { return SWIG_Python_InitShadowInstance(args); } SWIGINTERN PyObject *_wrap_new_DictAction(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; DictAction *result = 0 ; if (!SWIG_Python_UnpackTuple(args,"new_DictAction",0,0,0)) SWIG_fail; { try { result = (DictAction *)new DictAction(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_DictAction, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_DictAction(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; DictAction *arg1 = (DictAction *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_DictAction, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_DictAction" "', argument " "1"" of type '" "DictAction *""'"); } arg1 = reinterpret_cast< DictAction * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *DictAction_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_DictAction, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *DictAction_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { return SWIG_Python_InitShadowInstance(args); } SWIGINTERN PyObject *_wrap_new_ListAction(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ListAction *result = 0 ; if (!SWIG_Python_UnpackTuple(args,"new_ListAction",0,0,0)) SWIG_fail; { try { result = (ListAction *)new ListAction(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ListAction, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_ListAction(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ListAction *arg1 = (ListAction *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ListAction, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_ListAction" "', argument " "1"" of type '" "ListAction *""'"); } arg1 = reinterpret_cast< ListAction * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *ListAction_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_ListAction, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *ListAction_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { return SWIG_Python_InitShadowInstance(args); } SWIGINTERN PyObject *_wrap_new_TupleListAction(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TupleListAction *result = 0 ; if (!SWIG_Python_UnpackTuple(args,"new_TupleListAction",0,0,0)) SWIG_fail; { try { result = (TupleListAction *)new TupleListAction(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_TupleListAction, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_TupleListAction(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TupleListAction *arg1 = (TupleListAction *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TupleListAction, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_TupleListAction" "', argument " "1"" of type '" "TupleListAction *""'"); } arg1 = reinterpret_cast< TupleListAction * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *TupleListAction_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_TupleListAction, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *TupleListAction_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { return SWIG_Python_InitShadowInstance(args); } SWIGINTERN PyObject *_wrap_new_ObjectSerializer(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ObjectSerializer *result = 0 ; if (!SWIG_Python_UnpackTuple(args,"new_ObjectSerializer",0,0,0)) SWIG_fail; { try { result = (ObjectSerializer *)new ObjectSerializer(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_ObjectSerializer, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ObjectSerializer_write(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ObjectSerializer *arg1 = (ObjectSerializer *) 0 ; std::ostream *arg2 = 0 ; PythonReference arg3 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject *swig_obj[3] ; if (!SWIG_Python_UnpackTuple(args,"ObjectSerializer_write",3,3,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ObjectSerializer, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ObjectSerializer_write" "', argument " "1"" of type '" "ObjectSerializer *""'"); } arg1 = reinterpret_cast< ObjectSerializer * >(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_std__ostream, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ObjectSerializer_write" "', argument " "2"" of type '" "std::ostream &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "ObjectSerializer_write" "', argument " "2"" of type '" "std::ostream &""'"); } arg2 = reinterpret_cast< std::ostream * >(argp2); { arg3 = PythonReference(swig_obj[2]); } { try { (arg1)->write(*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_ObjectSerializer_read(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ObjectSerializer *arg1 = (ObjectSerializer *) 0 ; std::istream *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject *swig_obj[2] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"ObjectSerializer_read",2,2,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ObjectSerializer, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ObjectSerializer_read" "', argument " "1"" of type '" "ObjectSerializer *""'"); } arg1 = reinterpret_cast< ObjectSerializer * >(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_std__istream, 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ObjectSerializer_read" "', argument " "2"" of type '" "std::istream &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "ObjectSerializer_read" "', argument " "2"" of type '" "std::istream &""'"); } arg2 = reinterpret_cast< std::istream * >(argp2); { try { result = (arg1)->read(*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_ObjectSerializer(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; ObjectSerializer *arg1 = (ObjectSerializer *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ObjectSerializer, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_ObjectSerializer" "', argument " "1"" of type '" "ObjectSerializer *""'"); } arg1 = reinterpret_cast< ObjectSerializer * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *ObjectSerializer_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_ObjectSerializer, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *ObjectSerializer_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { return SWIG_Python_InitShadowInstance(args); } SWIGINTERN PyObject *_wrap_new_TST(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *result = 0 ; if (!SWIG_Python_UnpackTuple(args,"new_TST",0,0,0)) SWIG_fail; { try { result = (TST *)new TST(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_TST, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_TST(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_TST" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_TST_write_to_file(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; PythonReference arg2 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[2] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"TST_write_to_file",2,2,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_write_to_file" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { arg2 = PythonReference(swig_obj[1]); } { try { result = (arg1)->write_to_file(arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_TST_read_from_file(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; PythonReference arg2 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[2] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"TST_read_from_file",2,2,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_read_from_file" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { arg2 = PythonReference(swig_obj[1]); } { try { result = (arg1)->read_from_file(arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_TST___getitem__(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[2] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"TST___getitem__",2,2,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST___getitem__" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { try { result = (arg1)->__getitem__((string_type const &)*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST___setitem__(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; PythonReference arg3 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[3] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"TST___setitem__",3,3,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST___setitem__" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { arg3 = PythonReference(swig_obj[2]); } { try { result = (arg1)->__setitem__((string_type const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST___delitem__(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[2] ; if (!SWIG_Python_UnpackTuple(args,"TST___delitem__",2,2,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST___delitem__" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { try { (arg1)->__delitem__((string_type const &)*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST___contains__(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[2] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"TST___contains__",2,2,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST___contains__" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { try { result = (arg1)->__contains__((string_type const &)*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST___iter__(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; SwigValueWrapper< TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > > result; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST___iter__" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { try { result = (arg1)->__iter__(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new TSTLexicalIterator(static_cast< const TSTLexicalIterator& >(result))), SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_TST_iterator__SWIG_0(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; void *argp1 = 0 ; int res1 = 0 ; SwigValueWrapper< TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > > result; if ((nobjs < 1) || (nobjs > 1)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_iterator" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { try { result = (arg1)->iterator(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new TSTLexicalIterator(static_cast< const TSTLexicalIterator& >(result))), SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_TST_iterator__SWIG_1(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; SwigValueWrapper< TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > > result; if ((nobjs < 2) || (nobjs > 2)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_iterator" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { try { result = (arg1)->iterator((string_type const &)*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new TSTLexicalIterator(static_cast< const TSTLexicalIterator& >(result))), SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_POINTER_OWN | 0 ); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST_iterator(PyObject *self, PyObject *args) { int argc; PyObject *argv[3]; if (!(argc = SWIG_Python_UnpackTuple(args,"TST_iterator",0,2,argv))) SWIG_fail; --argc; if (argc == 1) { return _wrap_TST_iterator__SWIG_0(self, argc, argv); } if (argc == 2) { return _wrap_TST_iterator__SWIG_1(self, argc, argv); } fail: SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'TST_iterator'.\n" " Possible C/C++ prototypes are:\n" " iterator(TST *)\n" " iterator(TST *,string_type const &)\n"); return NULL; } SWIGINTERN PyObject *_wrap_TST_close_match_iterator(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; int arg3 ; void *argp1 = 0 ; int res1 = 0 ; int val3 ; int ecode3 = 0 ; PyObject *swig_obj[3] ; SwigValueWrapper< TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > > result; if (!SWIG_Python_UnpackTuple(args,"TST_close_match_iterator",3,3,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_close_match_iterator" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "TST_close_match_iterator" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); { try { result = (arg1)->close_match_iterator((string_type const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new TSTCloseMatchIterator(static_cast< const TSTCloseMatchIterator& >(result))), SWIGTYPE_p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_POINTER_OWN | 0 ); { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST_put(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; PythonReference arg3 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[3] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"TST_put",3,3,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_put" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { arg3 = PythonReference(swig_obj[2]); } { try { result = (arg1)->put((string_type const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[2] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"TST_get",2,2,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_get" "', argument " "1"" of type '" "TST const *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { try { result = ((TST const *)arg1)->get((string_type const &)*arg2); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST_pack(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_pack" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { try { (arg1)->pack(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_TST_walk_SWIG_0_0(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; tst_filter< char,PythonReference,string_type > *arg2 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg3 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; PythonReference result; if ((nobjs < 3) || (nobjs > 3)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_walk" "', argument " "1"" of type '" "TST const *""'"); } arg1 = reinterpret_cast< TST * >(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &argp2,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "TST_walk" "', argument " "2"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg2 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp2); res3 = SWIG_ConvertPtr(swig_obj[2], &argp3,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "TST_walk" "', argument " "3"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp3); { try { result = ((TST const *)arg1)->walk(arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_TST_walk_SWIG_0_1(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; tst_filter< char,PythonReference,string_type > *arg2 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg3 = (tst_action< char,PythonReference,string_type > *) 0 ; string_type *arg4 = 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; void *argp3 = 0 ; int res3 = 0 ; PythonReference result; if ((nobjs < 4) || (nobjs > 4)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_walk" "', argument " "1"" of type '" "TST const *""'"); } arg1 = reinterpret_cast< TST * >(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &argp2,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "TST_walk" "', argument " "2"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg2 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp2); res3 = SWIG_ConvertPtr(swig_obj[2], &argp3,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "TST_walk" "', argument " "3"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp3); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[3],&buffer,&size); arg4 = new string_type(buffer,size); } { try { result = ((TST const *)arg1)->walk(arg2,arg3,(string_type const &)*arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg4; } return resultobj; fail: { delete arg4; } return NULL; } SWIGINTERN PyObject *_wrap_TST_walk(PyObject *self, PyObject *args) { int argc; PyObject *argv[5]; if (!(argc = SWIG_Python_UnpackTuple(args,"TST_walk",0,4,argv))) SWIG_fail; --argc; if (argc == 3) { return _wrap_TST_walk_SWIG_0_0(self, argc, argv); } if (argc == 4) { return _wrap_TST_walk_SWIG_0_1(self, argc, argv); } fail: SWIG_SetErrorMsg(PyExc_NotImplementedError,"Wrong number of arguments for overloaded function 'TST_walk'.\n" " Possible C/C++ prototypes are:\n" " walk(TST const *,tst_filter< char,PythonReference,string_type > *,tst_action< char,PythonReference,string_type > *)\n" " walk(TST const *,tst_filter< char,PythonReference,string_type > *,tst_action< char,PythonReference,string_type > *,string_type const &)\n"); return NULL; } SWIGINTERN PyObject *_wrap_TST_close_match(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; int arg3 ; tst_filter< char,PythonReference,string_type > *arg4 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg5 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; int val3 ; int ecode3 = 0 ; void *argp4 = 0 ; int res4 = 0 ; void *argp5 = 0 ; int res5 = 0 ; PyObject *swig_obj[5] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"TST_close_match",5,5,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_close_match" "', argument " "1"" of type '" "TST const *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "TST_close_match" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); res4 = SWIG_ConvertPtr(swig_obj[3], &argp4,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "TST_close_match" "', argument " "4"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg4 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp4); res5 = SWIG_ConvertPtr(swig_obj[4], &argp5,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res5)) { SWIG_exception_fail(SWIG_ArgError(res5), "in method '" "TST_close_match" "', argument " "5"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg5 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp5); { try { result = ((TST const *)arg1)->close_match((string_type const &)*arg2,arg3,arg4,arg5); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST_match(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; tst_filter< char,PythonReference,string_type > *arg3 = (tst_filter< char,PythonReference,string_type > *) 0 ; tst_action< char,PythonReference,string_type > *arg4 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp3 = 0 ; int res3 = 0 ; void *argp4 = 0 ; int res4 = 0 ; PyObject *swig_obj[4] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"TST_match",4,4,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_match" "', argument " "1"" of type '" "TST const *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } res3 = SWIG_ConvertPtr(swig_obj[2], &argp3,SWIGTYPE_p_tst_filterT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "TST_match" "', argument " "3"" of type '" "tst_filter< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_filter< char,PythonReference,string_type > * >(argp3); res4 = SWIG_ConvertPtr(swig_obj[3], &argp4,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "TST_match" "', argument " "4"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg4 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp4); { try { result = ((TST const *)arg1)->match((string_type const &)*arg2,arg3,arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST_scan(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; tst_action< char,PythonReference,string_type > *arg3 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp3 = 0 ; int res3 = 0 ; PyObject *swig_obj[3] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"TST_scan",3,3,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_scan" "', argument " "1"" of type '" "TST *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } res3 = SWIG_ConvertPtr(swig_obj[2], &argp3,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res3)) { SWIG_exception_fail(SWIG_ArgError(res3), "in method '" "TST_scan" "', argument " "3"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg3 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp3); { try { result = (arg1)->scan((string_type const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } return resultobj; fail: { delete arg2; } return NULL; } SWIGINTERN PyObject *_wrap_TST_scan_with_stop_chars(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TST *arg1 = (TST *) 0 ; string_type *arg2 = 0 ; string_type *arg3 = 0 ; tst_action< char,PythonReference,string_type > *arg4 = (tst_action< char,PythonReference,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp4 = 0 ; int res4 = 0 ; PyObject *swig_obj[4] ; PythonReference result; if (!SWIG_Python_UnpackTuple(args,"TST_scan_with_stop_chars",4,4,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TST, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TST_scan_with_stop_chars" "', argument " "1"" of type '" "TST const *""'"); } arg1 = reinterpret_cast< TST * >(argp1); { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[1],&buffer,&size); arg2 = new string_type(buffer,size); } { char* buffer; - int size; + Py_ssize_t size; PyString_AsStringAndSize(swig_obj[2],&buffer,&size); arg3 = new string_type(buffer,size); } res4 = SWIG_ConvertPtr(swig_obj[3], &argp4,SWIGTYPE_p_tst_actionT_char_PythonReference_string_type_t, 0 | 0 ); if (!SWIG_IsOK(res4)) { SWIG_exception_fail(SWIG_ArgError(res4), "in method '" "TST_scan_with_stop_chars" "', argument " "4"" of type '" "tst_action< char,PythonReference,string_type > *""'"); } arg4 = reinterpret_cast< tst_action< char,PythonReference,string_type > * >(argp4); { try { result = ((TST const *)arg1)->scan_with_stop_chars((string_type const &)*arg2,(string_type const &)*arg3,arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } { resultobj = (&result)->lend(); } { delete arg2; } { delete arg3; } return resultobj; fail: { delete arg2; } { delete arg3; } return NULL; } SWIGINTERN PyObject *TST_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_TST, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *TST_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { return SWIG_Python_InitShadowInstance(args); } SWIGINTERN PyObject *_wrap_new__lexical_iterator_type(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *) 0 ; qad_string< char > *arg2 = 0 ; int arg3 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; int val3 ; int ecode3 = 0 ; PyObject *swig_obj[3] ; lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *result = 0 ; if (!SWIG_Python_UnpackTuple(args,"new__lexical_iterator_type",3,3,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new__lexical_iterator_type" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > * >(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_qad_stringT_char_t, 0 | 0); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "new__lexical_iterator_type" "', argument " "2"" of type '" "qad_string< char > const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new__lexical_iterator_type" "', argument " "2"" of type '" "qad_string< char > const &""'"); } arg2 = reinterpret_cast< qad_string< char > * >(argp2); ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "new__lexical_iterator_type" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); { try { result = (lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *)new lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > const *)arg1,(qad_string< char > const &)*arg2,arg3); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__lexical_iterator_type_next(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type result; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_lexical_iterator_type_next" "', argument " "1"" of type '" "lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { result = (arg1)->next(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type(static_cast< const lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type& >(result))), SWIGTYPE_p_std__pairT_qad_stringT_char_t_PythonReference_p_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete__lexical_iterator_type(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete__lexical_iterator_type" "', argument " "1"" of type '" "lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_lexical_iterator_type_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_lexical_iterator_type_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { return SWIG_Python_InitShadowInstance(args); } SWIGINTERN PyObject *_wrap_new__close_match_iterator_type(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *arg1 = (tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > *) 0 ; qad_string< char > *arg2 = 0 ; int arg3 ; int arg4 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; int val3 ; int ecode3 = 0 ; int val4 ; int ecode4 = 0 ; PyObject *swig_obj[4] ; match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *result = 0 ; if (!SWIG_Python_UnpackTuple(args,"new__close_match_iterator_type",4,4,swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_tstT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new__close_match_iterator_type" "', argument " "1"" of type '" "tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > const *""'"); } arg1 = reinterpret_cast< tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > * >(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &argp2, SWIGTYPE_p_qad_stringT_char_t, 0 | 0); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "new__close_match_iterator_type" "', argument " "2"" of type '" "qad_string< char > const &""'"); } if (!argp2) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "new__close_match_iterator_type" "', argument " "2"" of type '" "qad_string< char > const &""'"); } arg2 = reinterpret_cast< qad_string< char > * >(argp2); ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); if (!SWIG_IsOK(ecode3)) { SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "new__close_match_iterator_type" "', argument " "3"" of type '" "int""'"); } arg3 = static_cast< int >(val3); ecode4 = SWIG_AsVal_int(swig_obj[3], &val4); if (!SWIG_IsOK(ecode4)) { SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "new__close_match_iterator_type" "', argument " "4"" of type '" "int""'"); } arg4 = static_cast< int >(val4); { try { result = (match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *)new match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >((tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > const *)arg1,(qad_string< char > const &)*arg2,arg3,arg4); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_NEW | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap__close_match_iterator_type_next(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type result; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "_close_match_iterator_type_next" "', argument " "1"" of type '" "match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { result = (arg1)->next(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type(static_cast< const match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > >::value_type& >(result))), SWIGTYPE_p_std__pairT_qad_stringT_char_t_PythonReference_p_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete__close_match_iterator_type(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *arg1 = (match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete__close_match_iterator_type" "', argument " "1"" of type '" "match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > *""'"); } arg1 = reinterpret_cast< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_close_match_iterator_type_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_qad_stringT_char_t_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_close_match_iterator_type_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { return SWIG_Python_InitShadowInstance(args); } SWIGINTERN PyObject *_wrap_TSTLexicalIterator___iter__(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *arg1 = (TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; SwigValueWrapper< TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > > result; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TSTLexicalIterator___iter__" "', argument " "1"" of type '" "TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *""'"); } arg1 = reinterpret_cast< TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > * >(argp1); { try { result = (arg1)->__iter__(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > >(static_cast< const TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > >& >(result))), SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_TSTLexicalIterator_next(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *arg1 = (TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; PyObject *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TSTLexicalIterator_next" "', argument " "1"" of type '" "TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *""'"); } arg1 = reinterpret_cast< TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > * >(argp1); { try { result = (PyObject *)(arg1)->next(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = result; return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_delete_TSTLexicalIterator(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *arg1 = (TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_POINTER_DISOWN | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_TSTLexicalIterator" "', argument " "1"" of type '" "TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *""'"); } arg1 = reinterpret_cast< TSTIterator< lexical_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > * >(argp1); { try { delete arg1; } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_Py_Void(); return resultobj; fail: return NULL; } SWIGINTERN PyObject *TSTLexicalIterator_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *obj; if (!SWIG_Python_UnpackTuple(args,(char*)"swigregister", 1, 1,&obj)) return NULL; SWIG_TypeNewClientData(SWIGTYPE_p_TSTIteratorT_lexical_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_NewClientData(obj)); return SWIG_Py_Void(); } SWIGINTERN PyObject *_wrap_TSTCloseMatchIterator___iter__(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *arg1 = (TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; SwigValueWrapper< TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,qad_string< char > > > > result; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TSTCloseMatchIterator___iter__" "', argument " "1"" of type '" "TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *""'"); } arg1 = reinterpret_cast< TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > * >(argp1); { try { result = (arg1)->__iter__(); } catch (TSTException &e) { PyErr_SetString(PyExc_RuntimeError,e.what()); SWIG_fail; } catch (PythonException &e) { if(!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError,e.what()); } SWIG_fail; } } resultobj = SWIG_NewPointerObj((new TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > >(static_cast< const TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > >& >(result))), SWIGTYPE_p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, SWIG_POINTER_OWN | 0 ); return resultobj; fail: return NULL; } SWIGINTERN PyObject *_wrap_TSTCloseMatchIterator_next(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *arg1 = (TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *) 0 ; void *argp1 = 0 ; int res1 = 0 ; PyObject *swig_obj[1] ; PyObject *result = 0 ; if (!args) SWIG_fail; swig_obj[0] = args; res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_TSTIteratorT_match_iteratorT_char_PythonReference_memory_storageT_char_PythonReference_t_ObjectSerializer_string_type_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "TSTCloseMatchIterator_next" "', argument " "1"" of type '" "TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > *""'"); } arg1 = reinterpret_cast< TSTIterator< match_iterator< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type > > * >(argp1); { try {
nlehuen/pytst
00b63dc1aa109948fc3274f6607427c06fae7714
This is a test commit to help figure out if I am using git correctly. As it happens, I am actually interested in finding out where this tcc module lives so that I can run the tests.
diff --git a/python/test/test.py b/python/test/test.py index 03d3022..fd6dcc2 100644 --- a/python/test/test.py +++ b/python/test/test.py @@ -1,532 +1,533 @@ # -*- coding: iso-8859-1 -*- import sys # sys.path.insert(0,r"D:\projets\tst\python\Debug") import unittest import os import random import string import datetime from time import time from itertools import izip from tst import * random.seed(0) def random_string(length): return ''.join([random.choice(string.letters) for x in xrange(length)]) +# Where does tcc live? from tcc.timer import Timer from tcc.util import levenshtein timers = {} def timer_start(name): timers.setdefault(name,Timer()).start() def timer_end(name,normalize=1.0): timers.setdefault(name,Timer()).stop(normalize) def print_timers(comment): keys = timers.keys() keys.sort() for name in keys: print '%16s : %s'%(name,timers[name]) statsfilename = os.path.join(os.path.dirname(__file__),'stats.csv') if os.path.isfile(statsfilename): statsfile = file(statsfilename,'ab') else: statsfile = file(statsfilename,'wb') header = [ 'date', 'version', 'comment' ] for key in keys: header.append('%s:min'%key) header.append('%s:med'%key) header.append('%s:avg'%key) header.append('%s:max'%key) statsfile.write(';'.join(header)) statsfile.write('\n') row = [ datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S'), TST_VERSION, comment, ] for key in keys: timer = timers[key] row.append(('%7.4f'%timer.min).replace('.',',')) row.append(('%7.4f'%timer.med).replace('.',',')) row.append(('%7.4f'%timer.avg).replace('.',',')) row.append(('%7.4f'%timer.max).replace('.',',')) statsfile.write(';'.join(row)) statsfile.write('\n') class TestRefCount(unittest.TestCase): def setUp(self): self.a = 'toto' self.rc_a = sys.getrefcount(self.a) self.rc_None = sys.getrefcount(None) self.tree=TST() def testSetup(self): self.assertEqual(sys.getrefcount(None),self.rc_None+17) self.assertEqual(sys.getrefcount(self.a),self.rc_a) def testStore(self): self.tree[self.a]=self.a self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) def testOverwrite(self): self.tree[self.a]=self.a a2 = self.tree.put(self.a,'coucou') self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) del(a2) self.assertEqual(sys.getrefcount(self.a),self.rc_a) def testWalkList(self): l=self.tree.walk(None,ListAction()) self.assertEqual(sys.getrefcount(self.a),self.rc_a) self.tree[self.a]=self.a self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) l=self.tree.walk(None,ListAction()) self.assertEqual(sys.getrefcount(self.a),self.rc_a+2) del(l) self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) def testWalkDict(self): self.tree[self.a]=self.a self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) d=self.tree.walk(None,DictAction()) self.assertEqual(sys.getrefcount(self.a),self.rc_a+2) del(d) self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) del self.tree[self.a] self.assertEqual(sys.getrefcount(self.a),self.rc_a) def testRemove(self): del(self.tree) self.assertEqual(sys.getrefcount(None),self.rc_None) self.assertEqual(sys.getrefcount(self.a),self.rc_a) class TestCollectors(unittest.TestCase): def setUp(self): self.tree = TST() self.keys = dict( a = 1, ab = 2, abc = 3, b = 4 ) for k,v in self.keys.iteritems(): self.tree[k] = v def testListAction(self): l = self.tree.walk(None,ListAction()) self.assertEqual(l,[1,2,3,4]) def testTupleListAction(self): l = self.tree.walk(None,TupleListAction()) self.assertEqual(l,[('a',0,1),('ab',0,2),('abc',0,3),('b',0,4)]) def testDictAction(self): l = self.tree.walk(None,DictAction()) self.assertEqual(l,dict(a=(0,1),ab=(0,2),abc=(0,3),b=(0,4))) def skey(): format = '%%.%if'%random.randint(1,10) return format%random.random() class TestBasics(unittest.TestCase): def setUp(self): self.tree = TST() self.keys = dict([ (skey(),random.random()) for x in xrange(250) ]) for k,v in self.keys.iteritems(): self.tree[k] = v def testGet(self): for k,v in self.keys.iteritems(): self.assertEqual(self.tree[k],v) def testWithRemove(self): for k in random.sample(self.keys,len(self.keys)/8): del self.keys[k] del self.tree[k] self.tree.pack() self.testGet() def testWithUpdate(self): for k in random.sample(self.keys,len(self.keys)/8): v = self.keys[k] nv = random.random() self.keys[k] = nv self.assertEqual(self.tree.put(k,nv),v) self.testGet() def testWalk(self): timer_start("walk") for i in xrange(100): d = self.tree.walk(None,DictAction()) timer_end("walk") for k,v in d.iteritems(): self.assertEquals(self.tree[k],v[1]) def testWalkWithRoot(self): ref = self.tree.walk(None,DictAction()) timer_start("walk_root") for i in xrange(100): d = self.tree.walk(None,DictAction(),'0.1') timer_end("walk_root") for k, v in ref.iteritems(): if k.startswith('0.1'): self.assert_(k in d) self.assertEquals(v,d[k]) for k, v in d.iteritems(): self.assert_(k.startswith('0.1')) self.assertEquals(self.tree[k],v[1]) def testCloseMatch(self): for k1 in self.keys.iterkeys(): timer_start("close_match") d = self.tree.close_match(k1,4,None,DictAction()) timer_end("close_match") for k2 in self.keys.iterkeys(): distance = levenshtein(k1,k2) if distance<=4: self.assert_(k2 in d,"Match manquant pour %s : %s (distance = %i)"%( k1, k2, distance, )) self.assert_(k2 in d and d[k2][0]==distance,"Mauvaise distance pour %s et %s : %i != %s"%( k1, k2, distance, d.get(k2)[0] )) else: self.assert_(k2 not in d,"Mauvaise distance pour %s et %s : %i > 4 mais trouvé %s"%( k1, k2, distance, d.get(k2) )) def testPrefixMatch(self): for k1 in self.keys.iterkeys(): timer_start("prefix_match") d = self.tree.prefix_match(k1[:len(k1)/2],None,DictAction()) timer_end("prefix_match") self.assert_(k1 in d,"Une cle manque dans un prefix_match pour %s"%(k1,)) k2 = k1 + k1 timer_start("prefix_match") d = self.tree.prefix_match(k2,None,DictAction()) timer_end("prefix_match") self.assert_(k2 not in d,"Une cle manque dans un prefix_match pour %s"%(k1,)) def testWriteRead(self): self.tree.write_to_file('test.tst') self.tree = TST() self.tree.read_from_file('test.tst') self.testGet() class TestMatch(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['abc'] = 'abc' self.tree['ab'] = 'ab' self.tree['a'] = 'a' self.tree['bbc'] = 'bbc' self.tree['efgfjhny'] = 'ok' def testJoker1(self): d = self.tree.match("a?c",None,DictAction()) self.assertEquals(d,dict(abc=(0,"abc"))) def testJoker2(self): d = self.tree.match("???",None,DictAction()) self.assertEquals(d,{'abc': (0, 'abc'), 'bbc': (0, 'bbc')}) def testJoker3(self): d = self.tree.match("??",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab')}) def testStar1(self): d = self.tree.match("a*c",None,DictAction()) self.assertEquals(d,dict(abc=(0,"abc"))) def testStar2(self): d = self.tree.match("a*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'abc': (0, 'abc')}) def testStar2_1(self): d = self.tree.match("ab*",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab'), 'abc': (0, 'abc')}) def testStar2_2(self): d = self.tree.match("*b",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab')}) d = self.tree.match("*bbc",None,DictAction()) self.assertEquals(d,{'bbc': (0, 'bbc')}) def testStar3(self): d = self.tree.match("*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) d = self.tree.match("*?*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) def testStar3_1(self): d = self.tree.match("**",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) d = self.tree.match("***",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) def testStar4(self): d = self.tree.match("e*ny",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar5(self): d = self.tree.match("*****y",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar6(self): d = self.tree.match("????*",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar7(self): d = self.tree.match("ef?f*n?",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) class TestIterators(unittest.TestCase): def setUp(self): self.tree = TST() self.keys = dict( titi = 1, toto = 2, tati = 3, a = 5 ) for k, v in self.keys.iteritems(): self.tree[k] = v def testLexical1(self): d = {} for k, v in self.tree: d[k] = v self.assertEqual(d,self.keys) def testLexical2(self): d = {} for k, v in self.tree.iterator('t'): d[k] = v self.keys.pop('a') self.assertEqual(d,self.keys) def testCloseMatch(self): d = {} for k, v in self.tree.close_match_iterator('t',1): d[k] = v self.assertEqual(d,dict( a = 5 )) d = {} for k, v in self.tree.close_match_iterator('tito',1): d[k] = v self.assertEqual(d,dict( titi = 1, toto = 2 )) d = {} for k, v in self.tree.close_match_iterator('tuto',1): d[k] = v self.assertEqual(d,dict( toto = 2 )) class TestCallableAction(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['foo'] = 'bar' def testCA1(self): res = {} def callback(key, length, obj): res[key] = obj def result(): res['hello'] = 'world' return res self.assertEqual( self.tree.walk(None, CallableAction(callback, result)), {'foo':'bar', 'hello':'world'} ) def testCA2(self): res = {} def callback(key, length, obj): # Provoke an exception print 0 / 0 res[key] = obj def result(): return res try: self.tree.walk(None, CallableAction(callback, result)), self.fail("Should have raised an exception") except ZeroDivisionError: pass def testCA3(self): res = {} def callback(key, length, obj): res[key] = obj def result(): # Provoke an exception return 0/0 try: self.tree.walk(None, CallableAction(callback, result)), self.fail("Should have raised an exception") except ZeroDivisionError: pass class TestCallableFilter(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['foo'] = 'bar' self.tree['bar'] = 'foo' def testCF1(self): res = {} def cfilter(key, length, obj): res[key] = obj return obj self.tree.walk(CallableFilter(cfilter),None) self.assertEqual( res, {'foo':'bar', 'bar':'foo'} ) def testCF2(self): def cfilter(key, length, obj): if key=='foo': return 'boo' else: return obj self.assertEqual( self.tree.walk(CallableFilter(cfilter),DictAction()), {'foo':(0,'boo'),'bar':(0,'foo')} ) def testCF3(self): def cfilter(key, length, obj): if key=='foo': # raises an exception return 0 / 0 else: return obj try: self.tree.walk(CallableFilter(cfilter),DictAction()), self.fail("Should have raised an exception") except ZeroDivisionError: pass class TestHighCapacity(unittest.TestCase): def setUp(self): tree = TST() timer_start('build_big') keys = map(str,xrange(100000)) random.shuffle(keys) timer_end('build_big') timer_start('write_big') for k in keys: tree[k] = k timer_end('write_big') self.keys, self.tree = keys, tree def testGet(self): timer_start('read_big') for k in self.keys: self.assertEqual(self.tree[k],k) timer_end('read_big') def testFullPack(self): timer_start('delete_full') for k in self.keys: del self.tree[k] timer_end('delete_full') self.tree.pack() for k in self.keys: self.assertEqual(self.tree[k],None) sample = random.sample(self.keys,len(self.keys)/10) random.shuffle(sample) timer_start('refill_post_pack/10') for k in sample: self.tree[k] = k timer_end('refill_post_pack/10',10) for k in sample: self.assertEqual(self.tree[k],k) del self.tree[k] self.tree.pack() for k in self.keys: self.assertEqual(self.tree[k],None) self.tree.write_to_file('test.tst') def testDelete(self): sample = random.sample(self.keys,len(self.keys)/10) random.shuffle(sample) timer_start('delete_big/10') for k in sample: del self.tree[k] timer_end('delete_big/10',10) random.shuffle(sample) timer_start('refill_pre_pack/10') for k in sample: self.tree[k] = k timer_end('refill_pre_pack/10',10) self.testGet() random.shuffle(sample) timer_start('delete_big/10') for k in sample: del self.tree[k] timer_end('delete_big/10',10)
nlehuen/pytst
5829a4f19d07b18d74794a5f4963d4848e4d8159
Removed the gymnastic about include copying etc.
diff --git a/python/build-all-versions.bat b/python/build-all-versions.bat index 3be608e..cf0a612 100644 --- a/python/build-all-versions.bat +++ b/python/build-all-versions.bat @@ -1,10 +1,5 @@ -rmdir /s /q build include -mkdir include & xcopy ..\include include -copy ..\include\LICENSE . -swig -O -Iinclude -DSCANNER -c++ -python tst.i -del MANIFEST +swig -O -I../include -DSCANNER -c++ -python tst.i for %%p in (23 24 25 26) do ( c:\python%%p\python.exe setup.py clean build --compile=mingw32 sdist bdist_wininst rmdir /s /q build ) -rmdir /s /q include diff --git a/python/build.bat b/python/build.bat index acb8dbb..25875d4 100644 --- a/python/build.bat +++ b/python/build.bat @@ -1,7 +1,4 @@ -rmdir /s /q build include -mkdir include & xcopy ..\include include -copy ..\include\LICENSE . -swig -O -Iinclude -DSCANNER -c++ -python tst.i -del MANIFEST +rmdir /s /q build +swig -O -I../include -DSCANNER -c++ -python tst.i python setup.py clean sdist bdist_wininst -rmdir /s /q build include +rmdir /s /q build diff --git a/python/setup.py b/python/setup.py index 1171f6e..e76e03e 100644 --- a/python/setup.py +++ b/python/setup.py @@ -1,49 +1,49 @@ # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from distutils.core import setup, Extension import sys extra_compile_args = [] setup( name = "pytst", version = "1.16", author = "Nicolas Lehuen", author_email = "nicolas@lehuen.com", url = "http://nicolas.lehuen.com/index.php/category/Pytst", description = "An implementation of a Ternary Search Tree (TST) in C++ with Python bindings", py_modules = ["tst"], ext_modules = [ Extension( "_tst", ["tst_wrap.cxx"], - include_dirs=['include'], + include_dirs=['../include'], extra_compile_args = extra_compile_args, define_macros=[('SCANNER', None),], ) ], download_url = "http://nicolas.lehuen.com/download/pytst/", classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: C++', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Scientific/Engineering :: Information Analysis', ] )
nlehuen/pytst
48345b62fb1665817302d15f5060472d91dc1f87
Line endings conversion
diff --git a/python/build-python-libs.bat b/python/build-python-libs.bat index ba9abc4..6e335de 100644 --- a/python/build-python-libs.bat +++ b/python/build-python-libs.bat @@ -1,7 +1,7 @@ -rem See http://www.redmountainsw.com/wordpress/archives/building-python-extensions-with-activepython-25-and-visual-studio-2005 -for %%p in (23 24 25 26) do ( - pexports c:\\windows\\system32\\python%%p.dll > python%%p.def - dlltool --dllname python%%p.dll --def python%%p.def --output-lib libpython%%p.a - del python%%p.def - move libpython%%p.a c:\python%%p\libs -) +rem See http://www.redmountainsw.com/wordpress/archives/building-python-extensions-with-activepython-25-and-visual-studio-2005 +for %%p in (23 24 25 26) do ( + pexports c:\\windows\\system32\\python%%p.dll > python%%p.def + dlltool --dllname python%%p.dll --def python%%p.def --output-lib libpython%%p.a + del python%%p.def + move libpython%%p.a c:\python%%p\libs +) diff --git a/python/compacttst.py b/python/compacttst.py index 0693b8e..c42e0f4 100644 --- a/python/compacttst.py +++ b/python/compacttst.py @@ -1,765 +1,765 @@ -# -*- coding: iso-8859-1 -*- -from array import array -import sys - -# Tant qu'à faire vu qu'ici le nombre de caractères par noeud est complètement -# dynamique, on peut se lâcher, mettre 1024 caractère ou plus -CHARS_PER_NODE = 1024 - -class tst_node(object): - """ classe représentant un noeud du TST """ - - # __slots__ est une optimisation permettant de créer des objets Python - # non dynamiques, ce qui utilise moins de mémoire - __slots__ = ['chars','data','next','left','right'] - - instances = 0 - - def __init__(self): - tst_node.instances += 1 - self.chars = array('c') - self.data = None - self.next = None - self.left = None - self.right = None - - def __repr__(self): - return "node(%s,data=%s,%i,%i,%i)"%( - self.chars, - self.data, - self.left is not None and 1 or 0, - self.next is not None and 1 or 0, - self.right is not None and 1 or 0, - ) - -class balance_info(object): - __slots__ = ['did_balance','height','balance','right_balance','left_balance'] - - def __init__(self,did_balance=False,height=0,balance=0,right_balance=0,left_balance=0): - self.did_balance = did_balance - self.height = height - self.balance = balance - self.right_balance = right_balance - self.left_balance = left_balance - - def __repr__(self): - return "balance_info(d=%s,h=%s,b=%s,l=%s,r=%s)"%( - self.did_balance, - self.height, - self.balance, - self.left_balance, - self.right_balance - ) - -class compact_tst(object): - """ Implémentation d'un TST compact """ - - def __init__(self): - self.root = None - - def __getitem__(self,string): - """ Lit dans l'arbre selon la syntaxe tst[string] """ - - # ATTENTION : ce code est intentionnellement dupliqué dans la méthode - # visit(). Ne pas oublier de mettre celle-ci à jour lorsqu'il est modifié - # ici. - - node = self.root - index = 0 - while node is not None: - local_index = 0 - - # On avance tant qu'il y a égalité - diff = 0 - while local_index < len(node.chars) and index < len(string): - diff = cmp(string[index],node.chars[local_index]) - if diff == 0: - local_index += 1 - index += 1 - else: - break - - if diff != 0: - # On a une différence de caractère - - if local_index < len(node.chars) - 1: - # on s'est arrêté avant le dernier caractère du noeud, - # il n'y a donc pas de match possible (sinon il y aurait eu - # split à l'insertion) - return None - elif diff>0: - node = node.left - else: # diff<0 - node = node.right - - elif local_index == len(node.chars): - # On est au bout des caractères du noeud - - if index == len(string): - # On est également au bout de la clé - # C'est qu'on a de la chance ! - return node.data - else: - # On avance d'un cran - node = node.next - - else: - # On n'est pas au bout des caractères, c'est qu'on est au - # bout de la clé, et donc qu'il n'y a pas de match, sinon - # il y aurait eu un split - assert index == len(string) - return None - - # node is None ==> pas de match - return None - - - def __setitem__(self,string,value): - """ Ecrit dans l'arbre selon la syntaxe tst[string] = value """ - self.root, discard = self._insert(string,value,0,self.root) - assert self[string] == value - - def _insert(self,string,value,index,node): - if node is None: - return self._new_node(string,value,index) - - local_index = 0 - - # On avance tant qu'il y a égalité - diff = 0 - while local_index < len(node.chars) and index<len(string): - diff = cmp(string[index],node.chars[local_index]) - if diff == 0: - local_index += 1 - index += 1 - else: - break - - if diff!=0: - assert local_index < len(node.chars) and index<len(string) - - # On a trouvé un point de divergence avant le dernier caractère du - # noeud, et de la clé, il va donc falloir splitter - if local_index < len(node.chars) - 1: - node, balance = self._split_node(node,local_index) - # On peut essayer de joindre le noeud suivant au noeud d'après - # car le split peut permettre de compléter un noeud pas totalement - # remplit - node.next, discard = self._compact_node(node.next,None) - - # Maintenant que le split est fait, on peut continuer à positionner - # la nouvelle clé - balance = balance_info() - if diff>0: - node.left, left_balance = self._insert(string,value,index,node.left) - balance.did_balance = left_balance.did_balance - right_balance = self._compute_balance(node.right) - else: - node.right, right_balance = self._insert(string,value,index,node.right) - balance.did_balance = right_balance.did_balance - left_balance = self._compute_balance(node.left) - - # On calcule la nouvelle balance en tenant compte des modifs - if len(node.chars)>1: - balance.height = 1 - else: - balance.height = max(left_balance.height, right_balance.height) + 1 - balance.balance = left_balance.height - right_balance.height - balance.left_balance = left_balance.balance - balance.right_balance = right_balance.balance - - if not balance.did_balance: - # On effectue la balance si elle n'a pas déjà été effectuée - node, balance = self._balance(node,balance) - - if len(node.chars)!=1: - # Si à l'issue de la balance on se retrouve avec plusieurs - # caractères, alors la hauteur du nouveau noeud est 1. - balance.height = 1 - balance.balance = 0 - balance.left_balance = 0 - balance.right_balance = 0 - - return node, balance - - elif local_index == len(node.chars): - # On est arrivé au bout des caractères du noeud - # sans différence - - if index == len(string): - # On est également au bout de la clé - # C'est qu'on a de la chance ! - node.data = value - else: - # On n'est pas au bout de la clé - node.next, next_balance = self._insert(string,value,index,node.next) - - # Suite à un split du noeud suivant, il est peut-être possible - # de le recoller à ce noeud ? - node, discard = self._compact_node(node, None) - - return node, self._compute_balance(node) - - else: - # On est arrivé au bout de la clé, mais pas au bout des caractères - # du noeud - assert index == len(string) - - # On est au bout de la clé, mais avant la fin des caractères du - # noeud ; il faut donc splitter, mais au local_index précédent car - # on a bêtement avancé les deux à la fois aux lignes 105 - 106 - node, balance = self._split_node(node,local_index-1) - - # On peut essayer de joindre le noeud suivant au noeud d'après - node.next, discard = self._compact_node(node.next,None) - - # On stocke ensuite la clé et la valeur - node.data = value - - return node, balance - - def __delitem__(self,string): - self.root, discard = self._remove(string,0,self.root) - - def _remove(self,string,index,node): - if node is None: - return None - - local_index = 0 - - # On avance tant qu'il y a égalité - diff = 0 - while local_index < len(node.chars) and index<len(string): - diff = cmp(string[index],node.chars[local_index]) - if diff == 0: - local_index += 1 - index += 1 - else: - break - - if diff!=0: - assert local_index < len(node.chars) and index<len(string) - - # On a trouvé un point de divergence avant le dernier caractère du - # noeud, et de la clé, il va donc falloir splitter - if local_index < len(node.chars) - 1: - return node, self._compute_balance(node) - - # Maintenant que le split est fait, on peut continuer à positionner - # la nouvelle clé - balance = balance_info() - if diff>0: - node.left, left_balance = self._remove(string,index,node.left) - balance.did_balance = left_balance.did_balance - node, balance = self._compact_node(node,balance,True) - right_balance = self._compute_balance(node.right) - else: - node.right, right_balance = self._remove(string,index,node.right) - balance.did_balance = right_balance.did_balance - node, balance = self._compact_node(node,balance,True) - left_balance = self._compute_balance(node.left) - - # On calcule la nouvelle balance en tenant compte des modifs - if len(node.chars)>1: - balance.height = 1 - else: - balance.height = max(left_balance.height, right_balance.height) + 1 - balance.balance = left_balance.height - right_balance.height - balance.left_balance = left_balance.balance - balance.right_balance = right_balance.balance - - if not balance.did_balance: - # On effectue la balance si elle n'a pas déjà été effectuée - node, balance = self._balance(node,balance) - - if len(node.chars)!=1: - # Si à l'issue de la balance on se retrouve avec plusieurs - # caractères, alors la hauteur du nouveau noeud est 1. - balance.height = 1 - balance.balance = 0 - balance.left_balance = 0 - balance.right_balance = 0 - - # return self._compact_node(node,balance) - return node, balance - - elif local_index == len(node.chars): - # On est arrivé au bout des caractères du noeud - # sans différence - - if index == len(string): - # On est également au bout de la clé - # C'est qu'on a de la chance ! - node.data = None - else: - # On n'est pas au bout de la clé - node.next, next_balance = self._remove(string,index,node.next) - - # Suite à un split du noeud suivant, il est peut-être possible - # de le recoller à ce noeud ? - # node, discard = self._compact_node(node, None) - - return self._compact_node(node,self._compute_balance(node)) - - else: - # On est arrivé au bout de la clé, mais pas au bout des caractères - # du noeud - assert index == len(string) - - # On est au bout de la clé, mais avant la fin des caractères du - # noeud - - return node, balance - - def _compute_balance(self,node): - - if node is not None: - if len(node.chars)>1: - # La hauteur d'un noeud contenant plusieurs caractères - # est forcément 1 - return balance_info(height=1) - else: - balance = balance_info() - - # Récursion sur les noeuds fils - left_balance = self._compute_balance(node.left) - right_balance = self._compute_balance(node.right) - - balance.did_balance = False - balance.height = max(left_balance.height, right_balance.height) + 1 - balance.balance = left_balance.height - right_balance.height - balance.left_balance = left_balance.balance - balance.right_balance = right_balance.balance - - return balance - else: - # La hauteur d'un noeud non existant est 0, ce qui fait - # que la hauteur d'une feuille est 1 - return balance_info() - - def _balance(self,node,balance): - assert balance.height == self._compute_balance(node).height, (node, balance, self._compute_balance(node)) - assert len(node.chars)>1 or balance.balance == self._compute_balance(node).balance, "%s : %s != %s"%(node,balance,self._compute_balance(node)) - assert balance.left_balance == self._compute_balance(node.left).balance - assert balance.right_balance == self._compute_balance(node.right).balance - - assert -2 < balance.left_balance < 2 - assert -2 < balance.right_balance < 2 - assert -3 < balance.balance < 3 - - assert -2 < self._compute_balance(node.left).balance < 2 - assert -2 < self._compute_balance(node.right).balance < 2 - assert -3 < self._compute_balance(node).balance < 3 - - # Assure le critère AVL - if balance.balance > 1: - if balance.left_balance > 0: - node, balance = self._ll(node,balance) - else: - node, balance = self._lr(node,balance) - balance.did_balance = True - elif balance.balance < -1: - if balance.right_balance < 0: - node, balance = self._rr(node,balance) - else: - node, balance = self._rl(node,balance) - balance.did_balance = True - - assert -2 < self._compute_balance(node).balance < 2,(node,self._compute_balance(node)) - assert -2 < balance.balance < 2 - - return node, balance - - def _ll(self,node,balance): - # Un déséquilibre LL n'est possible qu'avec un noeud de gauche - # n'ayant qu'un caractère - assert len(node.left.chars) == 1 - - # On fait la rotation au niveau des liens - left_node = node.left - node.left = left_node.right - left_node.right = node - - # Et maintenant on ramène tous les caractères du noeud d'origine sauf son - # dernier, et on les insère au début du noeud de gauche. - # En gros si dans le noeud d'origine on a abcdefG - # et dans le noeud de gauche on a juste B - # A la fin on a dans le noeud d'origine juste G - # et dans le noeud de gauche abcdefB - new_char = node.chars.pop() - node.chars.append(left_node.chars.pop()) - left_node.chars.append(new_char) - node.chars, left_node.chars = left_node.chars, node.chars - - # Il est possible que le noeud d'origine soit concaténable avec la suite - left_node.right, discard = self._compact_node(left_node.right,None) - - # On ajuste la balance en fonction de l'opération effectuée - balance.height -= 1 - balance.balance = 0 - balance.left_balance = 0 - - # Le noeud de gauche prend la place du noeud d'origine dans l'arbre - return left_node, balance - - def _rr(self,node,balance): - assert len(node.right.chars) == 1 - - right_node = node.right - node.right = right_node.left - right_node.left = node - - new_char = node.chars.pop() - node.chars.append(right_node.chars.pop()) - right_node.chars.append(new_char) - node.chars, right_node.chars = right_node.chars, node.chars - - right_node.left, discard = self._compact_node(right_node.left,None) - - balance.height -= 1 - balance.balance = 0 - balance.right_balance = 0 - - return right_node, balance - - def _lr(self,node,balance): - if len(node.left.right.chars)>1: - node.left.right, discard = self._split_node(node.left.right,0) - node.left, discard = self._rr(node.left,balance_info()) - node, balance = self._ll(node,balance) - return node, balance - - def _rl(self,node,balance): - if len(node.right.left.chars)>1: - node.right.left, discard = self._split_node(node.right.left,0) - node.right, discard = self._ll(node.right,balance_info()) - node, balance = self._rr(node,balance) - return node, balance - - def _split_node(self,node,local_index): - """ Découpe un noeud à l'index donné """ - assert local_index < len(node.chars) - - # On crée un nouveau noeud - new_node = tst_node() - - # On prend tout le début du segment de clé du noeud y compris - # le caractère qui diffère et on les met dans le nouveau noeud - new_node.chars = node.chars[0:local_index + 1] - - # La suite de ce nouveau noeud est l'ancien noeud - new_node.next = node - - # On adapte la chaîne dans l'ancien noeud, c'est le restant de - # la chaîne après le split - node.chars = node.chars[local_index + 1:] - - return new_node, balance_info(height=1) - - def _compact_node(self,node,balance,debug=False): - """ Tente de ressouder un noeud à son noeud suivant si cela est - possible """ - if node is None: - return None, balance_info() - elif node.data is not None: - return node, balance - elif ( - node.next is not None - and node.left is None and node.right is None - and len(node.chars)+len(node.next.chars)<CHARS_PER_NODE - ): - # Les quatre conditions ci dessus sont : - # - on a un noeud suivant - # - le noeud actuel n'est pas un pivot (dans ce cas la concaténation - # serait impossible) - # - le noeud actuel ne contient pas de données (idem) - # - il y a de la place pour les caractères du noeud courant dans - # le noeud suivant - if debug: print "CAT", node, node.next, - node.chars.extend(node.next.chars) - node.next.chars = node.chars - if debug: print '=>',node.next - return node.next, self._compute_balance(node.next) - elif ( - node.next is None - and (node.left is None or node.right is None) - ): - if node.left is None and node.right is None: - if debug: print "CAT2", node, "=>", None - return None, balance_info() - else: - # On prend le noeud restant - new_node = node.left or node.right - - if len(node.chars)+len(new_node.chars) - 1 < CHARS_PER_NODE: - if debug: print "CAT3", node, new_node, - # On supprime le dernier caractère du noeud - node.chars.pop() - # On ajoute les caractères du nouveau noeud - node.chars.extend(new_node.chars) - # On met le résultat dans le nouveau noeud - new_node.chars = node.chars - if debug: print '=>',new_node - return new_node, self._compute_balance(new_node) - else: - return node, balance - else: - return node, balance - - def _new_node(self,string,value,index): - new_node = tst_node() - - # On remplit le segment du noeud avec un maximum de caractères de la clé - # en partant de l'index donné - length = min(len(string)-index,CHARS_PER_NODE) - new_node.chars.extend(string[index:index+length]) - - if index+length<len(string): - # s'il reste des caractères dans la clé après ce segment... - new_node.next, discard = self._new_node(string,value,index+length) - else: - # sinon on met la clé et la donnée dans ce noeud - new_node.data = value - - return new_node, balance_info(height=1) - - def stats(self,node,acc,depth=0): - if node == None : return - - acc['nodes'] = acc.get('nodes',0) + 1 - acc['total_chars'] = acc.get('total_chars',0) + len(node.chars) - key = ('nbchars',len(node.chars)) - - acc[key] = acc.get(key,0) + 1 - - links = ((node.left is not None and 1) or 0) + ((node.next is not None and 1) or 0) + ((node.right is not None and 1) or 0) - key = ('links',links) - acc[key] = acc.get(key,0) + 1 - - key = ('depth',depth) - acc[key] = acc.get(key,0) + 1 - - self.stats(node.left,acc,depth+1) - self.stats(node.next,acc,depth+1) - self.stats(node.right,acc,depth+1) - - return acc - - def visit(self,callback,string=None): - if string is not None: - # Ce code est copié / collé depuis _find_node(). - # C'est fait exprès, car cela évite d'avoir instanciation d'un - # tuple pour retour de valeur multiple à chaque appel de __getitem__. - - node = self.root - index = 0 - while node is not None: - local_index = 0 - - # On avance tant qu'il y a égalité - diff = 0 - while local_index < len(node.chars) and index < len(string): - diff = cmp(string[index],node.chars[local_index]) - if diff == 0: - local_index += 1 - index += 1 - else: - break - - if diff != 0: - # On a une différence de caractère - - if local_index < len(node.chars) - 1: - # on s'est arrêté avant le dernier caractère du noeud, - # il n'y a donc pas de match possible (sinon il y aurait eu - # split à l'insertion) - node = None - break - else: - # différence au dernier caractère du noeud - if diff>0: - node = node.left - elif diff<0: - node = node.right - - elif local_index == len(node.chars): - # On est au bout des caractères du noeud - - if index == len(string): - # On est également au bout de la clé - # C'est qu'on a de la chance ! - break - else: - # On avance d'un cran - node = node.next - - else: - # On n'est pas au bout des caractères, c'est qu'on est au - # bout de la clé, et donc qu'il n'y a pas de match, sinon - # il y aurait eu un split - assert index == len(string) - # On retourne le noeud quand même car il va être utile pour - # le visiteur, simplement il n'y a aucune donnée dedans - break - - if node is None: - return False - else: - key = string[:len(string)-local_index] - return self._visit(node,array('c',key),callback,local_index<len(node.chars)) - else: - return self._visit(self.root,array('c'),callback,True) - - def _visit(self,node,string,callback,visit_left_right): - if node is None: - return False - - # D'abord à droite pour obtenir un ordre lexicographique - if visit_left_right and self._visit(node.right,string+node.chars[:-1],callback,True): - return True - - # Maintenant le noeud en cours - if node.data is not None and callback(string+node.chars,node.data): - return True - - # Puis le noeud suivant - if self._visit(node.next,string+node.chars,callback,True): - return True - - # Puis à gauche - if visit_left_right and self._visit(node.left,string+node.chars[:-1],callback,True): - return True - - return False - - def cat(self,node,debug=False): - """ Méthode forçant la concaténation des noeuds, inutile sauf en cas de bug. """ - if node == None : return - node.left = self.cat(node.left,debug) - node.next = self.cat(node.next,debug) - node.right = self.cat(node.right,debug) - node, discard = self._compact_node(node,None,debug) - return node - - def debug(self,node,indentation=0): - print node.chars,node.data - if node.left is not None: - print ' '*(indentation+1),'LEFT', - self.debug(node.left,indentation+1) - if node.next is not None: - print ' '*(indentation+1),'NEXT', - self.debug(node.next,indentation+1) - if node.right is not None: - print ' '*(indentation+1),'RIGHT', - self.debug(node.right,indentation+1) - -if __name__ == '__main__': - urls = compact_tst() - - def callback(key,value): - assert urls[key] == value, "%s : %s != %s"%(key,urls[key],value) - print key, value - return False - - QUANTITY = 1000 - 1 - - n = 0 - try: - chars = 0 - for n, l in enumerate(file('url_1000000.csv','rb')): - if n == QUANTITY: break - if n%1000==0 : print n - key = l.rstrip() - chars += len(key) - urls[key] = 0 - finally: - stats = {} - urls.stats(urls.root,stats) - print n+1, "lignes", chars, "caracteres" - for key in sorted(stats.keys()): - print "%16s\t%6i\t%6.2f%%"%( - key, - stats[key], - (key=='total_chars' and 100.0 * stats[key] / chars) or (100.0 * stats[key] / stats['nodes']) - ) - - urls.root = urls.cat(urls.root,True) - - # On recalcule les stats après concaténation forcée des noeuds. - # Si qqchose a changé c'est un bug ! - stats = {} - urls.stats(urls.root,stats) - print n+1, "lignes", chars, "caracteres" - for key in sorted(stats.keys()): - print "%16s\t%6i\t%6.2f%%"%( - key, - stats[key], - (key=='total_chars' and 100.0 * stats[key] / chars) or (100.0 * stats[key] / stats['nodes']) - ) - - for n, l in enumerate(file('url_1000000.csv','rb')): - if n == QUANTITY: break - if n%1000==0 : print 'Delete ',n - key = l.rstrip() - if n%2 == 0 : del urls[key] - - urls.root = urls.cat(urls.root,True) - - for n, l in enumerate(file('url_1000000.csv','rb')): - if n == QUANTITY: break - if n%1000==0 : print 'Check ',n - key = l.rstrip() - if n%2==1: - assert urls[key] == 0 - else: - assert urls[key] is None - - # On recalcule les stats après concaténation forcée des noeuds. - # Si qqchose a changé c'est un bug ! - stats = {} - urls.stats(urls.root,stats) - print n+1, "lignes", chars, "caracteres" - for key in sorted(stats.keys()): - print "%16s\t%6i\t%6.2f%%"%( - key, - stats[key], - (key=='total_chars' and 100.0 * stats[key] / chars) or (100.0 * stats[key] / stats['nodes']) - ) - - t = compact_tst() - t['nicolas'] = 'nicolas' - t['laurent'] = 'laurent' - t['nicolas lehuen'] = 'nicolas lehuen' - t['laurent querel'] = 'laurent querel' - assert 'nicolas' == t['nicolas'] - assert 'nicolas lehuen' == t['nicolas lehuen'] - assert 'laurent' == t['laurent'] - assert 'laurent querel' == t['laurent querel'] - - import random - - t = compact_tst() - - data = range(1000) - seed = random.randint(-5000000,5000000) - print 'Seed is ',seed - seed = 654 - random.Random(seed).shuffle(data) - - for i, d in enumerate(data): - if i%100==0: print i - t[str(d)] = d - for i2, d2 in enumerate(data[:i]): - assert t[str(d2)] == d2 - - for i, d in enumerate(data): - if i%100==0: print i - if i%3==0: del t[str(d)] - - t.root = t.cat(t.root,True) - - for i,d in enumerate(data): - if i%3==0 : - assert t[str(d)] == None, "%s => %s != %s"%(d,None,t[str(d)]) - else: - assert t[str(d)] == d, "%s => %s != %s"%(d,i,t[str(d)]) +# -*- coding: iso-8859-1 -*- +from array import array +import sys + +# Tant qu'à faire vu qu'ici le nombre de caractères par noeud est complètement +# dynamique, on peut se lâcher, mettre 1024 caractère ou plus +CHARS_PER_NODE = 1024 + +class tst_node(object): + """ classe représentant un noeud du TST """ + + # __slots__ est une optimisation permettant de créer des objets Python + # non dynamiques, ce qui utilise moins de mémoire + __slots__ = ['chars','data','next','left','right'] + + instances = 0 + + def __init__(self): + tst_node.instances += 1 + self.chars = array('c') + self.data = None + self.next = None + self.left = None + self.right = None + + def __repr__(self): + return "node(%s,data=%s,%i,%i,%i)"%( + self.chars, + self.data, + self.left is not None and 1 or 0, + self.next is not None and 1 or 0, + self.right is not None and 1 or 0, + ) + +class balance_info(object): + __slots__ = ['did_balance','height','balance','right_balance','left_balance'] + + def __init__(self,did_balance=False,height=0,balance=0,right_balance=0,left_balance=0): + self.did_balance = did_balance + self.height = height + self.balance = balance + self.right_balance = right_balance + self.left_balance = left_balance + + def __repr__(self): + return "balance_info(d=%s,h=%s,b=%s,l=%s,r=%s)"%( + self.did_balance, + self.height, + self.balance, + self.left_balance, + self.right_balance + ) + +class compact_tst(object): + """ Implémentation d'un TST compact """ + + def __init__(self): + self.root = None + + def __getitem__(self,string): + """ Lit dans l'arbre selon la syntaxe tst[string] """ + + # ATTENTION : ce code est intentionnellement dupliqué dans la méthode + # visit(). Ne pas oublier de mettre celle-ci à jour lorsqu'il est modifié + # ici. + + node = self.root + index = 0 + while node is not None: + local_index = 0 + + # On avance tant qu'il y a égalité + diff = 0 + while local_index < len(node.chars) and index < len(string): + diff = cmp(string[index],node.chars[local_index]) + if diff == 0: + local_index += 1 + index += 1 + else: + break + + if diff != 0: + # On a une différence de caractère + + if local_index < len(node.chars) - 1: + # on s'est arrêté avant le dernier caractère du noeud, + # il n'y a donc pas de match possible (sinon il y aurait eu + # split à l'insertion) + return None + elif diff>0: + node = node.left + else: # diff<0 + node = node.right + + elif local_index == len(node.chars): + # On est au bout des caractères du noeud + + if index == len(string): + # On est également au bout de la clé + # C'est qu'on a de la chance ! + return node.data + else: + # On avance d'un cran + node = node.next + + else: + # On n'est pas au bout des caractères, c'est qu'on est au + # bout de la clé, et donc qu'il n'y a pas de match, sinon + # il y aurait eu un split + assert index == len(string) + return None + + # node is None ==> pas de match + return None + + + def __setitem__(self,string,value): + """ Ecrit dans l'arbre selon la syntaxe tst[string] = value """ + self.root, discard = self._insert(string,value,0,self.root) + assert self[string] == value + + def _insert(self,string,value,index,node): + if node is None: + return self._new_node(string,value,index) + + local_index = 0 + + # On avance tant qu'il y a égalité + diff = 0 + while local_index < len(node.chars) and index<len(string): + diff = cmp(string[index],node.chars[local_index]) + if diff == 0: + local_index += 1 + index += 1 + else: + break + + if diff!=0: + assert local_index < len(node.chars) and index<len(string) + + # On a trouvé un point de divergence avant le dernier caractère du + # noeud, et de la clé, il va donc falloir splitter + if local_index < len(node.chars) - 1: + node, balance = self._split_node(node,local_index) + # On peut essayer de joindre le noeud suivant au noeud d'après + # car le split peut permettre de compléter un noeud pas totalement + # remplit + node.next, discard = self._compact_node(node.next,None) + + # Maintenant que le split est fait, on peut continuer à positionner + # la nouvelle clé + balance = balance_info() + if diff>0: + node.left, left_balance = self._insert(string,value,index,node.left) + balance.did_balance = left_balance.did_balance + right_balance = self._compute_balance(node.right) + else: + node.right, right_balance = self._insert(string,value,index,node.right) + balance.did_balance = right_balance.did_balance + left_balance = self._compute_balance(node.left) + + # On calcule la nouvelle balance en tenant compte des modifs + if len(node.chars)>1: + balance.height = 1 + else: + balance.height = max(left_balance.height, right_balance.height) + 1 + balance.balance = left_balance.height - right_balance.height + balance.left_balance = left_balance.balance + balance.right_balance = right_balance.balance + + if not balance.did_balance: + # On effectue la balance si elle n'a pas déjà été effectuée + node, balance = self._balance(node,balance) + + if len(node.chars)!=1: + # Si à l'issue de la balance on se retrouve avec plusieurs + # caractères, alors la hauteur du nouveau noeud est 1. + balance.height = 1 + balance.balance = 0 + balance.left_balance = 0 + balance.right_balance = 0 + + return node, balance + + elif local_index == len(node.chars): + # On est arrivé au bout des caractères du noeud + # sans différence + + if index == len(string): + # On est également au bout de la clé + # C'est qu'on a de la chance ! + node.data = value + else: + # On n'est pas au bout de la clé + node.next, next_balance = self._insert(string,value,index,node.next) + + # Suite à un split du noeud suivant, il est peut-être possible + # de le recoller à ce noeud ? + node, discard = self._compact_node(node, None) + + return node, self._compute_balance(node) + + else: + # On est arrivé au bout de la clé, mais pas au bout des caractères + # du noeud + assert index == len(string) + + # On est au bout de la clé, mais avant la fin des caractères du + # noeud ; il faut donc splitter, mais au local_index précédent car + # on a bêtement avancé les deux à la fois aux lignes 105 - 106 + node, balance = self._split_node(node,local_index-1) + + # On peut essayer de joindre le noeud suivant au noeud d'après + node.next, discard = self._compact_node(node.next,None) + + # On stocke ensuite la clé et la valeur + node.data = value + + return node, balance + + def __delitem__(self,string): + self.root, discard = self._remove(string,0,self.root) + + def _remove(self,string,index,node): + if node is None: + return None + + local_index = 0 + + # On avance tant qu'il y a égalité + diff = 0 + while local_index < len(node.chars) and index<len(string): + diff = cmp(string[index],node.chars[local_index]) + if diff == 0: + local_index += 1 + index += 1 + else: + break + + if diff!=0: + assert local_index < len(node.chars) and index<len(string) + + # On a trouvé un point de divergence avant le dernier caractère du + # noeud, et de la clé, il va donc falloir splitter + if local_index < len(node.chars) - 1: + return node, self._compute_balance(node) + + # Maintenant que le split est fait, on peut continuer à positionner + # la nouvelle clé + balance = balance_info() + if diff>0: + node.left, left_balance = self._remove(string,index,node.left) + balance.did_balance = left_balance.did_balance + node, balance = self._compact_node(node,balance,True) + right_balance = self._compute_balance(node.right) + else: + node.right, right_balance = self._remove(string,index,node.right) + balance.did_balance = right_balance.did_balance + node, balance = self._compact_node(node,balance,True) + left_balance = self._compute_balance(node.left) + + # On calcule la nouvelle balance en tenant compte des modifs + if len(node.chars)>1: + balance.height = 1 + else: + balance.height = max(left_balance.height, right_balance.height) + 1 + balance.balance = left_balance.height - right_balance.height + balance.left_balance = left_balance.balance + balance.right_balance = right_balance.balance + + if not balance.did_balance: + # On effectue la balance si elle n'a pas déjà été effectuée + node, balance = self._balance(node,balance) + + if len(node.chars)!=1: + # Si à l'issue de la balance on se retrouve avec plusieurs + # caractères, alors la hauteur du nouveau noeud est 1. + balance.height = 1 + balance.balance = 0 + balance.left_balance = 0 + balance.right_balance = 0 + + # return self._compact_node(node,balance) + return node, balance + + elif local_index == len(node.chars): + # On est arrivé au bout des caractères du noeud + # sans différence + + if index == len(string): + # On est également au bout de la clé + # C'est qu'on a de la chance ! + node.data = None + else: + # On n'est pas au bout de la clé + node.next, next_balance = self._remove(string,index,node.next) + + # Suite à un split du noeud suivant, il est peut-être possible + # de le recoller à ce noeud ? + # node, discard = self._compact_node(node, None) + + return self._compact_node(node,self._compute_balance(node)) + + else: + # On est arrivé au bout de la clé, mais pas au bout des caractères + # du noeud + assert index == len(string) + + # On est au bout de la clé, mais avant la fin des caractères du + # noeud + + return node, balance + + def _compute_balance(self,node): + + if node is not None: + if len(node.chars)>1: + # La hauteur d'un noeud contenant plusieurs caractères + # est forcément 1 + return balance_info(height=1) + else: + balance = balance_info() + + # Récursion sur les noeuds fils + left_balance = self._compute_balance(node.left) + right_balance = self._compute_balance(node.right) + + balance.did_balance = False + balance.height = max(left_balance.height, right_balance.height) + 1 + balance.balance = left_balance.height - right_balance.height + balance.left_balance = left_balance.balance + balance.right_balance = right_balance.balance + + return balance + else: + # La hauteur d'un noeud non existant est 0, ce qui fait + # que la hauteur d'une feuille est 1 + return balance_info() + + def _balance(self,node,balance): + assert balance.height == self._compute_balance(node).height, (node, balance, self._compute_balance(node)) + assert len(node.chars)>1 or balance.balance == self._compute_balance(node).balance, "%s : %s != %s"%(node,balance,self._compute_balance(node)) + assert balance.left_balance == self._compute_balance(node.left).balance + assert balance.right_balance == self._compute_balance(node.right).balance + + assert -2 < balance.left_balance < 2 + assert -2 < balance.right_balance < 2 + assert -3 < balance.balance < 3 + + assert -2 < self._compute_balance(node.left).balance < 2 + assert -2 < self._compute_balance(node.right).balance < 2 + assert -3 < self._compute_balance(node).balance < 3 + + # Assure le critère AVL + if balance.balance > 1: + if balance.left_balance > 0: + node, balance = self._ll(node,balance) + else: + node, balance = self._lr(node,balance) + balance.did_balance = True + elif balance.balance < -1: + if balance.right_balance < 0: + node, balance = self._rr(node,balance) + else: + node, balance = self._rl(node,balance) + balance.did_balance = True + + assert -2 < self._compute_balance(node).balance < 2,(node,self._compute_balance(node)) + assert -2 < balance.balance < 2 + + return node, balance + + def _ll(self,node,balance): + # Un déséquilibre LL n'est possible qu'avec un noeud de gauche + # n'ayant qu'un caractère + assert len(node.left.chars) == 1 + + # On fait la rotation au niveau des liens + left_node = node.left + node.left = left_node.right + left_node.right = node + + # Et maintenant on ramène tous les caractères du noeud d'origine sauf son + # dernier, et on les insère au début du noeud de gauche. + # En gros si dans le noeud d'origine on a abcdefG + # et dans le noeud de gauche on a juste B + # A la fin on a dans le noeud d'origine juste G + # et dans le noeud de gauche abcdefB + new_char = node.chars.pop() + node.chars.append(left_node.chars.pop()) + left_node.chars.append(new_char) + node.chars, left_node.chars = left_node.chars, node.chars + + # Il est possible que le noeud d'origine soit concaténable avec la suite + left_node.right, discard = self._compact_node(left_node.right,None) + + # On ajuste la balance en fonction de l'opération effectuée + balance.height -= 1 + balance.balance = 0 + balance.left_balance = 0 + + # Le noeud de gauche prend la place du noeud d'origine dans l'arbre + return left_node, balance + + def _rr(self,node,balance): + assert len(node.right.chars) == 1 + + right_node = node.right + node.right = right_node.left + right_node.left = node + + new_char = node.chars.pop() + node.chars.append(right_node.chars.pop()) + right_node.chars.append(new_char) + node.chars, right_node.chars = right_node.chars, node.chars + + right_node.left, discard = self._compact_node(right_node.left,None) + + balance.height -= 1 + balance.balance = 0 + balance.right_balance = 0 + + return right_node, balance + + def _lr(self,node,balance): + if len(node.left.right.chars)>1: + node.left.right, discard = self._split_node(node.left.right,0) + node.left, discard = self._rr(node.left,balance_info()) + node, balance = self._ll(node,balance) + return node, balance + + def _rl(self,node,balance): + if len(node.right.left.chars)>1: + node.right.left, discard = self._split_node(node.right.left,0) + node.right, discard = self._ll(node.right,balance_info()) + node, balance = self._rr(node,balance) + return node, balance + + def _split_node(self,node,local_index): + """ Découpe un noeud à l'index donné """ + assert local_index < len(node.chars) + + # On crée un nouveau noeud + new_node = tst_node() + + # On prend tout le début du segment de clé du noeud y compris + # le caractère qui diffère et on les met dans le nouveau noeud + new_node.chars = node.chars[0:local_index + 1] + + # La suite de ce nouveau noeud est l'ancien noeud + new_node.next = node + + # On adapte la chaîne dans l'ancien noeud, c'est le restant de + # la chaîne après le split + node.chars = node.chars[local_index + 1:] + + return new_node, balance_info(height=1) + + def _compact_node(self,node,balance,debug=False): + """ Tente de ressouder un noeud à son noeud suivant si cela est + possible """ + if node is None: + return None, balance_info() + elif node.data is not None: + return node, balance + elif ( + node.next is not None + and node.left is None and node.right is None + and len(node.chars)+len(node.next.chars)<CHARS_PER_NODE + ): + # Les quatre conditions ci dessus sont : + # - on a un noeud suivant + # - le noeud actuel n'est pas un pivot (dans ce cas la concaténation + # serait impossible) + # - le noeud actuel ne contient pas de données (idem) + # - il y a de la place pour les caractères du noeud courant dans + # le noeud suivant + if debug: print "CAT", node, node.next, + node.chars.extend(node.next.chars) + node.next.chars = node.chars + if debug: print '=>',node.next + return node.next, self._compute_balance(node.next) + elif ( + node.next is None + and (node.left is None or node.right is None) + ): + if node.left is None and node.right is None: + if debug: print "CAT2", node, "=>", None + return None, balance_info() + else: + # On prend le noeud restant + new_node = node.left or node.right + + if len(node.chars)+len(new_node.chars) - 1 < CHARS_PER_NODE: + if debug: print "CAT3", node, new_node, + # On supprime le dernier caractère du noeud + node.chars.pop() + # On ajoute les caractères du nouveau noeud + node.chars.extend(new_node.chars) + # On met le résultat dans le nouveau noeud + new_node.chars = node.chars + if debug: print '=>',new_node + return new_node, self._compute_balance(new_node) + else: + return node, balance + else: + return node, balance + + def _new_node(self,string,value,index): + new_node = tst_node() + + # On remplit le segment du noeud avec un maximum de caractères de la clé + # en partant de l'index donné + length = min(len(string)-index,CHARS_PER_NODE) + new_node.chars.extend(string[index:index+length]) + + if index+length<len(string): + # s'il reste des caractères dans la clé après ce segment... + new_node.next, discard = self._new_node(string,value,index+length) + else: + # sinon on met la clé et la donnée dans ce noeud + new_node.data = value + + return new_node, balance_info(height=1) + + def stats(self,node,acc,depth=0): + if node == None : return + + acc['nodes'] = acc.get('nodes',0) + 1 + acc['total_chars'] = acc.get('total_chars',0) + len(node.chars) + key = ('nbchars',len(node.chars)) + + acc[key] = acc.get(key,0) + 1 + + links = ((node.left is not None and 1) or 0) + ((node.next is not None and 1) or 0) + ((node.right is not None and 1) or 0) + key = ('links',links) + acc[key] = acc.get(key,0) + 1 + + key = ('depth',depth) + acc[key] = acc.get(key,0) + 1 + + self.stats(node.left,acc,depth+1) + self.stats(node.next,acc,depth+1) + self.stats(node.right,acc,depth+1) + + return acc + + def visit(self,callback,string=None): + if string is not None: + # Ce code est copié / collé depuis _find_node(). + # C'est fait exprès, car cela évite d'avoir instanciation d'un + # tuple pour retour de valeur multiple à chaque appel de __getitem__. + + node = self.root + index = 0 + while node is not None: + local_index = 0 + + # On avance tant qu'il y a égalité + diff = 0 + while local_index < len(node.chars) and index < len(string): + diff = cmp(string[index],node.chars[local_index]) + if diff == 0: + local_index += 1 + index += 1 + else: + break + + if diff != 0: + # On a une différence de caractère + + if local_index < len(node.chars) - 1: + # on s'est arrêté avant le dernier caractère du noeud, + # il n'y a donc pas de match possible (sinon il y aurait eu + # split à l'insertion) + node = None + break + else: + # différence au dernier caractère du noeud + if diff>0: + node = node.left + elif diff<0: + node = node.right + + elif local_index == len(node.chars): + # On est au bout des caractères du noeud + + if index == len(string): + # On est également au bout de la clé + # C'est qu'on a de la chance ! + break + else: + # On avance d'un cran + node = node.next + + else: + # On n'est pas au bout des caractères, c'est qu'on est au + # bout de la clé, et donc qu'il n'y a pas de match, sinon + # il y aurait eu un split + assert index == len(string) + # On retourne le noeud quand même car il va être utile pour + # le visiteur, simplement il n'y a aucune donnée dedans + break + + if node is None: + return False + else: + key = string[:len(string)-local_index] + return self._visit(node,array('c',key),callback,local_index<len(node.chars)) + else: + return self._visit(self.root,array('c'),callback,True) + + def _visit(self,node,string,callback,visit_left_right): + if node is None: + return False + + # D'abord à droite pour obtenir un ordre lexicographique + if visit_left_right and self._visit(node.right,string+node.chars[:-1],callback,True): + return True + + # Maintenant le noeud en cours + if node.data is not None and callback(string+node.chars,node.data): + return True + + # Puis le noeud suivant + if self._visit(node.next,string+node.chars,callback,True): + return True + + # Puis à gauche + if visit_left_right and self._visit(node.left,string+node.chars[:-1],callback,True): + return True + + return False + + def cat(self,node,debug=False): + """ Méthode forçant la concaténation des noeuds, inutile sauf en cas de bug. """ + if node == None : return + node.left = self.cat(node.left,debug) + node.next = self.cat(node.next,debug) + node.right = self.cat(node.right,debug) + node, discard = self._compact_node(node,None,debug) + return node + + def debug(self,node,indentation=0): + print node.chars,node.data + if node.left is not None: + print ' '*(indentation+1),'LEFT', + self.debug(node.left,indentation+1) + if node.next is not None: + print ' '*(indentation+1),'NEXT', + self.debug(node.next,indentation+1) + if node.right is not None: + print ' '*(indentation+1),'RIGHT', + self.debug(node.right,indentation+1) + +if __name__ == '__main__': + urls = compact_tst() + + def callback(key,value): + assert urls[key] == value, "%s : %s != %s"%(key,urls[key],value) + print key, value + return False + + QUANTITY = 1000 - 1 + + n = 0 + try: + chars = 0 + for n, l in enumerate(file('url_1000000.csv','rb')): + if n == QUANTITY: break + if n%1000==0 : print n + key = l.rstrip() + chars += len(key) + urls[key] = 0 + finally: + stats = {} + urls.stats(urls.root,stats) + print n+1, "lignes", chars, "caracteres" + for key in sorted(stats.keys()): + print "%16s\t%6i\t%6.2f%%"%( + key, + stats[key], + (key=='total_chars' and 100.0 * stats[key] / chars) or (100.0 * stats[key] / stats['nodes']) + ) + + urls.root = urls.cat(urls.root,True) + + # On recalcule les stats après concaténation forcée des noeuds. + # Si qqchose a changé c'est un bug ! + stats = {} + urls.stats(urls.root,stats) + print n+1, "lignes", chars, "caracteres" + for key in sorted(stats.keys()): + print "%16s\t%6i\t%6.2f%%"%( + key, + stats[key], + (key=='total_chars' and 100.0 * stats[key] / chars) or (100.0 * stats[key] / stats['nodes']) + ) + + for n, l in enumerate(file('url_1000000.csv','rb')): + if n == QUANTITY: break + if n%1000==0 : print 'Delete ',n + key = l.rstrip() + if n%2 == 0 : del urls[key] + + urls.root = urls.cat(urls.root,True) + + for n, l in enumerate(file('url_1000000.csv','rb')): + if n == QUANTITY: break + if n%1000==0 : print 'Check ',n + key = l.rstrip() + if n%2==1: + assert urls[key] == 0 + else: + assert urls[key] is None + + # On recalcule les stats après concaténation forcée des noeuds. + # Si qqchose a changé c'est un bug ! + stats = {} + urls.stats(urls.root,stats) + print n+1, "lignes", chars, "caracteres" + for key in sorted(stats.keys()): + print "%16s\t%6i\t%6.2f%%"%( + key, + stats[key], + (key=='total_chars' and 100.0 * stats[key] / chars) or (100.0 * stats[key] / stats['nodes']) + ) + + t = compact_tst() + t['nicolas'] = 'nicolas' + t['laurent'] = 'laurent' + t['nicolas lehuen'] = 'nicolas lehuen' + t['laurent querel'] = 'laurent querel' + assert 'nicolas' == t['nicolas'] + assert 'nicolas lehuen' == t['nicolas lehuen'] + assert 'laurent' == t['laurent'] + assert 'laurent querel' == t['laurent querel'] + + import random + + t = compact_tst() + + data = range(1000) + seed = random.randint(-5000000,5000000) + print 'Seed is ',seed + seed = 654 + random.Random(seed).shuffle(data) + + for i, d in enumerate(data): + if i%100==0: print i + t[str(d)] = d + for i2, d2 in enumerate(data[:i]): + assert t[str(d2)] == d2 + + for i, d in enumerate(data): + if i%100==0: print i + if i%3==0: del t[str(d)] + + t.root = t.cat(t.root,True) + + for i,d in enumerate(data): + if i%3==0 : + assert t[str(d)] == None, "%s => %s != %s"%(d,None,t[str(d)]) + else: + assert t[str(d)] == d, "%s => %s != %s"%(d,i,t[str(d)]) diff --git a/python/tst_wrap.h b/python/tst_wrap.h index 8ea3ab8..27ad451 100644 --- a/python/tst_wrap.h +++ b/python/tst_wrap.h @@ -1,406 +1,406 @@ -/* ---------------------------------------------------------------------------- - * This file was automatically generated by SWIG (http://www.swig.org). - * Version 1.3.38 - * - * This file is not intended to be easily readable and contains a number of - * coding conventions designed to improve portability and efficiency. Do not make - * changes to this file unless you know what you are doing--modify the SWIG - * interface file instead. - * ----------------------------------------------------------------------------- */ - -#ifndef SWIG_tst_WRAP_H_ -#define SWIG_tst_WRAP_H_ - -#include <map> -#include <string> - - -class SwigDirector__TST : public tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >, public Swig::Director { - -public: - SwigDirector__TST(PyObject *self); - virtual ~SwigDirector__TST(); - - -/* Internal Director utilities */ -public: - bool swig_get_inner(const char* name) const { - std::map<std::string, bool>::const_iterator iv = inner.find(name); - return (iv != inner.end() ? iv->second : false); - } - - void swig_set_inner(const char* name, bool val) const - { inner[name] = val;} - -private: - mutable std::map<std::string, bool> inner; -}; - - -class SwigDirector__Action : public tst_action< char,PythonReference,string_type >, public Swig::Director { - -public: - SwigDirector__Action(PyObject *self); - virtual ~SwigDirector__Action(); - virtual void perform(string_type const &string, int remaining_distance, PythonReference data); - virtual PythonReference result(); - - -/* Internal Director utilities */ -public: - bool swig_get_inner(const char* name) const { - std::map<std::string, bool>::const_iterator iv = inner.find(name); - return (iv != inner.end() ? iv->second : false); - } - - void swig_set_inner(const char* name, bool val) const - { inner[name] = val;} - -private: - mutable std::map<std::string, bool> inner; - - -#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) -/* VTable implementation */ - PyObject *swig_get_method(size_t method_index, const char *method_name) const { - PyObject *method = vtable[method_index]; - if (!method) { - swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); - method = PyObject_GetAttr(swig_get_self(), name); - if (method == NULL) { - std::string msg = "Method in class _Action doesn't exist, undefined "; - msg += method_name; - Swig::DirectorMethodException::raise(msg.c_str()); - } - vtable[method_index] = method; - }; - return method; - } -private: - mutable swig::SwigVar_PyObject vtable[2]; -#endif - -}; - - -class SwigDirector__Filter : public tst_filter< char,PythonReference,string_type >, public Swig::Director { - -public: - SwigDirector__Filter(PyObject *self); - virtual ~SwigDirector__Filter(); - virtual PythonReference perform(string_type const &string, int remaining_distance, PythonReference data); - - -/* Internal Director utilities */ -public: - bool swig_get_inner(const char* name) const { - std::map<std::string, bool>::const_iterator iv = inner.find(name); - return (iv != inner.end() ? iv->second : false); - } - - void swig_set_inner(const char* name, bool val) const - { inner[name] = val;} - -private: - mutable std::map<std::string, bool> inner; - - -#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) -/* VTable implementation */ - PyObject *swig_get_method(size_t method_index, const char *method_name) const { - PyObject *method = vtable[method_index]; - if (!method) { - swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); - method = PyObject_GetAttr(swig_get_self(), name); - if (method == NULL) { - std::string msg = "Method in class _Filter doesn't exist, undefined "; - msg += method_name; - Swig::DirectorMethodException::raise(msg.c_str()); - } - vtable[method_index] = method; - }; - return method; - } -private: - mutable swig::SwigVar_PyObject vtable[1]; -#endif - -}; - - -class SwigDirector_CallableAction : public CallableAction, public Swig::Director { - -public: - SwigDirector_CallableAction(PyObject *self, PythonReference perform, PythonReference result); - virtual ~SwigDirector_CallableAction(); - virtual void perform(string_type const &string, int remaining_distance, PythonReference data); - virtual PythonReference result(); - - -/* Internal Director utilities */ -public: - bool swig_get_inner(const char* name) const { - std::map<std::string, bool>::const_iterator iv = inner.find(name); - return (iv != inner.end() ? iv->second : false); - } - - void swig_set_inner(const char* name, bool val) const - { inner[name] = val;} - -private: - mutable std::map<std::string, bool> inner; - - -#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) -/* VTable implementation */ - PyObject *swig_get_method(size_t method_index, const char *method_name) const { - PyObject *method = vtable[method_index]; - if (!method) { - swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); - method = PyObject_GetAttr(swig_get_self(), name); - if (method == NULL) { - std::string msg = "Method in class CallableAction doesn't exist, undefined "; - msg += method_name; - Swig::DirectorMethodException::raise(msg.c_str()); - } - vtable[method_index] = method; - }; - return method; - } -private: - mutable swig::SwigVar_PyObject vtable[2]; -#endif - -}; - - -class SwigDirector_CallableFilter : public CallableFilter, public Swig::Director { - -public: - SwigDirector_CallableFilter(PyObject *self, PythonReference _callable); - virtual ~SwigDirector_CallableFilter(); - virtual PythonReference perform(string_type const &string, int remaining_distance, PythonReference data); - - -/* Internal Director utilities */ -public: - bool swig_get_inner(const char* name) const { - std::map<std::string, bool>::const_iterator iv = inner.find(name); - return (iv != inner.end() ? iv->second : false); - } - - void swig_set_inner(const char* name, bool val) const - { inner[name] = val;} - -private: - mutable std::map<std::string, bool> inner; - - -#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) -/* VTable implementation */ - PyObject *swig_get_method(size_t method_index, const char *method_name) const { - PyObject *method = vtable[method_index]; - if (!method) { - swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); - method = PyObject_GetAttr(swig_get_self(), name); - if (method == NULL) { - std::string msg = "Method in class CallableFilter doesn't exist, undefined "; - msg += method_name; - Swig::DirectorMethodException::raise(msg.c_str()); - } - vtable[method_index] = method; - }; - return method; - } -private: - mutable swig::SwigVar_PyObject vtable[1]; -#endif - -}; - - -class SwigDirector_DictAction : public DictAction, public Swig::Director { - -public: - SwigDirector_DictAction(PyObject *self); - virtual ~SwigDirector_DictAction(); - virtual void perform(string_type const &string, int remaining_distance, PythonReference data); - virtual PythonReference result(); - - -/* Internal Director utilities */ -public: - bool swig_get_inner(const char* name) const { - std::map<std::string, bool>::const_iterator iv = inner.find(name); - return (iv != inner.end() ? iv->second : false); - } - - void swig_set_inner(const char* name, bool val) const - { inner[name] = val;} - -private: - mutable std::map<std::string, bool> inner; - - -#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) -/* VTable implementation */ - PyObject *swig_get_method(size_t method_index, const char *method_name) const { - PyObject *method = vtable[method_index]; - if (!method) { - swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); - method = PyObject_GetAttr(swig_get_self(), name); - if (method == NULL) { - std::string msg = "Method in class DictAction doesn't exist, undefined "; - msg += method_name; - Swig::DirectorMethodException::raise(msg.c_str()); - } - vtable[method_index] = method; - }; - return method; - } -private: - mutable swig::SwigVar_PyObject vtable[2]; -#endif - -}; - - -class SwigDirector_ListAction : public ListAction, public Swig::Director { - -public: - SwigDirector_ListAction(PyObject *self); - virtual ~SwigDirector_ListAction(); - virtual void perform(string_type const &string, int remaining_distance, PythonReference data); - virtual PythonReference result(); - - -/* Internal Director utilities */ -public: - bool swig_get_inner(const char* name) const { - std::map<std::string, bool>::const_iterator iv = inner.find(name); - return (iv != inner.end() ? iv->second : false); - } - - void swig_set_inner(const char* name, bool val) const - { inner[name] = val;} - -private: - mutable std::map<std::string, bool> inner; - - -#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) -/* VTable implementation */ - PyObject *swig_get_method(size_t method_index, const char *method_name) const { - PyObject *method = vtable[method_index]; - if (!method) { - swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); - method = PyObject_GetAttr(swig_get_self(), name); - if (method == NULL) { - std::string msg = "Method in class ListAction doesn't exist, undefined "; - msg += method_name; - Swig::DirectorMethodException::raise(msg.c_str()); - } - vtable[method_index] = method; - }; - return method; - } -private: - mutable swig::SwigVar_PyObject vtable[2]; -#endif - -}; - - -class SwigDirector_TupleListAction : public TupleListAction, public Swig::Director { - -public: - SwigDirector_TupleListAction(PyObject *self); - virtual ~SwigDirector_TupleListAction(); - virtual void perform(string_type const &string, int remaining_distance, PythonReference data); - virtual PythonReference result(); - - -/* Internal Director utilities */ -public: - bool swig_get_inner(const char* name) const { - std::map<std::string, bool>::const_iterator iv = inner.find(name); - return (iv != inner.end() ? iv->second : false); - } - - void swig_set_inner(const char* name, bool val) const - { inner[name] = val;} - -private: - mutable std::map<std::string, bool> inner; - - -#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) -/* VTable implementation */ - PyObject *swig_get_method(size_t method_index, const char *method_name) const { - PyObject *method = vtable[method_index]; - if (!method) { - swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); - method = PyObject_GetAttr(swig_get_self(), name); - if (method == NULL) { - std::string msg = "Method in class TupleListAction doesn't exist, undefined "; - msg += method_name; - Swig::DirectorMethodException::raise(msg.c_str()); - } - vtable[method_index] = method; - }; - return method; - } -private: - mutable swig::SwigVar_PyObject vtable[2]; -#endif - -}; - - -class SwigDirector_TST : public TST, public Swig::Director { - -public: - SwigDirector_TST(PyObject *self); - virtual ~SwigDirector_TST(); - virtual PythonReference write_to_file(PythonReference file); - virtual PythonReference read_from_file(PythonReference file); - - -/* Internal Director utilities */ -public: - bool swig_get_inner(const char* name) const { - std::map<std::string, bool>::const_iterator iv = inner.find(name); - return (iv != inner.end() ? iv->second : false); - } - - void swig_set_inner(const char* name, bool val) const - { inner[name] = val;} - -private: - mutable std::map<std::string, bool> inner; - - -#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) -/* VTable implementation */ - PyObject *swig_get_method(size_t method_index, const char *method_name) const { - PyObject *method = vtable[method_index]; - if (!method) { - swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); - method = PyObject_GetAttr(swig_get_self(), name); - if (method == NULL) { - std::string msg = "Method in class TST doesn't exist, undefined "; - msg += method_name; - Swig::DirectorMethodException::raise(msg.c_str()); - } - vtable[method_index] = method; - }; - return method; - } -private: - mutable swig::SwigVar_PyObject vtable[2]; -#endif - -}; - - -#endif +/* ---------------------------------------------------------------------------- + * This file was automatically generated by SWIG (http://www.swig.org). + * Version 1.3.38 + * + * This file is not intended to be easily readable and contains a number of + * coding conventions designed to improve portability and efficiency. Do not make + * changes to this file unless you know what you are doing--modify the SWIG + * interface file instead. + * ----------------------------------------------------------------------------- */ + +#ifndef SWIG_tst_WRAP_H_ +#define SWIG_tst_WRAP_H_ + +#include <map> +#include <string> + + +class SwigDirector__TST : public tst< char,PythonReference,memory_storage< char,PythonReference >,ObjectSerializer,string_type >, public Swig::Director { + +public: + SwigDirector__TST(PyObject *self); + virtual ~SwigDirector__TST(); + + +/* Internal Director utilities */ +public: + bool swig_get_inner(const char* name) const { + std::map<std::string, bool>::const_iterator iv = inner.find(name); + return (iv != inner.end() ? iv->second : false); + } + + void swig_set_inner(const char* name, bool val) const + { inner[name] = val;} + +private: + mutable std::map<std::string, bool> inner; +}; + + +class SwigDirector__Action : public tst_action< char,PythonReference,string_type >, public Swig::Director { + +public: + SwigDirector__Action(PyObject *self); + virtual ~SwigDirector__Action(); + virtual void perform(string_type const &string, int remaining_distance, PythonReference data); + virtual PythonReference result(); + + +/* Internal Director utilities */ +public: + bool swig_get_inner(const char* name) const { + std::map<std::string, bool>::const_iterator iv = inner.find(name); + return (iv != inner.end() ? iv->second : false); + } + + void swig_set_inner(const char* name, bool val) const + { inner[name] = val;} + +private: + mutable std::map<std::string, bool> inner; + + +#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) +/* VTable implementation */ + PyObject *swig_get_method(size_t method_index, const char *method_name) const { + PyObject *method = vtable[method_index]; + if (!method) { + swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); + method = PyObject_GetAttr(swig_get_self(), name); + if (method == NULL) { + std::string msg = "Method in class _Action doesn't exist, undefined "; + msg += method_name; + Swig::DirectorMethodException::raise(msg.c_str()); + } + vtable[method_index] = method; + }; + return method; + } +private: + mutable swig::SwigVar_PyObject vtable[2]; +#endif + +}; + + +class SwigDirector__Filter : public tst_filter< char,PythonReference,string_type >, public Swig::Director { + +public: + SwigDirector__Filter(PyObject *self); + virtual ~SwigDirector__Filter(); + virtual PythonReference perform(string_type const &string, int remaining_distance, PythonReference data); + + +/* Internal Director utilities */ +public: + bool swig_get_inner(const char* name) const { + std::map<std::string, bool>::const_iterator iv = inner.find(name); + return (iv != inner.end() ? iv->second : false); + } + + void swig_set_inner(const char* name, bool val) const + { inner[name] = val;} + +private: + mutable std::map<std::string, bool> inner; + + +#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) +/* VTable implementation */ + PyObject *swig_get_method(size_t method_index, const char *method_name) const { + PyObject *method = vtable[method_index]; + if (!method) { + swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); + method = PyObject_GetAttr(swig_get_self(), name); + if (method == NULL) { + std::string msg = "Method in class _Filter doesn't exist, undefined "; + msg += method_name; + Swig::DirectorMethodException::raise(msg.c_str()); + } + vtable[method_index] = method; + }; + return method; + } +private: + mutable swig::SwigVar_PyObject vtable[1]; +#endif + +}; + + +class SwigDirector_CallableAction : public CallableAction, public Swig::Director { + +public: + SwigDirector_CallableAction(PyObject *self, PythonReference perform, PythonReference result); + virtual ~SwigDirector_CallableAction(); + virtual void perform(string_type const &string, int remaining_distance, PythonReference data); + virtual PythonReference result(); + + +/* Internal Director utilities */ +public: + bool swig_get_inner(const char* name) const { + std::map<std::string, bool>::const_iterator iv = inner.find(name); + return (iv != inner.end() ? iv->second : false); + } + + void swig_set_inner(const char* name, bool val) const + { inner[name] = val;} + +private: + mutable std::map<std::string, bool> inner; + + +#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) +/* VTable implementation */ + PyObject *swig_get_method(size_t method_index, const char *method_name) const { + PyObject *method = vtable[method_index]; + if (!method) { + swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); + method = PyObject_GetAttr(swig_get_self(), name); + if (method == NULL) { + std::string msg = "Method in class CallableAction doesn't exist, undefined "; + msg += method_name; + Swig::DirectorMethodException::raise(msg.c_str()); + } + vtable[method_index] = method; + }; + return method; + } +private: + mutable swig::SwigVar_PyObject vtable[2]; +#endif + +}; + + +class SwigDirector_CallableFilter : public CallableFilter, public Swig::Director { + +public: + SwigDirector_CallableFilter(PyObject *self, PythonReference _callable); + virtual ~SwigDirector_CallableFilter(); + virtual PythonReference perform(string_type const &string, int remaining_distance, PythonReference data); + + +/* Internal Director utilities */ +public: + bool swig_get_inner(const char* name) const { + std::map<std::string, bool>::const_iterator iv = inner.find(name); + return (iv != inner.end() ? iv->second : false); + } + + void swig_set_inner(const char* name, bool val) const + { inner[name] = val;} + +private: + mutable std::map<std::string, bool> inner; + + +#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) +/* VTable implementation */ + PyObject *swig_get_method(size_t method_index, const char *method_name) const { + PyObject *method = vtable[method_index]; + if (!method) { + swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); + method = PyObject_GetAttr(swig_get_self(), name); + if (method == NULL) { + std::string msg = "Method in class CallableFilter doesn't exist, undefined "; + msg += method_name; + Swig::DirectorMethodException::raise(msg.c_str()); + } + vtable[method_index] = method; + }; + return method; + } +private: + mutable swig::SwigVar_PyObject vtable[1]; +#endif + +}; + + +class SwigDirector_DictAction : public DictAction, public Swig::Director { + +public: + SwigDirector_DictAction(PyObject *self); + virtual ~SwigDirector_DictAction(); + virtual void perform(string_type const &string, int remaining_distance, PythonReference data); + virtual PythonReference result(); + + +/* Internal Director utilities */ +public: + bool swig_get_inner(const char* name) const { + std::map<std::string, bool>::const_iterator iv = inner.find(name); + return (iv != inner.end() ? iv->second : false); + } + + void swig_set_inner(const char* name, bool val) const + { inner[name] = val;} + +private: + mutable std::map<std::string, bool> inner; + + +#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) +/* VTable implementation */ + PyObject *swig_get_method(size_t method_index, const char *method_name) const { + PyObject *method = vtable[method_index]; + if (!method) { + swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); + method = PyObject_GetAttr(swig_get_self(), name); + if (method == NULL) { + std::string msg = "Method in class DictAction doesn't exist, undefined "; + msg += method_name; + Swig::DirectorMethodException::raise(msg.c_str()); + } + vtable[method_index] = method; + }; + return method; + } +private: + mutable swig::SwigVar_PyObject vtable[2]; +#endif + +}; + + +class SwigDirector_ListAction : public ListAction, public Swig::Director { + +public: + SwigDirector_ListAction(PyObject *self); + virtual ~SwigDirector_ListAction(); + virtual void perform(string_type const &string, int remaining_distance, PythonReference data); + virtual PythonReference result(); + + +/* Internal Director utilities */ +public: + bool swig_get_inner(const char* name) const { + std::map<std::string, bool>::const_iterator iv = inner.find(name); + return (iv != inner.end() ? iv->second : false); + } + + void swig_set_inner(const char* name, bool val) const + { inner[name] = val;} + +private: + mutable std::map<std::string, bool> inner; + + +#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) +/* VTable implementation */ + PyObject *swig_get_method(size_t method_index, const char *method_name) const { + PyObject *method = vtable[method_index]; + if (!method) { + swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); + method = PyObject_GetAttr(swig_get_self(), name); + if (method == NULL) { + std::string msg = "Method in class ListAction doesn't exist, undefined "; + msg += method_name; + Swig::DirectorMethodException::raise(msg.c_str()); + } + vtable[method_index] = method; + }; + return method; + } +private: + mutable swig::SwigVar_PyObject vtable[2]; +#endif + +}; + + +class SwigDirector_TupleListAction : public TupleListAction, public Swig::Director { + +public: + SwigDirector_TupleListAction(PyObject *self); + virtual ~SwigDirector_TupleListAction(); + virtual void perform(string_type const &string, int remaining_distance, PythonReference data); + virtual PythonReference result(); + + +/* Internal Director utilities */ +public: + bool swig_get_inner(const char* name) const { + std::map<std::string, bool>::const_iterator iv = inner.find(name); + return (iv != inner.end() ? iv->second : false); + } + + void swig_set_inner(const char* name, bool val) const + { inner[name] = val;} + +private: + mutable std::map<std::string, bool> inner; + + +#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) +/* VTable implementation */ + PyObject *swig_get_method(size_t method_index, const char *method_name) const { + PyObject *method = vtable[method_index]; + if (!method) { + swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); + method = PyObject_GetAttr(swig_get_self(), name); + if (method == NULL) { + std::string msg = "Method in class TupleListAction doesn't exist, undefined "; + msg += method_name; + Swig::DirectorMethodException::raise(msg.c_str()); + } + vtable[method_index] = method; + }; + return method; + } +private: + mutable swig::SwigVar_PyObject vtable[2]; +#endif + +}; + + +class SwigDirector_TST : public TST, public Swig::Director { + +public: + SwigDirector_TST(PyObject *self); + virtual ~SwigDirector_TST(); + virtual PythonReference write_to_file(PythonReference file); + virtual PythonReference read_from_file(PythonReference file); + + +/* Internal Director utilities */ +public: + bool swig_get_inner(const char* name) const { + std::map<std::string, bool>::const_iterator iv = inner.find(name); + return (iv != inner.end() ? iv->second : false); + } + + void swig_set_inner(const char* name, bool val) const + { inner[name] = val;} + +private: + mutable std::map<std::string, bool> inner; + + +#if defined(SWIG_PYTHON_DIRECTOR_VTABLE) +/* VTable implementation */ + PyObject *swig_get_method(size_t method_index, const char *method_name) const { + PyObject *method = vtable[method_index]; + if (!method) { + swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name); + method = PyObject_GetAttr(swig_get_self(), name); + if (method == NULL) { + std::string msg = "Method in class TST doesn't exist, undefined "; + msg += method_name; + Swig::DirectorMethodException::raise(msg.c_str()); + } + vtable[method_index] = method; + }; + return method; + } +private: + mutable swig::SwigVar_PyObject vtable[2]; +#endif + +}; + + +#endif diff --git a/textindex/mp3tag.py b/textindex/mp3tag.py index f8a9017..a594a30 100644 --- a/textindex/mp3tag.py +++ b/textindex/mp3tag.py @@ -1,107 +1,107 @@ -if __name__ == "__main__": - import sys - from time import time - import linecache - import glob - from textindex import textindex - import traceback - import linecache - from mutagen.mp3 import MP3 - import os - - ti = textindex() - - try: - start = time() - ti.read('mp3.ti') - print 'Loading time : %.2fs'%(time()-start) - except: - traceback.print_exc() - - start = time() - lines = 0 - - for root, dirnames, filenames in os.walk(sys.argv[1]): - for filename in filenames: - if filename[-4:].lower() == '.mp3': - try: - full_filename = os.path.join(root,filename) - mp3 = MP3(full_filename) - title = mp3.get('TIT2') - artist = mp3.get('TPE2') - album = mp3.get('TALB') - if title: - title = title.text[0].decode('iso-8859-1').lower() - ti.put_text(title,full_filename) - else: - ti.put_text(filename[:-4].lower(),mp3) - if artist: - artist = artist.text[0].decode('iso-8859-1').lower() - ti.put_text(artist,full_filename) - if album: - album = album.text[0].decode('iso-8859-1').lower() - ti.put_text(album,full_filename) - print title, album, artist - except: - pass - - ti.pack() - print 'Indexing time : %.2fs for %i lines'%(time()-start,lines) - - ti.write('mp3.ti') - - def lines(text,intersection=True): - for ln, r in ti.find_text(text.lower(),intersection): - print '%02i:%s'%( - r, - ln - ), - - def ilines(text,intersection=True): - for ln, r in ti.find_text(text.lower(),intersection): - print '%02i:%s'%( - r, - ln, - ), - - if len(sys.argv)>1 and sys.argv[-1]=='gui': - from Tkinter import * - class Explorer(object): - def __init__(self,master): - self.frame = Frame(master) - self.frame.pack(fill=BOTH, expand=1) - - self.entry = Entry(self.frame, name='input') - self.entry.pack(fill=X) - self.entry.bind('<KeyRelease>',self.keyPressed) - - frame = Frame(self.frame) - frame.pack(fill=BOTH, expand=1) - scrollbar = Scrollbar(frame, orient=VERTICAL) - self.list = Listbox(frame, name='list', yscrollcommand=scrollbar.set) - scrollbar.config(command=self.list.yview) - scrollbar.pack(side=RIGHT, fill=Y) - self.list.pack(side=LEFT, fill=BOTH, expand=1) - - self.label = Label(self.frame, name='count') - self.label.pack() - - def keyPressed(self,event): - self.list.delete(0,END) - start = time() - result = ti.find_text(self.entry.get().lower(),True) - # result.sort(key=lambda i : -i[1]) - elapsed = time() - start - for ln, r in result[:100]: - self.list.insert(END,'%02i:%s'%( - r, - ln - )) - self.label.config(text = '%i lines in %.2fs'%( - len(result), - elapsed - )) - - root = Tk() - explorer = Explorer(root) - root.mainloop() +if __name__ == "__main__": + import sys + from time import time + import linecache + import glob + from textindex import textindex + import traceback + import linecache + from mutagen.mp3 import MP3 + import os + + ti = textindex() + + try: + start = time() + ti.read('mp3.ti') + print 'Loading time : %.2fs'%(time()-start) + except: + traceback.print_exc() + + start = time() + lines = 0 + + for root, dirnames, filenames in os.walk(sys.argv[1]): + for filename in filenames: + if filename[-4:].lower() == '.mp3': + try: + full_filename = os.path.join(root,filename) + mp3 = MP3(full_filename) + title = mp3.get('TIT2') + artist = mp3.get('TPE2') + album = mp3.get('TALB') + if title: + title = title.text[0].decode('iso-8859-1').lower() + ti.put_text(title,full_filename) + else: + ti.put_text(filename[:-4].lower(),mp3) + if artist: + artist = artist.text[0].decode('iso-8859-1').lower() + ti.put_text(artist,full_filename) + if album: + album = album.text[0].decode('iso-8859-1').lower() + ti.put_text(album,full_filename) + print title, album, artist + except: + pass + + ti.pack() + print 'Indexing time : %.2fs for %i lines'%(time()-start,lines) + + ti.write('mp3.ti') + + def lines(text,intersection=True): + for ln, r in ti.find_text(text.lower(),intersection): + print '%02i:%s'%( + r, + ln + ), + + def ilines(text,intersection=True): + for ln, r in ti.find_text(text.lower(),intersection): + print '%02i:%s'%( + r, + ln, + ), + + if len(sys.argv)>1 and sys.argv[-1]=='gui': + from Tkinter import * + class Explorer(object): + def __init__(self,master): + self.frame = Frame(master) + self.frame.pack(fill=BOTH, expand=1) + + self.entry = Entry(self.frame, name='input') + self.entry.pack(fill=X) + self.entry.bind('<KeyRelease>',self.keyPressed) + + frame = Frame(self.frame) + frame.pack(fill=BOTH, expand=1) + scrollbar = Scrollbar(frame, orient=VERTICAL) + self.list = Listbox(frame, name='list', yscrollcommand=scrollbar.set) + scrollbar.config(command=self.list.yview) + scrollbar.pack(side=RIGHT, fill=Y) + self.list.pack(side=LEFT, fill=BOTH, expand=1) + + self.label = Label(self.frame, name='count') + self.label.pack() + + def keyPressed(self,event): + self.list.delete(0,END) + start = time() + result = ti.find_text(self.entry.get().lower(),True) + # result.sort(key=lambda i : -i[1]) + elapsed = time() - start + for ln, r in result[:100]: + self.list.insert(END,'%02i:%s'%( + r, + ln + )) + self.label.config(text = '%i lines in %.2fs'%( + len(result), + elapsed + )) + + root = Tk() + explorer = Explorer(root) + root.mainloop() diff --git a/textindex/testxapian.py b/textindex/testxapian.py index 07662fc..19626a3 100644 --- a/textindex/testxapian.py +++ b/textindex/testxapian.py @@ -1,87 +1,87 @@ -if __name__ == "__main__": - import sys - from time import time - import linecache - import glob - import traceback - import linecache - import xapian - import re - - stem = xapian.Stem("french") - ti = xapian.inmemory_open() - ti = xapian.WritableDatabase("test.ti", xapian.DB_CREATE_OR_OPEN) - # ti = xapian.quartz_open('test.idx') - -# start = time() -# lines = 0 -# for f in glob.glob('*.txt'): -# print f, -# for linenumber, line in enumerate(file(f,'rb')): -# lines += 1 -# line = line.strip() -# doc = xapian.Document() -# doc.set_data('%12s:%04i'%(f,linenumber)) -# for word_number, word in enumerate(re.findall(r'\w+',line.lower())): -# doc.add_posting(word,word_number) -# ti.add_document(doc) -# if linenumber % 100 == 0: -# sys.stdout.write('.') -# print 'OK' -# print 'Indexing time : %.2fs for %i lines'%(time()-start,lines) - - if len(sys.argv)>1 and sys.argv[1]=='gui': - from Tkinter import * - class Explorer(object): - def __init__(self,master): - self.frame = Frame(master) - self.frame.pack(fill=BOTH, expand=1) - - self.entry = Entry(self.frame, name='input') - self.entry.pack(fill=X) - self.entry.bind('<Key>',self.keyPressed) - - frame = Frame(self.frame) - frame.pack(fill=BOTH, expand=1) - scrollbar = Scrollbar(frame, orient=VERTICAL) - self.list = Listbox(frame, name='list', yscrollcommand=scrollbar.set) - scrollbar.config(command=self.list.yview) - scrollbar.pack(side=RIGHT, fill=Y) - self.list.pack(side=LEFT, fill=BOTH, expand=1) - - self.label = Label(self.frame, name='count') - self.label.pack() - - def keyPressed(self,event): - self.list.delete(0,END) - start = time() - if self.entry.get(): - query_parser = xapian.QueryParser() - enq = xapian.Enquire(ti) - query = query_parser.parse_query(self.entry.get(),query_parser.FLAG_WILDCARD) - print query.get_description() - enq.set_query(query) - elapsed = time() - start - result = enq.get_mset(0,100) - count = 0 - for doc in result: - count += 1 - ln = doc[4].get_data() - r = doc[1] - i = ln.rindex(':') - d = ln[:i].strip() - l = int(ln[i+1:]) - self.list.insert(END,'%.2f:%s:%i:%s'%( - r, - d, - l, - linecache.getline(d,l+1).strip() - )) - self.label.config(text = '%i lines in %.2fs'%( - count, - elapsed - )) - - root = Tk() - explorer = Explorer(root) - root.mainloop() +if __name__ == "__main__": + import sys + from time import time + import linecache + import glob + import traceback + import linecache + import xapian + import re + + stem = xapian.Stem("french") + ti = xapian.inmemory_open() + ti = xapian.WritableDatabase("test.ti", xapian.DB_CREATE_OR_OPEN) + # ti = xapian.quartz_open('test.idx') + +# start = time() +# lines = 0 +# for f in glob.glob('*.txt'): +# print f, +# for linenumber, line in enumerate(file(f,'rb')): +# lines += 1 +# line = line.strip() +# doc = xapian.Document() +# doc.set_data('%12s:%04i'%(f,linenumber)) +# for word_number, word in enumerate(re.findall(r'\w+',line.lower())): +# doc.add_posting(word,word_number) +# ti.add_document(doc) +# if linenumber % 100 == 0: +# sys.stdout.write('.') +# print 'OK' +# print 'Indexing time : %.2fs for %i lines'%(time()-start,lines) + + if len(sys.argv)>1 and sys.argv[1]=='gui': + from Tkinter import * + class Explorer(object): + def __init__(self,master): + self.frame = Frame(master) + self.frame.pack(fill=BOTH, expand=1) + + self.entry = Entry(self.frame, name='input') + self.entry.pack(fill=X) + self.entry.bind('<Key>',self.keyPressed) + + frame = Frame(self.frame) + frame.pack(fill=BOTH, expand=1) + scrollbar = Scrollbar(frame, orient=VERTICAL) + self.list = Listbox(frame, name='list', yscrollcommand=scrollbar.set) + scrollbar.config(command=self.list.yview) + scrollbar.pack(side=RIGHT, fill=Y) + self.list.pack(side=LEFT, fill=BOTH, expand=1) + + self.label = Label(self.frame, name='count') + self.label.pack() + + def keyPressed(self,event): + self.list.delete(0,END) + start = time() + if self.entry.get(): + query_parser = xapian.QueryParser() + enq = xapian.Enquire(ti) + query = query_parser.parse_query(self.entry.get(),query_parser.FLAG_WILDCARD) + print query.get_description() + enq.set_query(query) + elapsed = time() - start + result = enq.get_mset(0,100) + count = 0 + for doc in result: + count += 1 + ln = doc[4].get_data() + r = doc[1] + i = ln.rindex(':') + d = ln[:i].strip() + l = int(ln[i+1:]) + self.list.insert(END,'%.2f:%s:%i:%s'%( + r, + d, + l, + linecache.getline(d,l+1).strip() + )) + self.label.config(text = '%i lines in %.2fs'%( + count, + elapsed + )) + + root = Tk() + explorer = Explorer(root) + root.mainloop()
nlehuen/pytst
3f0d5923fe8cfaf4cb895fc9e6ebd4e0926a4afc
Release 1.16
diff --git a/include/tst.h b/include/tst.h index ad8bab2..478138a 100644 --- a/include/tst.h +++ b/include/tst.h @@ -1,534 +1,534 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __TST__H_INCLUDED__ #define __TST__H_INCLUDED__ -const char* const TST_VERSION = "1.16RC"; +const char* const TST_VERSION = "1.16"; #include "debug.h" #include <iostream> #ifdef __PYTHON__BUILD__ #include "Python.h" #define tst_malloc PyMem_Malloc #define tst_realloc PyMem_Realloc #define tst_free PyMem_Free // Pour ajouter/supprimer les fonctions de scanning. // #define SCANNER #else #include "stdlib.h" #define tst_malloc malloc #define tst_realloc realloc #define tst_free free // Pour ajouter/supprimer les fonctions de scanning. // #define SCANNER #endif template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst; #include "fundamentals.h" #include "memory_storage.h" #include "iterators.h" template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst { public: friend class lexical_iterator<charT,valueT,storageT,serializerT,stringT>; friend class match_iterator<charT,valueT,storageT,serializerT,stringT>; typedef charT character_type; typedef valueT value_type; typedef storageT storage_type; typedef serializerT serializer_type; tst(); virtual ~tst() { delete storage; } void pack() { storage->pack(root); } valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,const stringT & string) const; valueT close_match(const stringT & string,int maximum_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT prefix_match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT get(const stringT & string) const; valueT get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory); valueT put(const stringT & string,valueT data); void remove(const stringT & string); bool contains(const stringT & string) const; void write(std::ostream &file) const; void read(std::istream &file); lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator() const { stringT key; return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,key,root); } lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; find_node(&current_index,&best_node,string); return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,string.substr(0,string.size()-1),current_index); } match_iterator<charT,valueT,storageT,serializerT,stringT> close_match_iterator(const stringT & string,int distance) const { return match_iterator<charT,valueT,storageT,serializerT,stringT>(this,string,distance,root); } int get_number_of_nodes() const { return storage->size(); } valueT get_default_value() const { return default_value; } #ifdef SCANNER valueT scan(const stringT & string,tst_action<charT,valueT,stringT>* to_perform); valueT scan_with_stop_chars(const stringT & string,const stringT& stop_chars,tst_action<charT,valueT,stringT>* to_perform) const; #endif protected: void set_storage(storageT* new_storage) { delete storage; storage = new_storage; } private: storageT* storage; valueT default_value; int root; void walk_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void close_match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,const size_t position, const int distance, const int remaining_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_joker_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_star_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; int build_node(node_info<charT,valueT>* current_node,const stringT & string,size_t current_position); void remove_node(int* current_index,const stringT & string,const size_t position); tst_node<charT,valueT>* find_node(int* current_index,int* best_node, const stringT & string) const; void balance_node(node_info<charT,valueT>* bal); void ll(node_info<charT,valueT>* bal); void rr(node_info<charT,valueT>* bal); void lr(node_info<charT,valueT>* bal); void rl(node_info<charT,valueT>* bal); void compute_height_and_balance(node_info<charT,valueT>* current_node_info) const; void write_node(std::ostream& file,serializerT* writer,int index) const; int read_node(std::istream& file,serializerT* reader,int depth); #ifdef SCANNER void compute_backtrack(tst_node<charT,valueT> *current_node,const stringT & string,int si_match_start,int si_match_end); #endif }; template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst<charT,valueT,storageT,serializerT,stringT>::tst() : storage(new storage_type(16)), default_value() { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } /*************************** high-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return current_node->data; } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> bool tst<charT,valueT,storageT,serializerT,stringT>::contains(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return true; } else { return false; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::put(const stringT & string,valueT data) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; return storage->get(node_index)->store(data); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; tst_node<charT,valueT>* current_node=storage->get(node_index); valueT data = current_node->data; if(data==default_value) { data=factory->perform(string,0,current_node->data); current_node->store(data); return data; } else { return data; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove(const stringT & string) { remove_node(&root,string,0); if(root==UNDEFINED_INDEX) { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } } /**************************** low-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst_node<charT,valueT>* tst<charT,valueT,storageT,serializerT,stringT>::find_node(int* current_index,int* best_node,const stringT & string) const { tst_node<charT,valueT>* current_node; int diff; size_t pos=0; while(*current_index!=UNDEFINED_INDEX) { current_node=storage->get(*current_index); if(current_node->c==0) { *current_index=UNDEFINED_INDEX; return 0; } else { diff=string[pos]-(current_node->c); } if(diff==0) { if(current_node->data!=default_value) { *best_node=*current_index; } ++pos; if(pos<string.size()) { *current_index = current_node->next; } else { return current_node; } } else if(diff>0) { *current_index=current_node->right; } else { *current_index=current_node->left; } } return 0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> int tst<charT,valueT,storageT,serializerT,stringT>::build_node(node_info<charT,valueT>* current_node_info,const stringT & string,size_t current_position) { int diff,result; if(current_node_info->node->c==0) { current_node_info->node->c=string[current_position]; #ifdef SCANNER current_node_info->node->position=current_position; #endif diff=0; } else { diff=string[current_position]-(current_node_info->node->c); } current_node_info->height=-1; current_node_info->balance_performed=0; if(diff==0) { ++current_position; compute_height_and_balance(current_node_info); // TODO : est-ce bien necessaire ? if(current_position<string.size()) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->next; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->next = next_node_info.index; return result; } else { return current_node_info->index; } } else if(diff>0) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->right; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->right = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->left==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = next_node_info.height; current_node_info->left_balance = 0; current_node_info->right_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->left; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = next_node_info.height-other_node_info.height; current_node_info->left_balance = other_node_info.balance; current_node_info->right_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } else { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->left; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->left = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->right==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = -next_node_info.height; current_node_info->right_balance = 0; current_node_info->left_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->right; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = other_node_info.height-next_node_info.height; current_node_info->right_balance = other_node_info.balance; current_node_info->left_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove_node(int* current_index,const stringT & string,const size_t current_position) { tst_node<charT,valueT>* current_node = storage->get(*current_index); int diff,*next_index; if(current_node->c==0) { return; } else { diff=string[current_position]-(current_node->c); } if(diff==0) { if(current_position+1<string.size()) { next_index = &(current_node->next); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position+1); } } else { current_node->store(default_value); } } else if(diff>0) { next_index = &(current_node->right); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } else { next_index = &(current_node->left); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } current_node=storage->get(*current_index); if( current_node->data==default_value && current_node->next==UNDEFINED_INDEX && current_node->right==UNDEFINED_INDEX && current_node->left==UNDEFINED_INDEX) { storage->delete_node(*current_index); *current_index=UNDEFINED_INDEX; } else { node_info<charT,valueT> current_node_info; current_node_info.index=*current_index; current_node_info.node=current_node; current_node_info.height=-1; balance_node(&current_node_info); *current_index = current_node_info.index; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::balance_node(node_info<charT,valueT>* bal) { if(bal->height==-1) { compute_height_and_balance(bal); } bal->balance_performed=0; if(bal->balance>1) { if(bal->right_balance>0) { rr(bal); } else { rl(bal); } bal->balance_performed=1; } else if(bal->balance<-1) { if(bal->left_balance<0) { ll(bal); } else { lr(bal); } bal->balance_performed=1; } assert(abs(bal->balance)<2); assert(abs(bal->right_balance)<2); assert(abs(bal->left_balance)<2); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::ll(node_info<charT,valueT>* bal) { int left_index=bal->node->left; tst_node<charT,valueT>* left_node=storage->get(left_index); int left_right_index=left_node->right; bal->node->left=left_right_index; left_node->right=bal->index; bal->index=left_index; bal->node=storage->get(left_index); bal->height=bal->height-1; bal->balance=0; bal->right_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rr(node_info<charT,valueT>* bal) { int right_index=bal->node->right; tst_node<charT,valueT>* right_node=storage->get(right_index); int right_left_index=right_node->left; bal->node->right=right_left_index; right_node->left=bal->index; bal->index=right_index; bal->node=storage->get(right_index); bal->height=bal->height-1; bal->balance=0; bal->left_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::lr(node_info<charT,valueT>* bal) { node_info<charT,valueT> left; left.index = bal->node->left; left.node = storage->get(left.index); rr(&left); bal->node->left=left.index; ll(bal); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rl(node_info<charT,valueT>* bal) { node_info<charT,valueT> right; right.index = bal->node->right; right.node = storage->get(right.index); ll(&right); bal->node->right=right.index; rr(bal); } diff --git a/python/setup.py b/python/setup.py index a6816da..1171f6e 100644 --- a/python/setup.py +++ b/python/setup.py @@ -1,49 +1,49 @@ # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from distutils.core import setup, Extension import sys extra_compile_args = [] setup( name = "pytst", - version = "1.16-RC1", + version = "1.16", author = "Nicolas Lehuen", author_email = "nicolas@lehuen.com", url = "http://nicolas.lehuen.com/index.php/category/Pytst", description = "An implementation of a Ternary Search Tree (TST) in C++ with Python bindings", py_modules = ["tst"], ext_modules = [ Extension( "_tst", ["tst_wrap.cxx"], include_dirs=['include'], extra_compile_args = extra_compile_args, define_macros=[('SCANNER', None),], ) ], download_url = "http://nicolas.lehuen.com/download/pytst/", classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: C++', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Scientific/Engineering :: Information Analysis', ] )
nlehuen/pytst
b80b1543cd4ac6801ce6c5286df3839d053b6825
Fix for bug reported by Keith Davidson
diff --git a/python/pythonTST.h b/python/pythonTST.h index 4f618f8..0f66751 100644 --- a/python/pythonTST.h +++ b/python/pythonTST.h @@ -1,323 +1,332 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define __PYTHON__BUILD__ #include "tst.h" #include "Python.h" #include "PythonReference.h" #include "qad_string.h" #include <iostream> #include <fstream> #ifdef ZIPPED_TREE #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/zlib.hpp> #endif typedef qad_string<char> string_type; class CallableAction : public tst_action<char,PythonReference,string_type > { public: CallableAction(PythonReference perform,PythonReference result) : _perform(perform), _result(result) { } virtual ~CallableAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { if(_perform.get()==Py_None) { return; } PythonReference tuple(Py_BuildValue("s#iO",string.data(),string.size(),remaining_distance,data.get()),0); - Py_DECREF(PyObject_CallObject(_perform.get(),tuple.get())); + PyObject* result = PyObject_CallObject(_perform.get(),tuple.get()); + if(result) { + Py_DECREF(result); + } } virtual PythonReference result() { if(_result.get()==Py_None) { return PythonReference(); } else { - return PythonReference(PyObject_CallObject(_result.get(),0),0); + PyObject* result = PyObject_CallObject(_result.get(),0); + if(result) { + return PythonReference(result,0); + } + else { + return PythonReference(); + } } } private: PythonReference _perform,_result; }; class CallableFilter : public tst_filter<char,PythonReference,string_type > { public: CallableFilter(PythonReference _callable) : callable(_callable) { } virtual ~CallableFilter() { } virtual PythonReference perform(const string_type& string,int remaining_distance,PythonReference data) { PythonReference tuple(Py_BuildValue("s#iO",string.data(),string.size(),remaining_distance,data.get()),0); return PythonReference(PyObject_CallObject(callable.get(),tuple.get()),0); } private: PythonReference callable; }; class DictAction : public tst_action<char,PythonReference,string_type > { public: DictAction() : dict(PyDict_New(),0) { } virtual ~DictAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { PythonReference key(Py_BuildValue("s#",string.data(),string.size()),0); PyObject* old_tuple=PyDict_GetItem(dict.get(),key.get()); if(old_tuple!=0) { long value=PyInt_AsLong(PyTuple_GetItem(old_tuple,0)); if(value<remaining_distance) { return; } } PythonReference tuple(Py_BuildValue("iO",remaining_distance,data.get()),0); PyDict_SetItem(dict.get(),key.get(),tuple.get()); }; virtual PythonReference result() { return dict; } private: PythonReference dict; }; class ListAction : public tst_action<char,PythonReference,string_type > { public: ListAction() : list(PyList_New(0),0) { } virtual ~ListAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { PyList_Append(list.get(),data.get()); } virtual PythonReference result() { return list; } private: PythonReference list; }; class TupleListAction : public tst_action<char,PythonReference,string_type > { public: TupleListAction() : list(PyList_New(0),0){ } virtual ~TupleListAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { PythonReference tuple(Py_BuildValue("s#iO",string.data(),string.size(),remaining_distance,data.get()),0); PyList_Append(list.get(),tuple.get()); } virtual PythonReference result() { return list; } private: PythonReference list; }; class ObjectSerializer { public: ObjectSerializer(); void write(std::ostream& file,PythonReference data); PythonReference read(std::istream& file); private: PythonReference dumps,loads; }; ObjectSerializer::ObjectSerializer() { PythonReference name(PyString_FromString("cPickle"),0); PythonReference cPickle(PyImport_Import(name.get()),0); dumps = PythonReference(PyObject_GetAttrString(cPickle.get(),"dumps"),0); loads = PythonReference(PyObject_GetAttrString(cPickle.get(),"loads"),0); } void ObjectSerializer::write(std::ostream& file,PythonReference data) { PythonReference call(Py_BuildValue("Oi",data.get(),2),0); PythonReference result(PyObject_CallObject(dumps.get(),call.get()),0); char *string; int length; PyString_AsStringAndSize(result.get(),&string,&length); file.write((char*)(&length),sizeof(int)); file.write(string,length); } PythonReference ObjectSerializer::read(std::istream& file) { int length; file.read((char*)(&length),sizeof(int)); char* string=(char*)tst_malloc(length); file.read(string,length); PythonReference dumped(PyString_FromStringAndSize(string,length),0); PythonReference call(Py_BuildValue("(O)",dumped.get()),0); PythonReference result(PyObject_CallObject(loads.get(),call.get()),0); tst_free(string); return result; } class TST; template <typename iterator_type> class TSTIterator { public: friend class TST; TSTIterator __iter__() { return *this; } PyObject* next() { typename iterator_type::value_type v(iterator.next()); if(v.second) { return Py_BuildValue("s#O",v.first.data(),v.first.size(),v.second->get()); } else { PythonReference exceptions(PyImport_ImportModule("exceptions"),0); PythonReference stop_iteration = exceptions.getattr("StopIteration"); PyErr_SetNone(stop_iteration.get()); return 0; } } private: TSTIterator(iterator_type i) : iterator(i) { } iterator_type iterator; }; typedef TSTIterator<lexical_iterator<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > > TSTLexicalIterator; typedef TSTIterator<match_iterator<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > > TSTCloseMatchIterator; class TST : public tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > { public: TST() : tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >() { } virtual ~TST() { } virtual PythonReference write_to_file(PythonReference file) { if(!PyString_CheckExact(file.get())) { throw TSTException("Argument of write_to_file() must be a string object"); } std::ofstream out(PyString_AsString(file.get()),std::ofstream::binary|std::ofstream::out|std::ofstream::trunc); out.exceptions(std::ofstream::eofbit | std::ofstream::failbit | std::ofstream::badbit); #ifdef ZIPPED_TREE boost::iostreams::filtering_ostream fout; fout.push(boost::iostreams::zlib_compressor()); fout.push(out); this->write(fout); fout.strict_sync(); #else this->write(out); #endif out.close(); return PythonReference(); } virtual PythonReference read_from_file(PythonReference file) { if(!PyString_CheckExact(file.get())) { throw TSTException("Argument of read_from_file() must be a string object"); } std::ifstream in(PyString_AsString(file.get()),std::ifstream::binary|std::ifstream::in); in.exceptions(std::ifstream::eofbit | std::ifstream::failbit | std::ifstream::badbit); #ifdef ZIPPED_TREE boost::iostreams::filtering_istream fin; fin.push(boost::iostreams::zlib_decompressor()); fin.push(in); this->read(fin); #else this->read(in); #endif in.close(); return PythonReference(); } PythonReference __getitem__(const string_type& string) { return get(string); } PythonReference __setitem__(const string_type& string,PythonReference data) { return put(string,data); } void __delitem__(const string_type& string) { remove(string); } PythonReference __contains__(const string_type& string) { if(contains(string)) { return PythonReference(Py_False); } else { return PythonReference(Py_True); } } TSTLexicalIterator __iter__() { return TSTLexicalIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::iterator()); } TSTLexicalIterator iterator() { return TSTLexicalIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::iterator()); } TSTLexicalIterator iterator(const string_type& string) { return TSTLexicalIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::iterator(string)); } TSTCloseMatchIterator close_match_iterator(const string_type& string, int distance) { return TSTCloseMatchIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::close_match_iterator(string,distance)); } using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::put; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::get; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::pack; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::walk; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::close_match; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::match; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::scan; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::scan_with_stop_chars; }; diff --git a/python/setup.py b/python/setup.py index fc7e7f5..ef52d05 100644 --- a/python/setup.py +++ b/python/setup.py @@ -1,51 +1,51 @@ # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from distutils.core import setup, Extension import sys -extra_compile_args = [] -if sys.platform == "win32" and sys.version >= '2.4': - extra_compile_args = '/Zp1 /Og /Ob2 /Oi /Ot /GS'.split() +extra_compile_args = ['-mdll'] +#if sys.platform == "win32" and sys.version >= '2.4': +# extra_compile_args = '/Zp1 /Og /Ob2 /Oi /Ot /GS'.split() setup( name = "pytst", - version = "1.15", + version = "1.16RC", author = "Nicolas Lehuen", author_email = "nicolas@lehuen.com", url = "http://nicolas.lehuen.com/index.php/category/Pytst", description = "An implementation of a Ternary Search Tree (TST) in C++ with Python bindings", py_modules = ["tst"], ext_modules = [ Extension( "_tst", ["tst_wrap.cxx"], include_dirs=['include'], extra_compile_args = extra_compile_args, define_macros=[('SCANNER', None),], ) ], download_url = "http://nicolas.lehuen.com/download/pytst/", classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: C++', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Scientific/Engineering :: Information Analysis', ] ) diff --git a/python/test/test.py b/python/test/test.py index d2ebef2..e043224 100644 --- a/python/test/test.py +++ b/python/test/test.py @@ -1,629 +1,683 @@ # -*- coding: iso-8859-1 -*- import sys -sys.path.insert(0,r"D:\projets\tst\python\Debug") +# sys.path.insert(0,r"D:\projets\tst\python\Debug") import unittest import os import random import string import datetime from time import time from itertools import izip from tst import * random.seed(0) def random_string(length): return ''.join([random.choice(string.letters) for x in xrange(length)]) from tcc.timer import Timer from tcc.util import levenshtein timers = {} def timer_start(name): timers.setdefault(name,Timer()).start() def timer_end(name,normalize=1.0): timers.setdefault(name,Timer()).stop(normalize) def print_timers(comment): keys = sorted(timers.keys()) for name in keys: print '%16s : %s'%(name,timers[name]) statsfilename = os.path.join(os.path.dirname(__file__),'stats.csv') if os.path.isfile(statsfilename): statsfile = file(statsfilename,'ab') else: statsfile = file(statsfilename,'wb') header = [ 'date', 'version', 'comment' ] for key in keys: header.append('%s:min'%key) header.append('%s:med'%key) header.append('%s:avg'%key) header.append('%s:max'%key) statsfile.write(';'.join(header)) statsfile.write('\n') row = [ datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S'), TST_VERSION, comment, ] for key in keys: timer = timers[key] row.append(('%7.4f'%timer.min).replace('.',',')) row.append(('%7.4f'%timer.med).replace('.',',')) row.append(('%7.4f'%timer.avg).replace('.',',')) row.append(('%7.4f'%timer.max).replace('.',',')) statsfile.write(';'.join(row)) statsfile.write('\n') class TestRefCount(unittest.TestCase): def setUp(self): self.a = 'toto' self.rc_a = sys.getrefcount(self.a) self.rc_None = sys.getrefcount(None) self.tree=TST() def testSetup(self): self.assertEqual(sys.getrefcount(None),self.rc_None+17) self.assertEqual(sys.getrefcount(self.a),self.rc_a) def testStore(self): self.tree[self.a]=self.a self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) def testOverwrite(self): self.tree[self.a]=self.a a2 = self.tree.put(self.a,'coucou') self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) del(a2) self.assertEqual(sys.getrefcount(self.a),self.rc_a) def testWalkList(self): l=self.tree.walk(None,ListAction()) self.assertEqual(sys.getrefcount(self.a),self.rc_a) self.tree[self.a]=self.a self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) l=self.tree.walk(None,ListAction()) self.assertEqual(sys.getrefcount(self.a),self.rc_a+2) del(l) self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) def testWalkDict(self): self.tree[self.a]=self.a self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) d=self.tree.walk(None,DictAction()) self.assertEqual(sys.getrefcount(self.a),self.rc_a+2) del(d) self.assertEqual(sys.getrefcount(self.a),self.rc_a+1) del self.tree[self.a] self.assertEqual(sys.getrefcount(self.a),self.rc_a) def testRemove(self): del(self.tree) self.assertEqual(sys.getrefcount(None),self.rc_None) self.assertEqual(sys.getrefcount(self.a),self.rc_a) class TestCollectors(unittest.TestCase): def setUp(self): self.tree = TST() self.keys = dict( a = 1, ab = 2, abc = 3, b = 4 ) for k,v in self.keys.iteritems(): self.tree[k] = v def testListAction(self): l = self.tree.walk(None,ListAction()) self.assertEqual(l,[1,2,3,4]) def testTupleListAction(self): l = self.tree.walk(None,TupleListAction()) self.assertEqual(l,[('a',0,1),('ab',0,2),('abc',0,3),('b',0,4)]) def testDictAction(self): l = self.tree.walk(None,DictAction()) self.assertEqual(l,dict(a=(0,1),ab=(0,2),abc=(0,3),b=(0,4))) def skey(): format = '%%.%if'%random.randint(1,10) return format%random.random() class TestBasics(unittest.TestCase): def setUp(self): self.tree = TST() self.keys = dict([ (skey(),random.random()) for x in xrange(250) ]) for k,v in self.keys.iteritems(): self.tree[k] = v def testGet(self): for k,v in self.keys.iteritems(): self.assertEqual(self.tree[k],v) def testWithRemove(self): for k in random.sample(self.keys,len(self.keys)/8): del self.keys[k] del self.tree[k] self.tree.pack() self.testGet() def testWithUpdate(self): for k in random.sample(self.keys,len(self.keys)/8): v = self.keys[k] nv = random.random() self.keys[k] = nv self.assertEqual(self.tree.put(k,nv),v) self.testGet() def testWalk(self): timer_start("walk") for i in xrange(100): d = self.tree.walk(None,DictAction()) timer_end("walk") for k,v in d.iteritems(): self.assertEquals(self.tree[k],v[1]) def testWalkWithRoot(self): ref = self.tree.walk(None,DictAction()) timer_start("walk_root") for i in xrange(100): d = self.tree.walk(None,DictAction(),'0.1') timer_end("walk_root") for k, v in ref.iteritems(): if k.startswith('0.1'): self.assert_(k in d) self.assertEquals(v,d[k]) for k, v in d.iteritems(): self.assert_(k.startswith('0.1')) self.assertEquals(self.tree[k],v[1]) def testCloseMatch(self): for k1 in self.keys.iterkeys(): timer_start("close_match") d = self.tree.close_match(k1,4,None,DictAction()) timer_end("close_match") for k2 in self.keys.iterkeys(): distance = levenshtein(k1,k2) if distance<=4: self.assert_(k2 in d,"Match manquant pour %s : %s (distance = %i)"%( k1, k2, distance, )) self.assert_(k2 in d and d[k2][0]==distance,"Mauvaise distance pour %s et %s : %i != %s"%( k1, k2, distance, d.get(k2)[0] )) else: self.assert_(k2 not in d,"Mauvaise distance pour %s et %s : %i > 4 mais trouvé %s"%( k1, k2, distance, d.get(k2) )) def testPrefixMatch(self): for k1 in self.keys.iterkeys(): timer_start("prefix_match") d = self.tree.prefix_match(k1[:len(k1)/2],None,DictAction()) timer_end("prefix_match") self.assert_(k1 in d,"Une cle manque dans un prefix_match pour %s"%(k1,)) k2 = k1 + k1 timer_start("prefix_match") d = self.tree.prefix_match(k2,None,DictAction()) timer_end("prefix_match") self.assert_(k2 not in d,"Une cle manque dans un prefix_match pour %s"%(k1,)) def testWriteRead(self): self.tree.write_to_file('test.tst') self.tree = TST() self.tree.read_from_file('test.tst') self.testGet() class TestMatch(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['abc'] = 'abc' self.tree['ab'] = 'ab' self.tree['a'] = 'a' self.tree['bbc'] = 'bbc' self.tree['efgfjhny'] = 'ok' def testJoker1(self): d = self.tree.match("a?c",None,DictAction()) self.assertEquals(d,dict(abc=(0,"abc"))) def testJoker2(self): d = self.tree.match("???",None,DictAction()) self.assertEquals(d,{'abc': (0, 'abc'), 'bbc': (0, 'bbc')}) def testJoker3(self): d = self.tree.match("??",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab')}) def testStar1(self): d = self.tree.match("a*c",None,DictAction()) self.assertEquals(d,dict(abc=(0,"abc"))) def testStar2(self): d = self.tree.match("a*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'abc': (0, 'abc')}) def testStar2_1(self): d = self.tree.match("ab*",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab'), 'abc': (0, 'abc')}) def testStar2_2(self): d = self.tree.match("*b",None,DictAction()) self.assertEquals(d,{'ab': (0, 'ab')}) d = self.tree.match("*bbc",None,DictAction()) self.assertEquals(d,{'bbc': (0, 'bbc')}) def testStar3(self): d = self.tree.match("*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) d = self.tree.match("*?*",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) def testStar3_1(self): d = self.tree.match("**",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) d = self.tree.match("***",None,DictAction()) self.assertEquals(d,{'a': (0, 'a'), 'ab': (0, 'ab'), 'bbc': (0, 'bbc'), 'abc': (0, 'abc'), 'efgfjhny': (0, 'ok')}) def testStar4(self): d = self.tree.match("e*ny",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar5(self): d = self.tree.match("*****y",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar6(self): d = self.tree.match("????*",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) def testStar7(self): d = self.tree.match("ef?f*n?",None,DictAction()) self.assertEquals(d,{'efgfjhny': (0, 'ok')}) class TestIterators(unittest.TestCase): def setUp(self): self.tree = TST() self.keys = dict( titi = 1, toto = 2, tati = 3, a = 5 ) for k, v in self.keys.iteritems(): self.tree[k] = v def testLexical1(self): d = {} for k, v in self.tree: d[k] = v self.assertEqual(d,self.keys) def testLexical2(self): d = {} for k, v in self.tree.iterator('t'): d[k] = v self.keys.pop('a') self.assertEqual(d,self.keys) def testCloseMatch(self): d = {} for k, v in self.tree.close_match_iterator('t',1): d[k] = v self.assertEqual(d,dict( a = 5 )) d = {} for k, v in self.tree.close_match_iterator('tito',1): d[k] = v self.assertEqual(d,dict( titi = 1, toto = 2 )) d = {} for k, v in self.tree.close_match_iterator('tuto',1): d[k] = v self.assertEqual(d,dict( toto = 2 )) +class TestCallableAction(unittest.TestCase): + def setUp(self): + self.tree = TST() + self.tree['foo'] = 'bar' + + def testCA1(self): + res = {} + + def callback(key, length, obj): + res[key] = obj + + def result(): + res['hello'] = 'world' + return res + + self.assertEqual( + self.tree.walk(None, CallableAction(callback, result)), + {'foo':'bar', 'hello':'world'} + ) + + def testCA2(self): + res = {} + + def callback(key, length, obj): + # Provoke an exception + print 0 / 0 + res[key] = obj + + def result(): + return res + + try: + self.tree.walk(None, CallableAction(callback, result)), + self.fail("Should have raised an exception") + except: + pass + + def testCA3(self): + res = {} + + def callback(key, length, obj): + res[key] = obj + + def result(): + # Provoke an exception + return 0/0 + + try: + self.tree.walk(None, CallableAction(callback, result)), + self.fail("Should have raised an exception") + except: + pass + class TestHighCapacity(unittest.TestCase): def setUp(self): tree = TST() timer_start('build_big') keys = map(str,xrange(100000)) random.shuffle(keys) timer_end('build_big') timer_start('write_big') for k in keys: tree[k] = k timer_end('write_big') self.keys, self.tree = keys, tree def testGet(self): timer_start('read_big') for k in self.keys: self.assertEqual(self.tree[k],k) timer_end('read_big') def testFullPack(self): timer_start('delete_full') for k in self.keys: del self.tree[k] timer_end('delete_full') self.tree.pack() for k in self.keys: self.assertEqual(self.tree[k],None) sample = random.sample(self.keys,len(self.keys)/10) random.shuffle(sample) timer_start('refill_post_pack/10') for k in sample: self.tree[k] = k timer_end('refill_post_pack/10',10) for k in sample: self.assertEqual(self.tree[k],k) del self.tree[k] self.tree.pack() for k in self.keys: self.assertEqual(self.tree[k],None) self.tree.write_to_file('test.tst') def testDelete(self): sample = random.sample(self.keys,len(self.keys)/10) random.shuffle(sample) timer_start('delete_big/10') for k in sample: del self.tree[k] timer_end('delete_big/10',10) random.shuffle(sample) timer_start('refill_pre_pack/10') for k in sample: self.tree[k] = k timer_end('refill_pre_pack/10',10) self.testGet() random.shuffle(sample) timer_start('delete_big/10') for k in sample: del self.tree[k] timer_end('delete_big/10',10) self.tree.pack() random.shuffle(sample) timer_start('refill_post_pack/10') for k in sample: self.tree[k] = k timer_end('refill_post_pack/10',10) self.testGet() timer_start('delete_big/10') for k in self.keys[:len(self.keys)/10]: del self.tree[k] timer_end('delete_big/10',10) timer_start('pack/10') self.tree.pack() timer_end('pack/10',10) timer_start('check_delete_big') for k in self.keys[:len(self.keys)/10]: self.assertEqual(self.tree[k],None) for k in self.keys[len(self.keys)/10+1:]: self.assertEqual(self.tree[k],k) timer_end('check_delete_big') def testUpdate(self): timer_start('build_big/10') old_keys = self.keys[:len(self.keys)/10] new_keys = map(lambda x:str(int(x) + 1),old_keys) timer_end('build_big/10',10) timer_start('update_big/10') for k,kp in izip(old_keys,new_keys): self.assertEqual(self.tree.put(k,kp),k) timer_end('update_big/10',10) timer_start('check_update_big') for k,kp in izip(old_keys,new_keys): self.assertEqual(self.tree[k],kp) timer_end('check_update_big') class TestScan(unittest.TestCase): def setUp(self): self.tree = TST() self.tree['Nicolas']='Nicolas' self.tree['olaf']='olaf' self.tree['lazlo']='lazlo' self.tree['Nicolas-Antoinette']='Nicolas-Antoinette' self.tree['Antoinette']='Antoinette' self.tree['Antoine']='Antoine' self.tree['astride']='astride' self.tree['VICTOIRE']='VICTOIRE' self.tree['IAN']='IAN' self.tree['x']='x' self.tree['V']='V' self.tree['ROBERT']='ROBERT' self.tree['A N']='A N' self.tree['olaaf']='olaaf' self.tree['laslo']='laslo' def testScanMikeThornton(self): t = TST() t['ccc'] = 1 self.assertEqual(t.scan('cc',TupleListAction()),[('cc',-2,None)]) self.assertEqual(t.scan('ccd',TupleListAction()),[('ccd',-3,None)]) def testScan0_1(self): self.assertEqual(self.tree.scan('Nicolas',TupleListAction()),[('Nicolas', 7, 'Nicolas'),]) def testScan0_2(self): self.assertEqual(self.tree.scan(' Nicolas',TupleListAction()),[(' ',-1,None),('Nicolas', 7, 'Nicolas'),]) def testScan0_3(self): self.assertEqual(self.tree.scan('Nicolas ',TupleListAction()),[('Nicolas', 7, 'Nicolas'),(' ',-1,None),]) def testScan0_4(self): self.assertEqual(self.tree.scan(' Nicolas ',TupleListAction()),[(' ',-1,None),('Nicolas', 7, 'Nicolas'),(' ',-1,None),]) def testScan0_5(self): self.assertEqual(self.tree.scan(' ',TupleListAction()),[(' ',-1,None),]) def testScan0_6(self): self.assertEqual(self.tree.scan('la',TupleListAction()),[('la', -2, None)]) def testScan0_7(self): self.assertEqual(self.tree.scan('lazl',TupleListAction()),[('lazl', -4, None)]) def testScan1(self): timer_start("scan") for i in xrange(10000): self.assertEqual(self.tree.scan('lazlo',TupleListAction()),[('lazlo', 5, 'lazlo')]) self.assertEqual(self.tree.scan('Nicolazlo',TupleListAction()),[('Nico', -4, None), ('lazlo', 5, 'lazlo')]) timer_end("scan") def testScan24(self): self.assertEqual(self.tree.scan('A NicoNicoNicolasNicoNico',TupleListAction()),[('A N', 3, 'A N'), ('icoNico', -7, None), ('Nicolas', 7, 'Nicolas'), ('NicoNico', -8, None)]) def testScan1_1(self): self.assertEqual(self.tree.scan('hippocampe',TupleListAction()),[('hippocampe', -10, None)]) def testScan2(self): self.assertEqual(self.tree.scan('NicolaNicolaNicolaNicolaNicola',TupleListAction()),[('NicolaNicolaNicolaNicolaNicola', -30, None)]) def testScan3(self): self.assertEqual(self.tree.scan('Nicolasstupide',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('stupide', -7, None)]) def testScan4(self): self.assertEqual(self.tree.scan('Nicolast',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('t', -1, None)]) def testScan5(self): self.assertEqual(self.tree.scan('xxxNicolas',TupleListAction()),[('x', 1, 'x'), ('x', 1, 'x'), ('x', 1, 'x'), ('Nicolas', 7, 'Nicolas')]) def testScan6(self): self.assertEqual(self.tree.scan('xxx Nicolas',TupleListAction()),[('x', 1, 'x'), ('x', 1, 'x'), ('x', 1, 'x'), (' ', -1, None), ('Nicolas', 7, 'Nicolas')]) def testScan7(self): self.assertEqual(self.tree.scan('Antoinette Antoinette',TupleListAction()),[('Antoinette', 10, 'Antoinette'), (' ', -1, None), ('Antoinette', 10, 'Antoinette')]) def testScan8(self): self.assertEqual(self.tree.scan('Nicolas-Antoinette',TupleListAction()),[('Nicolas-Antoinette', 18, 'Nicolas-Antoinette')]) def testScan9(self): self.assertEqual(self.tree.scan('Nicolas-Antoine',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) def testScan9_1(self): self.assertEqual(self.tree.scan('Nicolas-Antoine-Antoine',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) def testScan9_2(self): self.assertEqual(self.tree.scan('Nicolas-Antoine-Antoine-',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('-', -1, None)]) def testScan10(self): self.assertEqual(self.tree.scan('Nicolas-Antoinet',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine'), ('t', -1, None)]) def testScanWithStopChars1(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolas',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas')]) def testScanWithStopChars2(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolasstupide',' -',TupleListAction()),[('Nicolasstupide', -14, None)]) def testScanWithStopChars25(self): timer_start("scan_stop_chars") for i in xrange(10000): self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) self.assertEqual(self.tree.scan_with_stop_chars('A Nico trlalaA Nico Nico Nico Nicolas Nico Nicol Nicol Nico',' ',TupleListAction()),[('A Nico trlalaA Nico Nico Nico ', -30, None), ('Nicolas', 7, 'Nicolas'), (' Nico Nicol Nicol Nico', -22, None)]) timer_end("scan_stop_chars") def testScanWithStopChars3(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolast',' -',TupleListAction()),[('Nicolast', -8, None)]) def testScanWithStopChars4(self): self.assertEqual(self.tree.scan_with_stop_chars('xxxNicolas',' -',TupleListAction()),[('xxxNicolas', -10, None)]) def testScanWithStopChars5(self): self.assertEqual(self.tree.scan_with_stop_chars('xxx Nicolas',' -',TupleListAction()),[('xxx ', -4, None),('Nicolas', 7, 'Nicolas')]) def testScanWithStopChars6(self): self.assertEqual(self.tree.scan_with_stop_chars('xxxAntoine Nicolas',' -',TupleListAction()),[('xxxAntoine ', -11, None),('Nicolas', 7, 'Nicolas')]) def testScanWithStopChars8(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoinette',' -',TupleListAction()),[('Nicolas-Antoinette', 18, 'Nicolas-Antoinette')]) def testScanWithStopChars9(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoine',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-', -1, None), ('Antoine', 7, 'Antoine')]) def testScanWithStopChars10(self): self.assertEqual(self.tree.scan_with_stop_chars('Nicolas-Antoinet',' -',TupleListAction()),[('Nicolas', 7, 'Nicolas'), ('-Antoinet', -9, None)]) def testScanVicieux(self): self.assertEqual(self.tree.scan_with_stop_chars('xxxAntoine A Nicolas',' -',TupleListAction()),[('xxxAntoine A ', -13, None),('Nicolas', 7, 'Nicolas')]) def testScanVicieux2(self): self.assertEqual(self.tree.scan_with_stop_chars('Antoinette Antoinette',' -',TupleListAction()),[('Antoinette', 10, 'Antoinette'), (' ', -1, None), ('Antoinette', 10, 'Antoinette')]) def testScanVicieux3(self): self.assertEqual(self.tree.scan_with_stop_chars('nastride lazlo',' -',TupleListAction()),[('nastride ', -9, None), ('lazlo', 5, 'lazlo')]) self.assertEqual(self.tree.scan_with_stop_chars('VIAN ROBERT',' -',TupleListAction()),[('VIAN ', -5, None), ('ROBERT', 6, 'ROBERT')]) if __name__ == '__main__': print "Testing pytst %s"%TST_VERSION comment = ' '.join(sys.argv[1:]) suite = unittest.TestSuite(( unittest.makeSuite(TestCollectors), unittest.makeSuite(TestBasics), unittest.makeSuite(TestHighCapacity), unittest.makeSuite(TestScan), unittest.makeSuite(TestIterators), unittest.makeSuite(TestMatch), + unittest.makeSuite(TestCallableAction), )) for i in xrange(3): unittest.TextTestRunner().run(suite) print_timers(comment)
nlehuen/pytst
c61db0a85bd5dfce99975ed4b73c645a130dfbf1
Version 1.15.
diff --git a/include/tst.h b/include/tst.h index 3b2b53c..9e819c0 100644 --- a/include/tst.h +++ b/include/tst.h @@ -1,534 +1,534 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __TST__H_INCLUDED__ #define __TST__H_INCLUDED__ -const char* const TST_VERSION = "1.14"; +const char* const TST_VERSION = "1.15"; #include "debug.h" #include <iostream> #ifdef __PYTHON__BUILD__ #include "Python.h" #define tst_malloc PyMem_Malloc #define tst_realloc PyMem_Realloc #define tst_free PyMem_Free // Pour ajouter/supprimer les fonctions de scanning. // #define SCANNER #else #include "stdlib.h" #define tst_malloc malloc #define tst_realloc realloc #define tst_free free // Pour ajouter/supprimer les fonctions de scanning. // #define SCANNER #endif template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst; #include "fundamentals.h" #include "memory_storage.h" #include "iterators.h" template < typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> class tst { public: friend class lexical_iterator<charT,valueT,storageT,serializerT,stringT>; friend class match_iterator<charT,valueT,storageT,serializerT,stringT>; typedef charT character_type; typedef valueT value_type; typedef storageT storage_type; typedef serializerT serializer_type; tst(); virtual ~tst() { delete storage; } void pack() { storage->pack(root); } valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT walk(tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,const stringT & string) const; valueT close_match(const stringT & string,int maximum_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT prefix_match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT match(const stringT & string,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; valueT get(const stringT & string) const; valueT get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory); valueT put(const stringT & string,valueT data); void remove(const stringT & string); bool contains(const stringT & string) const; void write(std::ostream &file) const; void read(std::istream &file); lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator() const { stringT key; return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,key,root); } lexical_iterator<charT,valueT,storageT,serializerT,stringT> iterator(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; find_node(&current_index,&best_node,string); return lexical_iterator<charT,valueT,storageT,serializerT,stringT>(this,string.substr(0,string.size()-1),current_index); } match_iterator<charT,valueT,storageT,serializerT,stringT> close_match_iterator(const stringT & string,int distance) const { return match_iterator<charT,valueT,storageT,serializerT,stringT>(this,string,distance,root); } int get_number_of_nodes() const { return storage->size(); } valueT get_default_value() const { return default_value; } #ifdef SCANNER valueT scan(const stringT & string,tst_action<charT,valueT,stringT>* to_perform); valueT scan_with_stop_chars(const stringT & string,const stringT& stop_chars,tst_action<charT,valueT,stringT>* to_perform) const; #endif protected: void set_storage(storageT* new_storage) { delete storage; storage = new_storage; } private: storageT* storage; valueT default_value; int root; void walk_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void close_match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,const size_t position, const int distance, const int remaining_distance,tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform) const; void match_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_joker_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; void match_star_recurse(tst_node<charT,valueT>* current_node,stringT & current_key,const stringT & string,size_t position, tst_filter<charT,valueT,stringT>* filter,tst_action<charT,valueT,stringT>* to_perform,bool advance) const; int build_node(node_info<charT,valueT>* current_node,const stringT & string,size_t current_position); void remove_node(int* current_index,const stringT & string,const size_t position); tst_node<charT,valueT>* find_node(int* current_index,int* best_node, const stringT & string) const; void balance_node(node_info<charT,valueT>* bal); void ll(node_info<charT,valueT>* bal); void rr(node_info<charT,valueT>* bal); void lr(node_info<charT,valueT>* bal); void rl(node_info<charT,valueT>* bal); void compute_height_and_balance(node_info<charT,valueT>* current_node_info) const; void write_node(std::ostream& file,serializerT* writer,int index) const; int read_node(std::istream& file,serializerT* reader,int depth); #ifdef SCANNER void compute_backtrack(tst_node<charT,valueT> *current_node,const stringT & string,int si_match_start,int si_match_end); #endif }; template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst<charT,valueT,storageT,serializerT,stringT>::tst() : storage(new storage_type(16)), default_value() { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } /*************************** high-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return current_node->data; } else { return default_value; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> bool tst<charT,valueT,storageT,serializerT,stringT>::contains(const stringT & string) const { int current_index=root,best_node=UNDEFINED_INDEX; tst_node<charT,valueT>* current_node=find_node(&current_index,&best_node,string); if(current_node) { return true; } else { return false; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::put(const stringT & string,valueT data) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; return storage->get(node_index)->store(data); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::get_or_build(const stringT & string,tst_filter<charT,valueT,stringT>* factory) { node_info<charT,valueT> root_info; root_info.index=root; root_info.node=storage->get(root); int node_index=build_node(&root_info,string,0); root = root_info.index; tst_node<charT,valueT>* current_node=storage->get(node_index); valueT data = current_node->data; if(data==default_value) { data=factory->perform(string,0,current_node->data); current_node->store(data); return data; } else { return data; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove(const stringT & string) { remove_node(&root,string,0); if(root==UNDEFINED_INDEX) { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } } /**************************** low-level tree management ***********************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> tst_node<charT,valueT>* tst<charT,valueT,storageT,serializerT,stringT>::find_node(int* current_index,int* best_node,const stringT & string) const { tst_node<charT,valueT>* current_node; int diff; size_t pos=0; while(*current_index!=UNDEFINED_INDEX) { current_node=storage->get(*current_index); if(current_node->c==0) { *current_index=UNDEFINED_INDEX; return 0; } else { diff=string[pos]-(current_node->c); } if(diff==0) { if(current_node->data!=default_value) { *best_node=*current_index; } ++pos; if(pos<string.size()) { *current_index = current_node->next; } else { return current_node; } } else if(diff>0) { *current_index=current_node->right; } else { *current_index=current_node->left; } } return 0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> int tst<charT,valueT,storageT,serializerT,stringT>::build_node(node_info<charT,valueT>* current_node_info,const stringT & string,size_t current_position) { int diff,result; if(current_node_info->node->c==0) { current_node_info->node->c=string[current_position]; #ifdef SCANNER current_node_info->node->position=current_position; #endif diff=0; } else { diff=string[current_position]-(current_node_info->node->c); } current_node_info->height=-1; current_node_info->balance_performed=0; if(diff==0) { ++current_position; compute_height_and_balance(current_node_info); // TODO : est-ce bien necessaire ? if(current_position<string.size()) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->next; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->next = next_node_info.index; return result; } else { return current_node_info->index; } } else if(diff>0) { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->right; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->right = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->left==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = next_node_info.height; current_node_info->left_balance = 0; current_node_info->right_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->left; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = next_node_info.height-other_node_info.height; current_node_info->left_balance = other_node_info.balance; current_node_info->right_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } else { node_info<charT,valueT> next_node_info; next_node_info.index = current_node_info->node->left; if(next_node_info.index==UNDEFINED_INDEX) { storage->new_node(&next_node_info); } else { next_node_info.node = storage->get(next_node_info.index); } result=build_node(&next_node_info,string,current_position); current_node_info->node = storage->get(current_node_info->index); current_node_info->node->left = next_node_info.index; if(next_node_info.balance_performed) { current_node_info->balance_performed=1; } else { if(current_node_info->node->right==UNDEFINED_INDEX) { current_node_info->height = next_node_info.height + 1; current_node_info->balance = -next_node_info.height; current_node_info->right_balance = 0; current_node_info->left_balance = next_node_info.balance; } else { node_info<charT,valueT> other_node_info; other_node_info.index = current_node_info->node->right; other_node_info.node = storage->get(other_node_info.index); compute_height_and_balance(&other_node_info); if(other_node_info.height>next_node_info.height) { current_node_info->height=other_node_info.height+1; } else { current_node_info->height=next_node_info.height+1; } current_node_info->balance = other_node_info.height-next_node_info.height; current_node_info->right_balance = other_node_info.balance; current_node_info->left_balance = next_node_info.balance; } balance_node(current_node_info); } return result; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::remove_node(int* current_index,const stringT & string,const size_t current_position) { tst_node<charT,valueT>* current_node = storage->get(*current_index); int diff,*next_index; if(current_node->c==0) { return; } else { diff=string[current_position]-(current_node->c); } if(diff==0) { if(current_position+1<string.size()) { next_index = &(current_node->next); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position+1); } } else { current_node->store(default_value); } } else if(diff>0) { next_index = &(current_node->right); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } else { next_index = &(current_node->left); if(*next_index!=UNDEFINED_INDEX) { remove_node(next_index,string,current_position); } } current_node=storage->get(*current_index); if( current_node->data==default_value && current_node->next==UNDEFINED_INDEX && current_node->right==UNDEFINED_INDEX && current_node->left==UNDEFINED_INDEX) { storage->delete_node(*current_index); *current_index=UNDEFINED_INDEX; } else { node_info<charT,valueT> current_node_info; current_node_info.index=*current_index; current_node_info.node=current_node; current_node_info.height=-1; balance_node(&current_node_info); *current_index = current_node_info.index; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::balance_node(node_info<charT,valueT>* bal) { if(bal->height==-1) { compute_height_and_balance(bal); } bal->balance_performed=0; if(bal->balance>1) { if(bal->right_balance>0) { rr(bal); } else { rl(bal); } bal->balance_performed=1; } else if(bal->balance<-1) { if(bal->left_balance<0) { ll(bal); } else { lr(bal); } bal->balance_performed=1; } assert(abs(bal->balance)<2); assert(abs(bal->right_balance)<2); assert(abs(bal->left_balance)<2); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::ll(node_info<charT,valueT>* bal) { int left_index=bal->node->left; tst_node<charT,valueT>* left_node=storage->get(left_index); int left_right_index=left_node->right; bal->node->left=left_right_index; left_node->right=bal->index; bal->index=left_index; bal->node=storage->get(left_index); bal->height=bal->height-1; bal->balance=0; bal->right_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rr(node_info<charT,valueT>* bal) { int right_index=bal->node->right; tst_node<charT,valueT>* right_node=storage->get(right_index); int right_left_index=right_node->left; bal->node->right=right_left_index; right_node->left=bal->index; bal->index=right_index; bal->node=storage->get(right_index); bal->height=bal->height-1; bal->balance=0; bal->left_balance=0; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::lr(node_info<charT,valueT>* bal) { node_info<charT,valueT> left; left.index = bal->node->left; left.node = storage->get(left.index); rr(&left); bal->node->left=left.index; ll(bal); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::rl(node_info<charT,valueT>* bal) { node_info<charT,valueT> right; right.index = bal->node->right; right.node = storage->get(right.index); ll(&right); bal->node->right=right.index; rr(bal); }
nlehuen/pytst
2308eb44ca83f15b4bebf27a6cd8ced53f64f6dc
Correction from Thomas Brox Rost (thomas@broxrost.com).
diff --git a/python/pythonTST.h b/python/pythonTST.h index 1cbf11d..77bccae 100644 --- a/python/pythonTST.h +++ b/python/pythonTST.h @@ -1,323 +1,323 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define __PYTHON__BUILD__ #include "tst.h" #include "Python.h" #include "PythonReference.h" #include "qad_string.h" #include <iostream> #include <fstream> #ifdef ZIPPED_TREE #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/zlib.hpp> #endif typedef qad_string<char> string_type; class CallableAction : public tst_action<char,PythonReference,string_type > { public: CallableAction(PythonReference perform,PythonReference result) : _perform(perform), _result(result) { } virtual ~CallableAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { if(_perform.get()==Py_None) { return; } PythonReference tuple(Py_BuildValue("s#iO",string.data(),string.size(),remaining_distance,data.get()),0); Py_DECREF(PyObject_CallObject(_perform.get(),tuple.get())); } virtual PythonReference result() { if(_result.get()==Py_None) { return PythonReference(); } else { return PythonReference(PyObject_CallObject(_result.get(),0),0); } } private: PythonReference _perform,_result; }; class CallableFilter : public tst_filter<char,PythonReference,string_type > { public: CallableFilter(PythonReference _callable) : callable(_callable) { } virtual ~CallableFilter() { } virtual PythonReference perform(const string_type& string,int remaining_distance,PythonReference data) { PythonReference tuple(Py_BuildValue("s#iO",string.data(),string.size(),remaining_distance,data.get()),0); return PythonReference(PyObject_CallObject(callable.get(),tuple.get()),0); } private: PythonReference callable; }; class DictAction : public tst_action<char,PythonReference,string_type > { public: DictAction() : dict(PyDict_New(),0) { } virtual ~DictAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { PythonReference key(Py_BuildValue("s#",string.data(),string.size()),0); PyObject* old_tuple=PyDict_GetItem(dict.get(),key.get()); if(old_tuple!=0) { long value=PyInt_AsLong(PyTuple_GetItem(old_tuple,0)); if(value<remaining_distance) { return; } } PythonReference tuple(Py_BuildValue("iO",remaining_distance,data.get()),0); PyDict_SetItem(dict.get(),key.get(),tuple.get()); }; virtual PythonReference result() { return dict; } private: PythonReference dict; }; class ListAction : public tst_action<char,PythonReference,string_type > { public: ListAction() : list(PyList_New(0),0) { } virtual ~ListAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { PyList_Append(list.get(),data.get()); } virtual PythonReference result() { return list; } private: PythonReference list; }; class TupleListAction : public tst_action<char,PythonReference,string_type > { public: TupleListAction() : list(PyList_New(0),0){ } virtual ~TupleListAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { PythonReference tuple(Py_BuildValue("s#iO",string.data(),string.size(),remaining_distance,data.get()),0); PyList_Append(list.get(),tuple.get()); } virtual PythonReference result() { return list; } private: PythonReference list; }; class ObjectSerializer { public: ObjectSerializer(); void write(std::ostream& file,PythonReference data); - PythonReference ObjectSerializer::read(std::istream& file); + PythonReference read(std::istream& file); private: PythonReference dumps,loads; }; ObjectSerializer::ObjectSerializer() { PythonReference name(PyString_FromString("cPickle"),0); PythonReference cPickle(PyImport_Import(name.get()),0); dumps = PythonReference(PyObject_GetAttrString(cPickle.get(),"dumps"),0); loads = PythonReference(PyObject_GetAttrString(cPickle.get(),"loads"),0); } void ObjectSerializer::write(std::ostream& file,PythonReference data) { PythonReference call(Py_BuildValue("Oi",data.get(),2),0); PythonReference result(PyObject_CallObject(dumps.get(),call.get()),0); char *string; int length; PyString_AsStringAndSize(result.get(),&string,&length); file.write((char*)(&length),sizeof(int)); file.write(string,length); } PythonReference ObjectSerializer::read(std::istream& file) { int length; file.read((char*)(&length),sizeof(int)); char* string=(char*)tst_malloc(length); file.read(string,length); PythonReference dumped(PyString_FromStringAndSize(string,length),0); PythonReference call(Py_BuildValue("(O)",dumped.get()),0); PythonReference result(PyObject_CallObject(loads.get(),call.get()),0); tst_free(string); return result; } class TST; template <typename iterator_type> class TSTIterator { public: friend class TST; TSTIterator __iter__() { return *this; } PyObject* next() { typename iterator_type::value_type v(iterator.next()); if(v.second) { return Py_BuildValue("s#O",v.first.data(),v.first.size(),v.second->get()); } else { PythonReference exceptions(PyImport_ImportModule("exceptions"),0); PythonReference stop_iteration = exceptions.getattr("StopIteration"); PyErr_SetNone(stop_iteration.get()); return 0; } } private: TSTIterator(iterator_type i) : iterator(i) { } iterator_type iterator; }; typedef TSTIterator<lexical_iterator<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > > TSTLexicalIterator; typedef TSTIterator<match_iterator<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > > TSTCloseMatchIterator; class TST : private tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > { public: TST() : tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >() { } virtual ~TST() { } virtual PythonReference write_to_file(PythonReference file) { if(!PyString_CheckExact(file.get())) { throw TSTException("Argument of write_to_file() must be a string object"); } std::ofstream out(PyString_AsString(file.get()),std::ofstream::binary|std::ofstream::out|std::ofstream::trunc); out.exceptions(std::ofstream::eofbit | std::ofstream::failbit | std::ofstream::badbit); #ifdef ZIPPED_TREE boost::iostreams::filtering_ostream fout; fout.push(boost::iostreams::zlib_compressor()); fout.push(out); this->write(fout); fout.strict_sync(); #else this->write(out); #endif out.close(); return PythonReference(); } virtual PythonReference read_from_file(PythonReference file) { if(!PyString_CheckExact(file.get())) { throw TSTException("Argument of read_from_file() must be a string object"); } std::ifstream in(PyString_AsString(file.get()),std::ifstream::binary|std::ifstream::in); in.exceptions(std::ifstream::eofbit | std::ifstream::failbit | std::ifstream::badbit); #ifdef ZIPPED_TREE boost::iostreams::filtering_istream fin; fin.push(boost::iostreams::zlib_decompressor()); fin.push(in); this->read(fin); #else this->read(in); #endif in.close(); return PythonReference(); } PythonReference __getitem__(const string_type& string) { return get(string); } PythonReference __setitem__(const string_type& string,PythonReference data) { return put(string,data); } void __delitem__(const string_type& string) { remove(string); } PythonReference __contains__(const string_type& string) { if(contains(string)) { return PythonReference(Py_False); } else { return PythonReference(Py_True); } } TSTLexicalIterator __iter__() { return TSTLexicalIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::iterator()); } TSTLexicalIterator iterator() { return TSTLexicalIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::iterator()); } TSTLexicalIterator iterator(const string_type& string) { return TSTLexicalIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::iterator(string)); } TSTCloseMatchIterator close_match_iterator(const string_type& string, int distance) { return TSTCloseMatchIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::close_match_iterator(string,distance)); } using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::put; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::get; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::pack; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::walk; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::close_match; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::match; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::scan; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::scan_with_stop_chars; };
nlehuen/pytst
b092e109d5b2e5a3cade2cb2cbd99cdff84472f3
Modification pour que ça compile sous Python 2.5.
diff --git a/python/build.bat b/python/build.bat index acb8dbb..cca605b 100644 --- a/python/build.bat +++ b/python/build.bat @@ -1,7 +1,7 @@ rmdir /s /q build include mkdir include & xcopy ..\include include copy ..\include\LICENSE . -swig -O -Iinclude -DSCANNER -c++ -python tst.i +rem swig -O -Iinclude -DSCANNER -c++ -python tst.i del MANIFEST python setup.py clean sdist bdist_wininst rmdir /s /q build include diff --git a/python/compacttst.py b/python/compacttst.py index 12a5994..0693b8e 100644 --- a/python/compacttst.py +++ b/python/compacttst.py @@ -1,607 +1,605 @@ # -*- coding: iso-8859-1 -*- from array import array import sys # Tant qu'à faire vu qu'ici le nombre de caractères par noeud est complètement # dynamique, on peut se lâcher, mettre 1024 caractère ou plus CHARS_PER_NODE = 1024 class tst_node(object): """ classe représentant un noeud du TST """ # __slots__ est une optimisation permettant de créer des objets Python # non dynamiques, ce qui utilise moins de mémoire __slots__ = ['chars','data','next','left','right'] instances = 0 def __init__(self): tst_node.instances += 1 self.chars = array('c') self.data = None self.next = None self.left = None self.right = None def __repr__(self): return "node(%s,data=%s,%i,%i,%i)"%( self.chars, self.data, self.left is not None and 1 or 0, self.next is not None and 1 or 0, self.right is not None and 1 or 0, ) class balance_info(object): __slots__ = ['did_balance','height','balance','right_balance','left_balance'] def __init__(self,did_balance=False,height=0,balance=0,right_balance=0,left_balance=0): self.did_balance = did_balance self.height = height self.balance = balance self.right_balance = right_balance self.left_balance = left_balance def __repr__(self): return "balance_info(d=%s,h=%s,b=%s,l=%s,r=%s)"%( self.did_balance, self.height, self.balance, self.left_balance, self.right_balance ) class compact_tst(object): """ Implémentation d'un TST compact """ def __init__(self): self.root = None def __getitem__(self,string): """ Lit dans l'arbre selon la syntaxe tst[string] """ # ATTENTION : ce code est intentionnellement dupliqué dans la méthode # visit(). Ne pas oublier de mettre celle-ci à jour lorsqu'il est modifié # ici. node = self.root index = 0 while node is not None: local_index = 0 # On avance tant qu'il y a égalité diff = 0 while local_index < len(node.chars) and index < len(string): diff = cmp(string[index],node.chars[local_index]) if diff == 0: local_index += 1 index += 1 else: break if diff != 0: # On a une différence de caractère if local_index < len(node.chars) - 1: # on s'est arrêté avant le dernier caractère du noeud, # il n'y a donc pas de match possible (sinon il y aurait eu # split à l'insertion) return None - else: - # différence au dernier caractère du noeud - if diff>0: + elif diff>0: node = node.left - elif diff<0: - node = node.right + else: # diff<0 + node = node.right elif local_index == len(node.chars): # On est au bout des caractères du noeud if index == len(string): # On est également au bout de la clé # C'est qu'on a de la chance ! return node.data else: # On avance d'un cran node = node.next else: # On n'est pas au bout des caractères, c'est qu'on est au # bout de la clé, et donc qu'il n'y a pas de match, sinon # il y aurait eu un split assert index == len(string) return None # node is None ==> pas de match return None def __setitem__(self,string,value): """ Ecrit dans l'arbre selon la syntaxe tst[string] = value """ self.root, discard = self._insert(string,value,0,self.root) assert self[string] == value def _insert(self,string,value,index,node): if node is None: return self._new_node(string,value,index) local_index = 0 # On avance tant qu'il y a égalité diff = 0 while local_index < len(node.chars) and index<len(string): diff = cmp(string[index],node.chars[local_index]) if diff == 0: local_index += 1 index += 1 else: break if diff!=0: assert local_index < len(node.chars) and index<len(string) # On a trouvé un point de divergence avant le dernier caractère du # noeud, et de la clé, il va donc falloir splitter if local_index < len(node.chars) - 1: node, balance = self._split_node(node,local_index) # On peut essayer de joindre le noeud suivant au noeud d'après # car le split peut permettre de compléter un noeud pas totalement # remplit node.next, discard = self._compact_node(node.next,None) # Maintenant que le split est fait, on peut continuer à positionner # la nouvelle clé balance = balance_info() if diff>0: node.left, left_balance = self._insert(string,value,index,node.left) balance.did_balance = left_balance.did_balance right_balance = self._compute_balance(node.right) else: node.right, right_balance = self._insert(string,value,index,node.right) balance.did_balance = right_balance.did_balance left_balance = self._compute_balance(node.left) # On calcule la nouvelle balance en tenant compte des modifs if len(node.chars)>1: balance.height = 1 else: balance.height = max(left_balance.height, right_balance.height) + 1 balance.balance = left_balance.height - right_balance.height balance.left_balance = left_balance.balance balance.right_balance = right_balance.balance if not balance.did_balance: # On effectue la balance si elle n'a pas déjà été effectuée node, balance = self._balance(node,balance) if len(node.chars)!=1: # Si à l'issue de la balance on se retrouve avec plusieurs # caractères, alors la hauteur du nouveau noeud est 1. balance.height = 1 balance.balance = 0 balance.left_balance = 0 balance.right_balance = 0 return node, balance elif local_index == len(node.chars): # On est arrivé au bout des caractères du noeud # sans différence if index == len(string): # On est également au bout de la clé # C'est qu'on a de la chance ! node.data = value else: # On n'est pas au bout de la clé node.next, next_balance = self._insert(string,value,index,node.next) # Suite à un split du noeud suivant, il est peut-être possible # de le recoller à ce noeud ? node, discard = self._compact_node(node, None) return node, self._compute_balance(node) else: # On est arrivé au bout de la clé, mais pas au bout des caractères # du noeud assert index == len(string) # On est au bout de la clé, mais avant la fin des caractères du # noeud ; il faut donc splitter, mais au local_index précédent car # on a bêtement avancé les deux à la fois aux lignes 105 - 106 node, balance = self._split_node(node,local_index-1) # On peut essayer de joindre le noeud suivant au noeud d'après node.next, discard = self._compact_node(node.next,None) # On stocke ensuite la clé et la valeur node.data = value return node, balance def __delitem__(self,string): self.root, discard = self._remove(string,0,self.root) def _remove(self,string,index,node): if node is None: return None local_index = 0 # On avance tant qu'il y a égalité diff = 0 while local_index < len(node.chars) and index<len(string): diff = cmp(string[index],node.chars[local_index]) if diff == 0: local_index += 1 index += 1 else: break if diff!=0: assert local_index < len(node.chars) and index<len(string) # On a trouvé un point de divergence avant le dernier caractère du # noeud, et de la clé, il va donc falloir splitter if local_index < len(node.chars) - 1: return node, self._compute_balance(node) # Maintenant que le split est fait, on peut continuer à positionner # la nouvelle clé balance = balance_info() if diff>0: node.left, left_balance = self._remove(string,index,node.left) balance.did_balance = left_balance.did_balance node, balance = self._compact_node(node,balance,True) right_balance = self._compute_balance(node.right) else: node.right, right_balance = self._remove(string,index,node.right) balance.did_balance = right_balance.did_balance node, balance = self._compact_node(node,balance,True) left_balance = self._compute_balance(node.left) # On calcule la nouvelle balance en tenant compte des modifs if len(node.chars)>1: balance.height = 1 else: balance.height = max(left_balance.height, right_balance.height) + 1 balance.balance = left_balance.height - right_balance.height balance.left_balance = left_balance.balance balance.right_balance = right_balance.balance if not balance.did_balance: # On effectue la balance si elle n'a pas déjà été effectuée node, balance = self._balance(node,balance) if len(node.chars)!=1: # Si à l'issue de la balance on se retrouve avec plusieurs # caractères, alors la hauteur du nouveau noeud est 1. balance.height = 1 balance.balance = 0 balance.left_balance = 0 balance.right_balance = 0 # return self._compact_node(node,balance) return node, balance elif local_index == len(node.chars): # On est arrivé au bout des caractères du noeud # sans différence if index == len(string): # On est également au bout de la clé # C'est qu'on a de la chance ! node.data = None else: # On n'est pas au bout de la clé node.next, next_balance = self._remove(string,index,node.next) # Suite à un split du noeud suivant, il est peut-être possible # de le recoller à ce noeud ? # node, discard = self._compact_node(node, None) return self._compact_node(node,self._compute_balance(node)) else: # On est arrivé au bout de la clé, mais pas au bout des caractères # du noeud assert index == len(string) # On est au bout de la clé, mais avant la fin des caractères du # noeud return node, balance def _compute_balance(self,node): if node is not None: if len(node.chars)>1: # La hauteur d'un noeud contenant plusieurs caractères # est forcément 1 return balance_info(height=1) else: balance = balance_info() # Récursion sur les noeuds fils left_balance = self._compute_balance(node.left) right_balance = self._compute_balance(node.right) balance.did_balance = False balance.height = max(left_balance.height, right_balance.height) + 1 balance.balance = left_balance.height - right_balance.height balance.left_balance = left_balance.balance balance.right_balance = right_balance.balance return balance else: # La hauteur d'un noeud non existant est 0, ce qui fait # que la hauteur d'une feuille est 1 return balance_info() def _balance(self,node,balance): assert balance.height == self._compute_balance(node).height, (node, balance, self._compute_balance(node)) assert len(node.chars)>1 or balance.balance == self._compute_balance(node).balance, "%s : %s != %s"%(node,balance,self._compute_balance(node)) assert balance.left_balance == self._compute_balance(node.left).balance assert balance.right_balance == self._compute_balance(node.right).balance assert -2 < balance.left_balance < 2 assert -2 < balance.right_balance < 2 assert -3 < balance.balance < 3 assert -2 < self._compute_balance(node.left).balance < 2 assert -2 < self._compute_balance(node.right).balance < 2 assert -3 < self._compute_balance(node).balance < 3 # Assure le critère AVL if balance.balance > 1: if balance.left_balance > 0: node, balance = self._ll(node,balance) else: node, balance = self._lr(node,balance) balance.did_balance = True elif balance.balance < -1: if balance.right_balance < 0: node, balance = self._rr(node,balance) else: node, balance = self._rl(node,balance) balance.did_balance = True assert -2 < self._compute_balance(node).balance < 2,(node,self._compute_balance(node)) assert -2 < balance.balance < 2 return node, balance def _ll(self,node,balance): # Un déséquilibre LL n'est possible qu'avec un noeud de gauche # n'ayant qu'un caractère assert len(node.left.chars) == 1 # On fait la rotation au niveau des liens left_node = node.left node.left = left_node.right left_node.right = node # Et maintenant on ramène tous les caractères du noeud d'origine sauf son # dernier, et on les insère au début du noeud de gauche. # En gros si dans le noeud d'origine on a abcdefG # et dans le noeud de gauche on a juste B # A la fin on a dans le noeud d'origine juste G # et dans le noeud de gauche abcdefB new_char = node.chars.pop() node.chars.append(left_node.chars.pop()) left_node.chars.append(new_char) node.chars, left_node.chars = left_node.chars, node.chars # Il est possible que le noeud d'origine soit concaténable avec la suite left_node.right, discard = self._compact_node(left_node.right,None) # On ajuste la balance en fonction de l'opération effectuée balance.height -= 1 balance.balance = 0 balance.left_balance = 0 # Le noeud de gauche prend la place du noeud d'origine dans l'arbre return left_node, balance def _rr(self,node,balance): assert len(node.right.chars) == 1 right_node = node.right node.right = right_node.left right_node.left = node new_char = node.chars.pop() node.chars.append(right_node.chars.pop()) right_node.chars.append(new_char) node.chars, right_node.chars = right_node.chars, node.chars right_node.left, discard = self._compact_node(right_node.left,None) balance.height -= 1 balance.balance = 0 balance.right_balance = 0 return right_node, balance def _lr(self,node,balance): if len(node.left.right.chars)>1: node.left.right, discard = self._split_node(node.left.right,0) node.left, discard = self._rr(node.left,balance_info()) node, balance = self._ll(node,balance) return node, balance def _rl(self,node,balance): if len(node.right.left.chars)>1: node.right.left, discard = self._split_node(node.right.left,0) node.right, discard = self._ll(node.right,balance_info()) node, balance = self._rr(node,balance) return node, balance def _split_node(self,node,local_index): """ Découpe un noeud à l'index donné """ assert local_index < len(node.chars) # On crée un nouveau noeud new_node = tst_node() # On prend tout le début du segment de clé du noeud y compris # le caractère qui diffère et on les met dans le nouveau noeud new_node.chars = node.chars[0:local_index + 1] # La suite de ce nouveau noeud est l'ancien noeud new_node.next = node # On adapte la chaîne dans l'ancien noeud, c'est le restant de # la chaîne après le split node.chars = node.chars[local_index + 1:] return new_node, balance_info(height=1) def _compact_node(self,node,balance,debug=False): """ Tente de ressouder un noeud à son noeud suivant si cela est possible """ if node is None: return None, balance_info() elif node.data is not None: return node, balance elif ( node.next is not None and node.left is None and node.right is None and len(node.chars)+len(node.next.chars)<CHARS_PER_NODE ): # Les quatre conditions ci dessus sont : # - on a un noeud suivant # - le noeud actuel n'est pas un pivot (dans ce cas la concaténation # serait impossible) # - le noeud actuel ne contient pas de données (idem) # - il y a de la place pour les caractères du noeud courant dans # le noeud suivant if debug: print "CAT", node, node.next, node.chars.extend(node.next.chars) node.next.chars = node.chars if debug: print '=>',node.next return node.next, self._compute_balance(node.next) elif ( node.next is None and (node.left is None or node.right is None) ): if node.left is None and node.right is None: if debug: print "CAT2", node, "=>", None return None, balance_info() else: # On prend le noeud restant new_node = node.left or node.right if len(node.chars)+len(new_node.chars) - 1 < CHARS_PER_NODE: if debug: print "CAT3", node, new_node, # On supprime le dernier caractère du noeud node.chars.pop() # On ajoute les caractères du nouveau noeud node.chars.extend(new_node.chars) # On met le résultat dans le nouveau noeud new_node.chars = node.chars if debug: print '=>',new_node return new_node, self._compute_balance(new_node) else: return node, balance else: return node, balance def _new_node(self,string,value,index): new_node = tst_node() # On remplit le segment du noeud avec un maximum de caractères de la clé # en partant de l'index donné length = min(len(string)-index,CHARS_PER_NODE) new_node.chars.extend(string[index:index+length]) if index+length<len(string): # s'il reste des caractères dans la clé après ce segment... new_node.next, discard = self._new_node(string,value,index+length) else: # sinon on met la clé et la donnée dans ce noeud new_node.data = value return new_node, balance_info(height=1) def stats(self,node,acc,depth=0): if node == None : return acc['nodes'] = acc.get('nodes',0) + 1 acc['total_chars'] = acc.get('total_chars',0) + len(node.chars) key = ('nbchars',len(node.chars)) acc[key] = acc.get(key,0) + 1 links = ((node.left is not None and 1) or 0) + ((node.next is not None and 1) or 0) + ((node.right is not None and 1) or 0) key = ('links',links) acc[key] = acc.get(key,0) + 1 key = ('depth',depth) acc[key] = acc.get(key,0) + 1 self.stats(node.left,acc,depth+1) self.stats(node.next,acc,depth+1) self.stats(node.right,acc,depth+1) return acc def visit(self,callback,string=None): if string is not None: # Ce code est copié / collé depuis _find_node(). # C'est fait exprès, car cela évite d'avoir instanciation d'un # tuple pour retour de valeur multiple à chaque appel de __getitem__. node = self.root index = 0 while node is not None: local_index = 0 # On avance tant qu'il y a égalité diff = 0 while local_index < len(node.chars) and index < len(string): diff = cmp(string[index],node.chars[local_index]) if diff == 0: local_index += 1 index += 1 else: break if diff != 0: # On a une différence de caractère if local_index < len(node.chars) - 1: # on s'est arrêté avant le dernier caractère du noeud, # il n'y a donc pas de match possible (sinon il y aurait eu # split à l'insertion) node = None break else: # différence au dernier caractère du noeud if diff>0: node = node.left elif diff<0: node = node.right elif local_index == len(node.chars): # On est au bout des caractères du noeud if index == len(string): # On est également au bout de la clé # C'est qu'on a de la chance ! break else: # On avance d'un cran node = node.next else: # On n'est pas au bout des caractères, c'est qu'on est au # bout de la clé, et donc qu'il n'y a pas de match, sinon # il y aurait eu un split assert index == len(string) # On retourne le noeud quand même car il va être utile pour # le visiteur, simplement il n'y a aucune donnée dedans break if node is None: diff --git a/python/tst_wrap.cxx b/python/tst_wrap.cxx index 47dc0e1..e5dd80d 100644 --- a/python/tst_wrap.cxx +++ b/python/tst_wrap.cxx @@ -1539,1025 +1539,1025 @@ PySwigObject_own(PyObject *v, PyObject *args) #endif } return obj; } } #ifdef METH_O static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)PySwigObject_disown, METH_NOARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_NOARGS, (char *)"aquires ownership of the pointer"}, {(char *)"own", (PyCFunction)PySwigObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)PySwigObject_append, METH_O, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)PySwigObject_next, METH_NOARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)PySwigObject_repr, METH_NOARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #else static PyMethodDef swigobject_methods[] = { {(char *)"disown", (PyCFunction)PySwigObject_disown, METH_VARARGS, (char *)"releases ownership of the pointer"}, {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_VARARGS, (char *)"aquires ownership of the pointer"}, {(char *)"own", (PyCFunction)PySwigObject_own, METH_VARARGS, (char *)"returns/sets ownership of the pointer"}, {(char *)"append", (PyCFunction)PySwigObject_append, METH_VARARGS, (char *)"appends another 'this' object"}, {(char *)"next", (PyCFunction)PySwigObject_next, METH_VARARGS, (char *)"returns the next 'this' object"}, {(char *)"__repr__",(PyCFunction)PySwigObject_repr, METH_VARARGS, (char *)"returns object representation"}, {0, 0, 0, 0} }; #endif #if PY_VERSION_HEX < 0x02020000 SWIGINTERN PyObject * PySwigObject_getattr(PySwigObject *sobj,char *name) { return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name); } #endif SWIGRUNTIME PyTypeObject* _PySwigObject_type(void) { static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; static PyNumberMethods PySwigObject_as_number = { (binaryfunc)0, /*nb_add*/ (binaryfunc)0, /*nb_subtract*/ (binaryfunc)0, /*nb_multiply*/ (binaryfunc)0, /*nb_divide*/ (binaryfunc)0, /*nb_remainder*/ (binaryfunc)0, /*nb_divmod*/ (ternaryfunc)0,/*nb_power*/ (unaryfunc)0, /*nb_negative*/ (unaryfunc)0, /*nb_positive*/ (unaryfunc)0, /*nb_absolute*/ (inquiry)0, /*nb_nonzero*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ (coercion)0, /*nb_coerce*/ (unaryfunc)PySwigObject_long, /*nb_int*/ (unaryfunc)PySwigObject_long, /*nb_long*/ (unaryfunc)0, /*nb_float*/ (unaryfunc)PySwigObject_oct, /*nb_oct*/ (unaryfunc)PySwigObject_hex, /*nb_hex*/ #if PY_VERSION_HEX >= 0x02020000 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */ #elif PY_VERSION_HEX >= 0x02000000 0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */ #endif }; static PyTypeObject pyswigobject_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ (char *)"PySwigObject", /* tp_name */ sizeof(PySwigObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)PySwigObject_dealloc, /* tp_dealloc */ (printfunc)PySwigObject_print, /* tp_print */ #if PY_VERSION_HEX < 0x02020000 (getattrfunc)PySwigObject_getattr, /* tp_getattr */ #else (getattrfunc)0, /* tp_getattr */ #endif (setattrfunc)0, /* tp_setattr */ (cmpfunc)PySwigObject_compare, /* tp_compare */ (reprfunc)PySwigObject_repr, /* tp_repr */ &PySwigObject_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ (reprfunc)PySwigObject_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigobject_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ swigobject_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; pyswigobject_type = tmp; pyswigobject_type.ob_type = &PyType_Type; type_init = 1; } return &pyswigobject_type; } SWIGRUNTIME PyObject * PySwigObject_New(void *ptr, swig_type_info *ty, int own) { PySwigObject *sobj = PyObject_NEW(PySwigObject, PySwigObject_type()); if (sobj) { sobj->ptr = ptr; sobj->ty = ty; sobj->own = own; sobj->next = 0; } return (PyObject *)sobj; } /* ----------------------------------------------------------------------------- * Implements a simple Swig Packed type, and use it instead of string * ----------------------------------------------------------------------------- */ typedef struct { PyObject_HEAD void *pack; swig_type_info *ty; size_t size; } PySwigPacked; SWIGRUNTIME int PySwigPacked_print(PySwigPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { char result[SWIG_BUFFER_SIZE]; fputs("<Swig Packed ", fp); if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { fputs("at ", fp); fputs(result, fp); } fputs(v->ty->name,fp); fputs(">", fp); return 0; } SWIGRUNTIME PyObject * PySwigPacked_repr(PySwigPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { return PyString_FromFormat("<Swig Packed at %s%s>", result, v->ty->name); } else { return PyString_FromFormat("<Swig Packed %s>", v->ty->name); } } SWIGRUNTIME PyObject * PySwigPacked_str(PySwigPacked *v) { char result[SWIG_BUFFER_SIZE]; if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ return PyString_FromFormat("%s%s", result, v->ty->name); } else { return PyString_FromString(v->ty->name); } } SWIGRUNTIME int PySwigPacked_compare(PySwigPacked *v, PySwigPacked *w) { size_t i = v->size; size_t j = w->size; int s = (i < j) ? -1 : ((i > j) ? 1 : 0); return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size); } SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void); SWIGRUNTIME PyTypeObject* PySwigPacked_type(void) { static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type(); return type; } SWIGRUNTIMEINLINE int PySwigPacked_Check(PyObject *op) { return ((op)->ob_type == _PySwigPacked_type()) || (strcmp((op)->ob_type->tp_name,"PySwigPacked") == 0); } SWIGRUNTIME void PySwigPacked_dealloc(PyObject *v) { if (PySwigPacked_Check(v)) { PySwigPacked *sobj = (PySwigPacked *) v; free(sobj->pack); } PyObject_DEL(v); } SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void) { static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; static PyTypeObject pyswigpacked_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ (char *)"PySwigPacked", /* tp_name */ sizeof(PySwigPacked), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)PySwigPacked_dealloc, /* tp_dealloc */ (printfunc)PySwigPacked_print, /* tp_print */ (getattrfunc)0, /* tp_getattr */ (setattrfunc)0, /* tp_setattr */ (cmpfunc)PySwigPacked_compare, /* tp_compare */ (reprfunc)PySwigPacked_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ (reprfunc)PySwigPacked_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ swigpacked_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; pyswigpacked_type = tmp; pyswigpacked_type.ob_type = &PyType_Type; type_init = 1; } return &pyswigpacked_type; } SWIGRUNTIME PyObject * PySwigPacked_New(void *ptr, size_t size, swig_type_info *ty) { PySwigPacked *sobj = PyObject_NEW(PySwigPacked, PySwigPacked_type()); if (sobj) { void *pack = malloc(size); if (pack) { memcpy(pack, ptr, size); sobj->pack = pack; sobj->ty = ty; sobj->size = size; } else { PyObject_DEL((PyObject *) sobj); sobj = 0; } } return (PyObject *) sobj; } SWIGRUNTIME swig_type_info * PySwigPacked_UnpackData(PyObject *obj, void *ptr, size_t size) { if (PySwigPacked_Check(obj)) { PySwigPacked *sobj = (PySwigPacked *)obj; if (sobj->size != size) return 0; memcpy(ptr, sobj->pack, size); return sobj->ty; } else { return 0; } } /* ----------------------------------------------------------------------------- * pointers/data manipulation * ----------------------------------------------------------------------------- */ SWIGRUNTIMEINLINE PyObject * _SWIG_This(void) { return PyString_FromString("this"); } SWIGRUNTIME PyObject * SWIG_This(void) { static PyObject *SWIG_STATIC_POINTER(swig_this) = _SWIG_This(); return swig_this; } /* #define SWIG_PYTHON_SLOW_GETSET_THIS */ SWIGRUNTIME PySwigObject * SWIG_Python_GetSwigThis(PyObject *pyobj) { if (PySwigObject_Check(pyobj)) { return (PySwigObject *) pyobj; } else { PyObject *obj = 0; #if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000)) if (PyInstance_Check(pyobj)) { obj = _PyInstance_Lookup(pyobj, SWIG_This()); } else { PyObject **dictptr = _PyObject_GetDictPtr(pyobj); if (dictptr != NULL) { PyObject *dict = *dictptr; obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; } else { #ifdef PyWeakref_CheckProxy if (PyWeakref_CheckProxy(pyobj)) { PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; } #endif obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } } } #else obj = PyObject_GetAttr(pyobj,SWIG_This()); if (obj) { Py_DECREF(obj); } else { if (PyErr_Occurred()) PyErr_Clear(); return 0; } #endif if (obj && !PySwigObject_Check(obj)) { /* a PyObject is called 'this', try to get the 'real this' PySwigObject from it */ return SWIG_Python_GetSwigThis(obj); } return (PySwigObject *)obj; } } /* Acquire a pointer value */ SWIGRUNTIME int SWIG_Python_AcquirePtr(PyObject *obj, int own) { if (own) { PySwigObject *sobj = SWIG_Python_GetSwigThis(obj); if (sobj) { int oldown = sobj->own; sobj->own = own; return oldown; } } return 0; } /* Convert a pointer value */ SWIGRUNTIME int SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { if (!obj) return SWIG_ERROR; if (obj == Py_None) { if (ptr) *ptr = 0; return SWIG_OK; } else { PySwigObject *sobj = SWIG_Python_GetSwigThis(obj); while (sobj) { void *vptr = sobj->ptr; if (ty) { swig_type_info *to = sobj->ty; if (to == ty) { /* no type cast needed */ if (ptr) *ptr = vptr; break; } else { swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) { sobj = (PySwigObject *)sobj->next; } else { if (ptr) *ptr = SWIG_TypeCast(tc,vptr); break; } } } else { if (ptr) *ptr = vptr; break; } } if (sobj) { if (own) *own = sobj->own; if (flags & SWIG_POINTER_DISOWN) { sobj->own = 0; } return SWIG_OK; } else { int res = SWIG_ERROR; if (flags & SWIG_POINTER_IMPLICIT_CONV) { PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0; if (data && !data->implicitconv) { PyObject *klass = data->klass; if (klass) { PyObject *impconv; data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ impconv = SWIG_Python_CallFunctor(klass, obj); data->implicitconv = 0; if (PyErr_Occurred()) { PyErr_Clear(); impconv = 0; } if (impconv) { PySwigObject *iobj = SWIG_Python_GetSwigThis(impconv); if (iobj) { void *vptr; res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); if (SWIG_IsOK(res)) { if (ptr) { *ptr = vptr; /* transfer the ownership to 'ptr' */ iobj->own = 0; res = SWIG_AddCast(res); res = SWIG_AddNewMask(res); } else { res = SWIG_AddCast(res); } } } Py_DECREF(impconv); } } } } return res; } } } /* Convert a function ptr value */ SWIGRUNTIME int SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { if (!PyCFunction_Check(obj)) { return SWIG_ConvertPtr(obj, ptr, ty, 0); } else { void *vptr = 0; /* here we get the method pointer for callbacks */ - char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); + const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; if (desc) { desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; if (!desc) return SWIG_ERROR; } if (ty) { swig_cast_info *tc = SWIG_TypeCheck(desc,ty); if (!tc) return SWIG_ERROR; *ptr = SWIG_TypeCast(tc,vptr); } else { *ptr = vptr; } return SWIG_OK; } } /* Convert a packed value value */ SWIGRUNTIME int SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { swig_type_info *to = PySwigPacked_UnpackData(obj, ptr, sz); if (!to) return SWIG_ERROR; if (ty) { if (to != ty) { /* check type cast? */ swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); if (!tc) return SWIG_ERROR; } } return SWIG_OK; } /* ----------------------------------------------------------------------------- * Create a new pointer object * ----------------------------------------------------------------------------- */ /* Create a new instance object, whitout calling __init__, and set the 'this' attribute. */ SWIGRUNTIME PyObject* SWIG_Python_NewShadowInstance(PySwigClientData *data, PyObject *swig_this) { #if (PY_VERSION_HEX >= 0x02020000) PyObject *inst = 0; PyObject *newraw = data->newraw; if (newraw) { inst = PyObject_Call(newraw, data->newargs, NULL); if (inst) { #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { PyObject *dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; PyDict_SetItem(dict, SWIG_This(), swig_this); } } #else PyObject *key = SWIG_This(); PyObject_SetAttr(inst, key, swig_this); #endif } } else { PyObject *dict = PyDict_New(); PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); } return inst; #else #if (PY_VERSION_HEX >= 0x02010000) PyObject *inst; PyObject *dict = PyDict_New(); PyDict_SetItem(dict, SWIG_This(), swig_this); inst = PyInstance_NewRaw(data->newargs, dict); Py_DECREF(dict); return (PyObject *) inst; #else PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type); if (inst == NULL) { return NULL; } inst->in_class = (PyClassObject *)data->newargs; Py_INCREF(inst->in_class); inst->in_dict = PyDict_New(); if (inst->in_dict == NULL) { Py_DECREF(inst); return NULL; } #ifdef Py_TPFLAGS_HAVE_WEAKREFS inst->in_weakreflist = NULL; #endif #ifdef Py_TPFLAGS_GC PyObject_GC_Init(inst); #endif PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this); return (PyObject *) inst; #endif #endif } SWIGRUNTIME void SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) { PyObject *dict; #if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS) PyObject **dictptr = _PyObject_GetDictPtr(inst); if (dictptr != NULL) { dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); *dictptr = dict; } PyDict_SetItem(dict, SWIG_This(), swig_this); return; } #endif dict = PyObject_GetAttrString(inst, "__dict__"); PyDict_SetItem(dict, SWIG_This(), swig_this); Py_DECREF(dict); } SWIGINTERN PyObject * SWIG_Python_InitShadowInstance(PyObject *args) { PyObject *obj[2]; if (!SWIG_Python_UnpackTuple(args,(char*)"swiginit", 2, 2, obj)) { return NULL; } else { PySwigObject *sthis = SWIG_Python_GetSwigThis(obj[0]); if (sthis) { PySwigObject_append((PyObject*) sthis, obj[1]); } else { SWIG_Python_SetSwigThis(obj[0], obj[1]); } return SWIG_Py_Void(); } } /* Create a new pointer object */ SWIGRUNTIME PyObject * SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int flags) { if (!ptr) { return SWIG_Py_Void(); } else { int own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; PyObject *robj = PySwigObject_New(ptr, type, own); PySwigClientData *clientdata = type ? (PySwigClientData *)(type->clientdata) : 0; if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); if (inst) { Py_DECREF(robj); robj = inst; } } return robj; } } /* Create a new packed object */ SWIGRUNTIMEINLINE PyObject * SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { return ptr ? PySwigPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); } /* -----------------------------------------------------------------------------* * Get type list * -----------------------------------------------------------------------------*/ #ifdef SWIG_LINK_RUNTIME void *SWIG_ReturnGlobalTypeList(void *); #endif SWIGRUNTIME swig_module_info * SWIG_Python_GetModule(void) { static void *type_pointer = (void *)0; /* first check if module already created */ if (!type_pointer) { #ifdef SWIG_LINK_RUNTIME type_pointer = SWIG_ReturnGlobalTypeList((void *)0); #else type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME); if (PyErr_Occurred()) { PyErr_Clear(); type_pointer = (void *)0; } #endif } return (swig_module_info *) type_pointer; } #if PY_MAJOR_VERSION < 2 /* PyModule_AddObject function was introduced in Python 2.0. The following function is copied out of Python/modsupport.c in python version 2.3.4 */ SWIGINTERN int PyModule_AddObject(PyObject *m, char *name, PyObject *o) { PyObject *dict; if (!PyModule_Check(m)) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs module as first arg"); return SWIG_ERROR; } if (!o) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs non-NULL value"); return SWIG_ERROR; } dict = PyModule_GetDict(m); if (dict == NULL) { /* Internal error -- modules must have a dict! */ PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", PyModule_GetName(m)); return SWIG_ERROR; } if (PyDict_SetItemString(dict, name, o)) return SWIG_ERROR; Py_DECREF(o); return SWIG_OK; } #endif SWIGRUNTIME void SWIG_Python_DestroyModule(void *vptr) { swig_module_info *swig_module = (swig_module_info *) vptr; swig_type_info **types = swig_module->types; size_t i; for (i =0; i < swig_module->size; ++i) { swig_type_info *ty = types[i]; if (ty->owndata) { PySwigClientData *data = (PySwigClientData *) ty->clientdata; if (data) PySwigClientData_Del(data); } } Py_DECREF(SWIG_This()); } SWIGRUNTIME void SWIG_Python_SetModule(swig_module_info *swig_module) { static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */ PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule); if (pointer && module) { PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer); } else { Py_XDECREF(pointer); } } /* The python cached type query */ SWIGRUNTIME PyObject * SWIG_Python_TypeCache() { static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New(); return cache; } SWIGRUNTIME swig_type_info * SWIG_Python_TypeQuery(const char *type) { PyObject *cache = SWIG_Python_TypeCache(); PyObject *key = PyString_FromString(type); PyObject *obj = PyDict_GetItem(cache, key); swig_type_info *descriptor; if (obj) { descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj); } else { swig_module_info *swig_module = SWIG_Python_GetModule(); descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); if (descriptor) { obj = PyCObject_FromVoidPtr(descriptor, NULL); PyDict_SetItem(cache, key, obj); Py_DECREF(obj); } } Py_DECREF(key); return descriptor; } /* For backward compatibility only */ #define SWIG_POINTER_EXCEPTION 0 #define SWIG_arg_fail(arg) SWIG_Python_ArgFail(arg) #define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) SWIGRUNTIME int SWIG_Python_AddErrMesg(const char* mesg, int infront) { if (PyErr_Occurred()) { PyObject *type = 0; PyObject *value = 0; PyObject *traceback = 0; PyErr_Fetch(&type, &value, &traceback); if (value) { PyObject *old_str = PyObject_Str(value); Py_XINCREF(type); PyErr_Clear(); if (infront) { PyErr_Format(type, "%s %s", mesg, PyString_AsString(old_str)); } else { PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg); } Py_DECREF(old_str); } return 1; } else { return 0; } } SWIGRUNTIME int SWIG_Python_ArgFail(int argnum) { if (PyErr_Occurred()) { /* add information about failing argument */ char mesg[256]; PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); return SWIG_Python_AddErrMesg(mesg, 1); } else { return 0; } } SWIGRUNTIMEINLINE const char * PySwigObject_GetDesc(PyObject *self) { PySwigObject *v = (PySwigObject *)self; swig_type_info *ty = v ? v->ty : 0; return ty ? ty->str : (char*)""; } SWIGRUNTIME void SWIG_Python_TypeError(const char *type, PyObject *obj) { if (type) { #if defined(SWIG_COBJECT_TYPES) if (obj && PySwigObject_Check(obj)) { const char *otype = (const char *) PySwigObject_GetDesc(obj); if (otype) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'PySwigObject(%s)' is received", type, otype); return; } } else #endif { const char *otype = (obj ? obj->ob_type->tp_name : 0); if (otype) { PyObject *str = PyObject_Str(obj); const char *cstr = str ? PyString_AsString(str) : 0; if (cstr) { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", type, otype, cstr); } else { PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", type, otype); } Py_XDECREF(str); return; } } PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); } else { PyErr_Format(PyExc_TypeError, "unexpected type is received"); } } /* Convert a pointer value, signal an exception on a type mismatch */ SWIGRUNTIME void * SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) { void *result; if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { PyErr_Clear(); if (flags & SWIG_POINTER_EXCEPTION) { SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj); SWIG_Python_ArgFail(argnum); } } return result; } #ifdef __cplusplus #if 0 { /* cc-mode */ #endif } #endif #define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) #define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else /* -------- TYPES TABLE (BEGIN) -------- */ #define SWIGTYPE_p_CallableAction swig_types[0] #define SWIGTYPE_p_CallableFilter swig_types[1] #define SWIGTYPE_p_DictAction swig_types[2] #define SWIGTYPE_p_ListAction swig_types[3] #define SWIGTYPE_p_ObjectSerializer swig_types[4] #define SWIGTYPE_p_PythonReference swig_types[5] #define SWIGTYPE_p_TST swig_types[6] #define SWIGTYPE_p_TSTException swig_types[7] #define SWIGTYPE_p_TSTIteratorTlexical_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t_t swig_types[8] #define SWIGTYPE_p_TSTIteratorTmatch_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t_t swig_types[9] #define SWIGTYPE_p_TupleListAction swig_types[10] #define SWIGTYPE_p_actionTchar_PythonReference_string_type_t swig_types[11] #define SWIGTYPE_p_char swig_types[12] #define SWIGTYPE_p_character_type swig_types[13] #define SWIGTYPE_p_filterTchar_PythonReference_string_type_t swig_types[14] #define SWIGTYPE_p_lexical_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t swig_types[15] #define SWIGTYPE_p_match_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t swig_types[16] #define SWIGTYPE_p_qad_stringTchar_t swig_types[17] #define SWIGTYPE_p_serializer_type swig_types[18] #define SWIGTYPE_p_std__istream swig_types[19] #define SWIGTYPE_p_std__ostream swig_types[20] #define SWIGTYPE_p_std__pairTqad_stringTchar_t_PythonReference_p_t swig_types[21] #define SWIGTYPE_p_storage_type swig_types[22] #define SWIGTYPE_p_tstTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t swig_types[23] #define SWIGTYPE_p_tstTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t swig_types[24] #define SWIGTYPE_p_value_type swig_types[25] static swig_type_info *swig_types[27]; static swig_module_info swig_module = {swig_types, 26, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) /* -------- TYPES TABLE (END) -------- */ #if (PY_VERSION_HEX <= 0x02000000) # if !defined(SWIG_PYTHON_CLASSIC) # error "This python version requires to use swig with the '-classic' option" # endif #endif #if (PY_VERSION_HEX <= 0x02020000) # error "This python version requires to use swig with the '-nomodern' option" #endif #if (PY_VERSION_HEX <= 0x02020000) # error "This python version requires to use swig with the '-nomodernargs' option" #endif #ifndef METH_O # error "This python version requires to use swig with the '-nofastunpack' option" #endif #ifdef SWIG_TypeQuery # undef SWIG_TypeQuery #endif #define SWIG_TypeQuery SWIG_Python_TypeQuery /*----------------------------------------------- @(target):= _tst.so ------------------------------------------------*/ #define SWIG_init init_tst #define SWIG_name "_tst" #define SWIGVERSION 0x010329 #define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) #define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) #include <stdexcept> namespace swig { class PyObject_ptr { protected: PyObject *_obj; public: PyObject_ptr() :_obj(0) { } PyObject_ptr(const PyObject_ptr& item) : _obj(item._obj) { Py_XINCREF(_obj); } PyObject_ptr(PyObject *obj, bool initial_ref = true) :_obj(obj) { if (initial_ref) Py_XINCREF(_obj); } PyObject_ptr & operator=(const PyObject_ptr& item) { Py_XINCREF(item._obj); Py_XDECREF(_obj); _obj = item._obj; return *this; } ~PyObject_ptr() { Py_XDECREF(_obj); } @@ -6246,586 +6246,586 @@ static swig_type_info *swig_type_initial[] = { &_swigt__p_filterTchar_PythonReference_string_type_t, &_swigt__p_lexical_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t, &_swigt__p_match_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t, &_swigt__p_qad_stringTchar_t, &_swigt__p_serializer_type, &_swigt__p_std__istream, &_swigt__p_std__ostream, &_swigt__p_std__pairTqad_stringTchar_t_PythonReference_p_t, &_swigt__p_storage_type, &_swigt__p_tstTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t, &_swigt__p_tstTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t, &_swigt__p_value_type, }; static swig_cast_info _swigc__p_CallableAction[] = { {&_swigt__p_CallableAction, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_CallableFilter[] = { {&_swigt__p_CallableFilter, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_DictAction[] = { {&_swigt__p_DictAction, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ListAction[] = { {&_swigt__p_ListAction, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_ObjectSerializer[] = { {&_swigt__p_ObjectSerializer, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_PythonReference[] = { {&_swigt__p_PythonReference, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TST[] = { {&_swigt__p_TST, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TSTException[] = { {&_swigt__p_TSTException, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TSTIteratorTlexical_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t_t[] = { {&_swigt__p_TSTIteratorTlexical_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TSTIteratorTmatch_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t_t[] = { {&_swigt__p_TSTIteratorTmatch_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_TupleListAction[] = { {&_swigt__p_TupleListAction, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_actionTchar_PythonReference_string_type_t[] = { {&_swigt__p_actionTchar_PythonReference_string_type_t, 0, 0, 0}, {&_swigt__p_DictAction, _p_DictActionTo_p_actionTchar_PythonReference_string_type_t, 0, 0}, {&_swigt__p_ListAction, _p_ListActionTo_p_actionTchar_PythonReference_string_type_t, 0, 0}, {&_swigt__p_TupleListAction, _p_TupleListActionTo_p_actionTchar_PythonReference_string_type_t, 0, 0}, {&_swigt__p_CallableAction, _p_CallableActionTo_p_actionTchar_PythonReference_string_type_t, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_character_type[] = { {&_swigt__p_character_type, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_filterTchar_PythonReference_string_type_t[] = { {&_swigt__p_CallableFilter, _p_CallableFilterTo_p_filterTchar_PythonReference_string_type_t, 0, 0}, {&_swigt__p_filterTchar_PythonReference_string_type_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_lexical_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t[] = { {&_swigt__p_lexical_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_match_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t[] = { {&_swigt__p_match_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_qad_stringTchar_t[] = { {&_swigt__p_qad_stringTchar_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_serializer_type[] = { {&_swigt__p_serializer_type, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_std__istream[] = { {&_swigt__p_std__istream, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_std__ostream[] = { {&_swigt__p_std__ostream, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_std__pairTqad_stringTchar_t_PythonReference_p_t[] = { {&_swigt__p_std__pairTqad_stringTchar_t_PythonReference_p_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_storage_type[] = { {&_swigt__p_storage_type, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_tstTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t[] = { {&_swigt__p_tstTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_tstTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t[] = { {&_swigt__p_tstTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t, 0, 0, 0}, {&_swigt__p_TST, _p_TSTTo_p_tstTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_value_type[] = { {&_swigt__p_value_type, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { _swigc__p_CallableAction, _swigc__p_CallableFilter, _swigc__p_DictAction, _swigc__p_ListAction, _swigc__p_ObjectSerializer, _swigc__p_PythonReference, _swigc__p_TST, _swigc__p_TSTException, _swigc__p_TSTIteratorTlexical_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t_t, _swigc__p_TSTIteratorTmatch_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t_t, _swigc__p_TupleListAction, _swigc__p_actionTchar_PythonReference_string_type_t, _swigc__p_char, _swigc__p_character_type, _swigc__p_filterTchar_PythonReference_string_type_t, _swigc__p_lexical_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t, _swigc__p_match_iteratorTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t, _swigc__p_qad_stringTchar_t, _swigc__p_serializer_type, _swigc__p_std__istream, _swigc__p_std__ostream, _swigc__p_std__pairTqad_stringTchar_t_PythonReference_p_t, _swigc__p_storage_type, _swigc__p_tstTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_qad_stringTchar_t_t, _swigc__p_tstTchar_PythonReference_memory_storageTchar_PythonReference_t_ObjectSerializer_string_type_t, _swigc__p_value_type, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ static swig_const_info swig_const_table[] = { {0, 0, 0, 0.0, 0, 0}}; #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * Type initialization: * This problem is tough by the requirement that no dynamic * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back * to swig_type_info structures, we need some lookup code at initialization. * The idea is that swig generates all the structures that are needed. * The runtime then collects these partially filled structures. * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * * The generated swig_type_info structures are assigned staticly to an initial * array. We just loop though that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the * cast linked list. The cast data is initially stored in something like a * two-dimensional array. Each row corresponds to a type (there are the same * number of rows as there are in the swig_type_initial array). Each entry in * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that * swig_cast_info to the linked list (because the cast->type) pointer will * be correct. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* c-mode */ #endif #endif #if 0 #define SWIGRUNTIME_DEBUG #endif SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) { size_t i; swig_module_info *module_head; static int init_run = 0; clientdata = clientdata; if (init_run) return; init_run = 1; /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (module_head) { swig_module.next = module_head->next; module_head->next = &swig_module; } else { /* This is the first module loaded */ swig_module.next = &swig_module; SWIG_SetModule(clientdata, &swig_module); } /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); #endif for (i = 0; i < swig_module.size; ++i) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); #endif /* if there is another module already loaded */ if (swig_module.next != &swig_module) { type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found type %s\n", type->name); #endif if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); #endif } } else { type = swig_module.type_initial[i]; } /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif cast->type = ret; ret = 0; } else { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif if (!ocast) ret = 0; } } if (!ret) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif if (type->cast) { type->cast->prev = cast; cast->next = type->cast; } type->cast = cast; } cast++; } /* Set entry in modules->types array equal to the type */ swig_module.types[i] = type; } swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } printf("---- Total casts: %d\n",j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } /* This function will propagate the clientdata field of type to * any new swig_type_info structures that have been added into the list * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ SWIGRUNTIME void SWIG_PropagateClientData(void) { size_t i; swig_cast_info *equiv; static int init_run = 0; if (init_run) return; init_run = 1; for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } equiv = equiv->next; } } } } #ifdef __cplusplus #if 0 { /* c-mode */ #endif } #endif #ifdef __cplusplus extern "C" { #endif /* Python-specific SWIG API */ #define SWIG_newvarlink() SWIG_Python_newvarlink() #define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) #define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) /* ----------------------------------------------------------------------------- * global variable support code. * ----------------------------------------------------------------------------- */ typedef struct swig_globalvar { char *name; /* Name of global variable */ PyObject *(*get_attr)(void); /* Return the current value */ int (*set_attr)(PyObject *); /* Set the value */ struct swig_globalvar *next; } swig_globalvar; typedef struct swig_varlinkobject { PyObject_HEAD swig_globalvar *vars; } swig_varlinkobject; SWIGINTERN PyObject * swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) { return PyString_FromString("<Swig global variables>"); } SWIGINTERN PyObject * swig_varlink_str(swig_varlinkobject *v) { PyObject *str = PyString_FromString("("); swig_globalvar *var; for (var = v->vars; var; var=var->next) { PyString_ConcatAndDel(&str,PyString_FromString(var->name)); if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); } PyString_ConcatAndDel(&str,PyString_FromString(")")); return str; } SWIGINTERN int swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) { PyObject *str = swig_varlink_str(v); fprintf(fp,"Swig global variables "); fprintf(fp,"%s\n", PyString_AsString(str)); Py_DECREF(str); return 0; } SWIGINTERN void swig_varlink_dealloc(swig_varlinkobject *v) { swig_globalvar *var = v->vars; while (var) { swig_globalvar *n = var->next; free(var->name); free(var); var = n; } } SWIGINTERN PyObject * swig_varlink_getattr(swig_varlinkobject *v, char *n) { PyObject *res = NULL; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->get_attr)(); break; } var = var->next; } if (res == NULL && !PyErr_Occurred()) { PyErr_SetString(PyExc_NameError,"Unknown C global variable"); } return res; } SWIGINTERN int swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { int res = 1; swig_globalvar *var = v->vars; while (var) { if (strcmp(var->name,n) == 0) { res = (*var->set_attr)(p); break; } var = var->next; } if (res == 1 && !PyErr_Occurred()) { PyErr_SetString(PyExc_NameError,"Unknown C global variable"); } return res; } SWIGINTERN PyTypeObject* swig_varlink_type(void) { static char varlink__doc__[] = "Swig var link object"; static PyTypeObject varlink_type; static int type_init = 0; if (!type_init) { const PyTypeObject tmp = { PyObject_HEAD_INIT(NULL) 0, /* Number of items in variable part (ob_size) */ (char *)"swigvarlink", /* Type name (tp_name) */ sizeof(swig_varlinkobject), /* Basic size (tp_basicsize) */ 0, /* Itemsize (tp_itemsize) */ (destructor) swig_varlink_dealloc, /* Deallocator (tp_dealloc) */ (printfunc) swig_varlink_print, /* Print (tp_print) */ (getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */ (setattrfunc) swig_varlink_setattr, /* Set attr (tp_setattr) */ 0, /* tp_compare */ (reprfunc) swig_varlink_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)swig_varlink_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ varlink__doc__, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ #if PY_VERSION_HEX >= 0x02020000 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ #endif #if PY_VERSION_HEX >= 0x02030000 0, /* tp_del */ #endif #ifdef COUNT_ALLOCS 0,0,0,0 /* tp_alloc -> tp_next */ #endif }; varlink_type = tmp; varlink_type.ob_type = &PyType_Type; type_init = 1; } return &varlink_type; } /* Create a variable linking object for use later */ SWIGINTERN PyObject * SWIG_Python_newvarlink(void) { swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type()); if (result) { result->vars = 0; } return ((PyObject*) result); } SWIGINTERN void SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { swig_varlinkobject *v = (swig_varlinkobject *) p; swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); if (gv) { size_t size = strlen(name)+1; gv->name = (char *)malloc(size); if (gv->name) { strncpy(gv->name,name,size); gv->get_attr = get_attr; gv->set_attr = set_attr; gv->next = v->vars; } } v->vars = gv; } SWIGINTERN PyObject * SWIG_globals() { static PyObject *_SWIG_globals = 0; if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink(); return _SWIG_globals; } /* ----------------------------------------------------------------------------- * constants/methods manipulation * ----------------------------------------------------------------------------- */ /* Install Constants */ SWIGINTERN void SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { PyObject *obj = 0; size_t i; for (i = 0; constants[i].type; ++i) { switch(constants[i].type) { case SWIG_PY_POINTER: obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); break; case SWIG_PY_BINARY: obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); break; default: obj = 0; break; } if (obj) { PyDict_SetItemString(d, constants[i].name, obj); Py_DECREF(obj); } } } /* -----------------------------------------------------------------------------*/ /* Fix SwigMethods to carry the callback ptrs when needed */ /* -----------------------------------------------------------------------------*/ SWIGINTERN void SWIG_Python_FixMethods(PyMethodDef *methods, swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { size_t i; for (i = 0; methods[i].ml_name; ++i) { - char *c = methods[i].ml_doc; + const char *c = methods[i].ml_doc; if (c && (c = strstr(c, "swig_ptr: "))) { int j; swig_const_info *ci = 0; - char *name = c + 10; + const char *name = c + 10; for (j = 0; const_table[j].type; ++j) { if (strncmp(const_table[j].name, name, strlen(const_table[j].name)) == 0) { ci = &(const_table[j]); break; } } if (ci) { size_t shift = (ci->ptype) - types; swig_type_info *ty = types_initial[shift]; size_t ldoc = (c - methods[i].ml_doc); size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; char *ndoc = (char*)malloc(ldoc + lptr + 10); if (ndoc) { char *buff = ndoc; void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; if (ptr) { strncpy(buff, methods[i].ml_doc, ldoc); buff += ldoc; strncpy(buff, "swig_ptr: ", 10); buff += 10; SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); methods[i].ml_doc = ndoc; } } } } } } #ifdef __cplusplus } #endif /* -----------------------------------------------------------------------------* * Partial Init method * -----------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" #endif SWIGEXPORT void SWIG_init(void) { PyObject *m, *d; /* Fix SwigMethods to carry the callback ptrs when needed */ SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); m = Py_InitModule((char *) SWIG_name, SwigMethods); d = PyModule_GetDict(m); SWIG_InitializeModule(0); SWIG_InstallConstants(d,swig_const_table); PyDict_SetItemString(d,(char*)"cvar", SWIG_globals()); SWIG_addvarlink(SWIG_globals(),(char*)"TST_VERSION",TST_VERSION_get, TST_VERSION_set); SWIG_addvarlink(SWIG_globals(),(char*)"UNDEFINED_INDEX",UNDEFINED_INDEX_get, UNDEFINED_INDEX_set); SWIG_Python_SetConstant(d, "_lexical_iterator_type_state_left",SWIG_From_int(static_cast< int >(lexical_iterator<char,PythonReference,memory_storage<char,PythonReference >,ObjectSerializer,string_type >::state_left))); SWIG_Python_SetConstant(d, "_lexical_iterator_type_state_current",SWIG_From_int(static_cast< int >(lexical_iterator<char,PythonReference,memory_storage<char,PythonReference >,ObjectSerializer,string_type >::state_current))); SWIG_Python_SetConstant(d, "_lexical_iterator_type_state_right",SWIG_From_int(static_cast< int >(lexical_iterator<char,PythonReference,memory_storage<char,PythonReference >,ObjectSerializer,string_type >::state_right))); SWIG_Python_SetConstant(d, "_lexical_iterator_type_state_end",SWIG_From_int(static_cast< int >(lexical_iterator<char,PythonReference,memory_storage<char,PythonReference >,ObjectSerializer,string_type >::state_end))); SWIG_Python_SetConstant(d, "_close_match_iterator_type_state_left",SWIG_From_int(static_cast< int >(match_iterator<char,PythonReference,memory_storage<char,PythonReference >,ObjectSerializer,string_type >::state_left))); SWIG_Python_SetConstant(d, "_close_match_iterator_type_state_current",SWIG_From_int(static_cast< int >(match_iterator<char,PythonReference,memory_storage<char,PythonReference >,ObjectSerializer,string_type >::state_current))); SWIG_Python_SetConstant(d, "_close_match_iterator_type_state_skip_input",SWIG_From_int(static_cast< int >(match_iterator<char,PythonReference,memory_storage<char,PythonReference >,ObjectSerializer,string_type >::state_skip_input))); SWIG_Python_SetConstant(d, "_close_match_iterator_type_state_skip_base",SWIG_From_int(static_cast< int >(match_iterator<char,PythonReference,memory_storage<char,PythonReference >,ObjectSerializer,string_type >::state_skip_base))); SWIG_Python_SetConstant(d, "_close_match_iterator_type_state_right",SWIG_From_int(static_cast< int >(match_iterator<char,PythonReference,memory_storage<char,PythonReference >,ObjectSerializer,string_type >::state_right))); SWIG_Python_SetConstant(d, "_close_match_iterator_type_state_end",SWIG_From_int(static_cast< int >(match_iterator<char,PythonReference,memory_storage<char,PythonReference >,ObjectSerializer,string_type >::state_end))); }
nlehuen/pytst
1a1493e1269799076d540d29c78395e84a95d656
Mise à jour de textindex suite aux changements d'API de TST (passage à string partout).
diff --git a/com/tstlib/_tstlib.h b/com/tstlib/_tstlib.h index 12498d0..1939828 100644 --- a/com/tstlib/_tstlib.h +++ b/com/tstlib/_tstlib.h @@ -1,519 +1,519 @@ /* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 6.00.0361 */ -/* at Sat Apr 01 15:31:23 2006 +/* at Sun Jul 16 11:58:43 2006 */ /* Compiler settings for _tstlib.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 475 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif // __RPCNDR_H_VERSION__ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef ___tstlib_h__ #define ___tstlib_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IDocumentsScore_FWD_DEFINED__ #define __IDocumentsScore_FWD_DEFINED__ typedef interface IDocumentsScore IDocumentsScore; #endif /* __IDocumentsScore_FWD_DEFINED__ */ #ifndef __ITextIndex_FWD_DEFINED__ #define __ITextIndex_FWD_DEFINED__ typedef interface ITextIndex ITextIndex; #endif /* __ITextIndex_FWD_DEFINED__ */ #ifndef __CDocumentsScore_FWD_DEFINED__ #define __CDocumentsScore_FWD_DEFINED__ #ifdef __cplusplus typedef class CDocumentsScore CDocumentsScore; #else typedef struct CDocumentsScore CDocumentsScore; #endif /* __cplusplus */ #endif /* __CDocumentsScore_FWD_DEFINED__ */ #ifndef __CTextIndex_FWD_DEFINED__ #define __CTextIndex_FWD_DEFINED__ #ifdef __cplusplus typedef class CTextIndex CTextIndex; #else typedef struct CTextIndex CTextIndex; #endif /* __cplusplus */ #endif /* __CTextIndex_FWD_DEFINED__ */ /* header files for imported files */ #include "prsht.h" #include "mshtml.h" #include "mshtmhst.h" #include "exdisp.h" #include "objsafe.h" #ifdef __cplusplus extern "C"{ #endif void * __RPC_USER MIDL_user_allocate(size_t); void __RPC_USER MIDL_user_free( void * ); #ifndef __IDocumentsScore_INTERFACE_DEFINED__ #define __IDocumentsScore_INTERFACE_DEFINED__ /* interface IDocumentsScore */ /* [unique][helpstring][dual][uuid][object] */ EXTERN_C const IID IID_IDocumentsScore; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("1741BA73-3BC1-4CD0-BFF1-8CB5FA5C077A") IDocumentsScore : public IDispatch { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Size( /* [retval][out] */ LONG *pVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetDocument( /* [in] */ LONG index, /* [retval][out] */ BSTR *document) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetScore( /* [in] */ LONG index, /* [retval][out] */ LONG *score) = 0; }; #else /* C style interface */ typedef struct IDocumentsScoreVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IDocumentsScore * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IDocumentsScore * This); ULONG ( STDMETHODCALLTYPE *Release )( IDocumentsScore * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( IDocumentsScore * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( IDocumentsScore * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( IDocumentsScore * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( IDocumentsScore * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size )( IDocumentsScore * This, /* [retval][out] */ LONG *pVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetDocument )( IDocumentsScore * This, /* [in] */ LONG index, /* [retval][out] */ BSTR *document); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetScore )( IDocumentsScore * This, /* [in] */ LONG index, /* [retval][out] */ LONG *score); END_INTERFACE } IDocumentsScoreVtbl; interface IDocumentsScore { CONST_VTBL struct IDocumentsScoreVtbl *lpVtbl; }; #ifdef COBJMACROS #define IDocumentsScore_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IDocumentsScore_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IDocumentsScore_Release(This) \ (This)->lpVtbl -> Release(This) #define IDocumentsScore_GetTypeInfoCount(This,pctinfo) \ (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) #define IDocumentsScore_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define IDocumentsScore_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define IDocumentsScore_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #define IDocumentsScore_get_Size(This,pVal) \ (This)->lpVtbl -> get_Size(This,pVal) #define IDocumentsScore_GetDocument(This,index,document) \ (This)->lpVtbl -> GetDocument(This,index,document) #define IDocumentsScore_GetScore(This,index,score) \ (This)->lpVtbl -> GetScore(This,index,score) #endif /* COBJMACROS */ #endif /* C style interface */ /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IDocumentsScore_get_Size_Proxy( IDocumentsScore * This, /* [retval][out] */ LONG *pVal); void __RPC_STUB IDocumentsScore_get_Size_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IDocumentsScore_GetDocument_Proxy( IDocumentsScore * This, /* [in] */ LONG index, /* [retval][out] */ BSTR *document); void __RPC_STUB IDocumentsScore_GetDocument_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IDocumentsScore_GetScore_Proxy( IDocumentsScore * This, /* [in] */ LONG index, /* [retval][out] */ LONG *score); void __RPC_STUB IDocumentsScore_GetScore_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IDocumentsScore_INTERFACE_DEFINED__ */ #ifndef __ITextIndex_INTERFACE_DEFINED__ #define __ITextIndex_INTERFACE_DEFINED__ /* interface ITextIndex */ /* [unique][helpstring][dual][uuid][object] */ EXTERN_C const IID IID_ITextIndex; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("3DF00A4D-6253-4D65-A586-6CE5E29B8980") ITextIndex : public IDispatch { public: virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE AddWord( /* [in] */ BSTR *word, /* [in] */ BSTR *document) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE AddText( /* [in] */ BSTR *text, /* [in] */ BSTR *document) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Pack( void) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE FindWord( /* [in] */ BSTR *word, /* [retval][out] */ IDocumentsScore **result) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE FindTextA( /* [in] */ BSTR *text, /* [in] */ LONG intersect, /* [retval][out] */ IDocumentsScore **result) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Version( /* [retval][out] */ BSTR *pVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Load( /* [in] */ BSTR *filename, /* [retval][out] */ LONG *result) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Save( /* [in] */ BSTR *filename, /* [retval][out] */ LONG *result) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE RemoveDocument( /* [in] */ BSTR *document) = 0; }; #else /* C style interface */ typedef struct ITextIndexVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( ITextIndex * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( ITextIndex * This); ULONG ( STDMETHODCALLTYPE *Release )( ITextIndex * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( ITextIndex * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( ITextIndex * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( ITextIndex * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( ITextIndex * This, /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *AddWord )( ITextIndex * This, /* [in] */ BSTR *word, /* [in] */ BSTR *document); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *AddText )( ITextIndex * This, /* [in] */ BSTR *text, /* [in] */ BSTR *document); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Pack )( ITextIndex * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *FindWord )( ITextIndex * This, /* [in] */ BSTR *word, /* [retval][out] */ IDocumentsScore **result); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *FindTextA )( ITextIndex * This, /* [in] */ BSTR *text, /* [in] */ LONG intersect, /* [retval][out] */ IDocumentsScore **result); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Version )( ITextIndex * This, /* [retval][out] */ BSTR *pVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Load )( ITextIndex * This, /* [in] */ BSTR *filename, /* [retval][out] */ LONG *result); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Save )( ITextIndex * This, /* [in] */ BSTR *filename, /* [retval][out] */ LONG *result); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *RemoveDocument )( ITextIndex * This, /* [in] */ BSTR *document); END_INTERFACE } ITextIndexVtbl; interface ITextIndex { CONST_VTBL struct ITextIndexVtbl *lpVtbl; }; #ifdef COBJMACROS #define ITextIndex_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define ITextIndex_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define ITextIndex_Release(This) \ (This)->lpVtbl -> Release(This) #define ITextIndex_GetTypeInfoCount(This,pctinfo) \ (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) #define ITextIndex_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) #define ITextIndex_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) #define ITextIndex_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) #define ITextIndex_AddWord(This,word,document) \ (This)->lpVtbl -> AddWord(This,word,document) #define ITextIndex_AddText(This,text,document) \ (This)->lpVtbl -> AddText(This,text,document) #define ITextIndex_Pack(This) \ (This)->lpVtbl -> Pack(This) #define ITextIndex_FindWord(This,word,result) \ (This)->lpVtbl -> FindWord(This,word,result) #define ITextIndex_FindTextA(This,text,intersect,result) \ (This)->lpVtbl -> FindTextA(This,text,intersect,result) #define ITextIndex_get_Version(This,pVal) \ (This)->lpVtbl -> get_Version(This,pVal) #define ITextIndex_Load(This,filename,result) \ (This)->lpVtbl -> Load(This,filename,result) #define ITextIndex_Save(This,filename,result) \ (This)->lpVtbl -> Save(This,filename,result) #define ITextIndex_RemoveDocument(This,document) \ (This)->lpVtbl -> RemoveDocument(This,document) #endif /* COBJMACROS */ #endif /* C style interface */ /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE ITextIndex_AddWord_Proxy( ITextIndex * This, /* [in] */ BSTR *word, /* [in] */ BSTR *document); void __RPC_STUB ITextIndex_AddWord_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE ITextIndex_AddText_Proxy( ITextIndex * This, /* [in] */ BSTR *text, /* [in] */ BSTR *document); void __RPC_STUB ITextIndex_AddText_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE ITextIndex_Pack_Proxy( ITextIndex * This); void __RPC_STUB ITextIndex_Pack_Stub( IRpcStubBuffer *This, diff --git a/com/tstlib/_tstlib.idl b/com/tstlib/_tstlib.idl index 32d81b2..1014172 100644 --- a/com/tstlib/_tstlib.idl +++ b/com/tstlib/_tstlib.idl @@ -1,73 +1,73 @@ -import "E:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\include\prsht.idl"; -import "E:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\include\mshtml.idl"; -import "e:\program files\microsoft visual studio .net 2003\vc7\platformsdk\include\dimm.idl"; -import "E:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\include\mshtmhst.idl"; -import "e:\program files\microsoft visual studio .net 2003\vc7\platformsdk\include\docobj.idl"; -import "E:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\include\exdisp.idl"; -import "E:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\include\objsafe.idl"; +import "C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\include\prsht.idl"; +import "C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\include\mshtml.idl"; +import "c:\program files\microsoft visual studio .net 2003\vc7\platformsdk\include\dimm.idl"; +import "C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\include\mshtmhst.idl"; +import "c:\program files\microsoft visual studio .net 2003\vc7\platformsdk\include\docobj.idl"; +import "C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\include\exdisp.idl"; +import "C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\include\objsafe.idl"; [ object, uuid(1741BA73-3BC1-4CD0-BFF1-8CB5FA5C077A), dual, helpstring("Interface IDocumentsScore"), pointer_default(unique) ] -#line 35 "c:\\projets\\development\\tst\\com\\tstlib\\documentsscore.h" +#line 35 "d:\\projets\\tst\\com\\tstlib\\documentsscore.h" interface IDocumentsScore : IDispatch { -#line 37 "c:\\projets\\development\\tst\\com\\tstlib\\documentsscore.h" +#line 37 "d:\\projets\\tst\\com\\tstlib\\documentsscore.h" [propget,id(1),helpstring("property Size")] HRESULT Size([out,retval] LONG *pVal); [id(2),helpstring("method GetDocument")] HRESULT GetDocument([in] LONG index, [out,retval] BSTR *document ); [id(3),helpstring("method GetScore")] HRESULT GetScore([in] LONG index, [out,retval] LONG *score); }; [ object, uuid(3DF00A4D-6253-4D65-A586-6CE5E29B8980), dual, helpstring("Interface ITextIndex"), pointer_default(unique) ] -#line 18 "c:\\projets\\development\\tst\\com\\tstlib\\textindex.h" +#line 18 "d:\\projets\\tst\\com\\tstlib\\textindex.h" interface ITextIndex : IDispatch { -#line 20 "c:\\projets\\development\\tst\\com\\tstlib\\textindex.h" +#line 20 "d:\\projets\\tst\\com\\tstlib\\textindex.h" [id(1),helpstring("method AddWord")] HRESULT AddWord([in] BSTR *word , [in] BSTR *document ); [id(2),helpstring("method AddText")] HRESULT AddText([in] BSTR *text , [in] BSTR *document ); [id(3),helpstring("method Pack")] HRESULT Pack(); [id(4),helpstring("method FindWord")] HRESULT FindWord([in] BSTR *word , [out,retval] IDocumentsScore **result ); [id(5),helpstring("method FindText")] HRESULT FindTextA([in] BSTR *text , [in] LONG intersect, [out,retval] IDocumentsScore **result ); [propget,id(6),helpstring("property Version")] HRESULT Version([out,retval] BSTR *pVal ); [id(7),helpstring("method Load")] HRESULT Load([in] BSTR *filename , [out,retval] LONG *result); [id(8),helpstring("method Save")] HRESULT Save([in] BSTR *filename , [out,retval] LONG *result); [id(9),helpstring("method RemoveDocument")] HRESULT RemoveDocument([in] BSTR *document ); }; [ version(1.0), uuid(013A8F97-F0CA-4F8E-BA0E-75B1FEB9DF79), helpstring("Bibliotheque de types tstlib 1.0") ] library tstlib { importlib("stdole2.tlb"); importlib("olepro32.dll"); [ version(1.0), uuid(98F35214-F66B-4BBF-B039-1AA4CA344DCF), helpstring("DocumentsScore Class") ] -#line 55 "c:\\projets\\development\\tst\\com\\tstlib\\documentsscore.h" +#line 55 "d:\\projets\\tst\\com\\tstlib\\documentsscore.h" coclass CDocumentsScore { interface IDocumentsScore; }; [ version(1.0), uuid(8EC92961-CAB3-4CA6-A36E-46C39424E80B), helpstring("TextIndex Class") ] -#line 45 "c:\\projets\\development\\tst\\com\\tstlib\\textindex.h" +#line 45 "d:\\projets\\tst\\com\\tstlib\\textindex.h" coclass CTextIndex { interface ITextIndex; }; } diff --git a/com/tstlib/_tstlib.tlb b/com/tstlib/_tstlib.tlb index 3250b8f..82b475d 100644 Binary files a/com/tstlib/_tstlib.tlb and b/com/tstlib/_tstlib.tlb differ diff --git a/com/tstlib/_tstlib_i.c b/com/tstlib/_tstlib_i.c index 452a4e6..e12952a 100644 --- a/com/tstlib/_tstlib_i.c +++ b/com/tstlib/_tstlib_i.c @@ -1,96 +1,96 @@ /* this ALWAYS GENERATED file contains the IIDs and CLSIDs */ /* link this file in with the server and any clients */ /* File created by MIDL compiler version 6.00.0361 */ -/* at Sat Apr 01 15:31:23 2006 +/* at Sun Jul 16 11:58:43 2006 */ /* Compiler settings for _tstlib.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #if !defined(_M_IA64) && !defined(_M_AMD64) #pragma warning( disable: 4049 ) /* more than 64k source lines */ #ifdef __cplusplus extern "C"{ #endif #include <rpc.h> #include <rpcndr.h> #ifdef _MIDL_USE_GUIDDEF_ #ifndef INITGUID #define INITGUID #include <guiddef.h> #undef INITGUID #else #include <guiddef.h> #endif #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ DEFINE_GUID(name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) #else // !_MIDL_USE_GUIDDEF_ #ifndef __IID_DEFINED__ #define __IID_DEFINED__ typedef struct _IID { unsigned long x; unsigned short s1; unsigned short s2; unsigned char c[8]; } IID; #endif // __IID_DEFINED__ #ifndef CLSID_DEFINED #define CLSID_DEFINED typedef IID CLSID; #endif // CLSID_DEFINED #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #endif !_MIDL_USE_GUIDDEF_ MIDL_DEFINE_GUID(IID, IID_IDocumentsScore,0x1741BA73,0x3BC1,0x4CD0,0xBF,0xF1,0x8C,0xB5,0xFA,0x5C,0x07,0x7A); MIDL_DEFINE_GUID(IID, IID_ITextIndex,0x3DF00A4D,0x6253,0x4D65,0xA5,0x86,0x6C,0xE5,0xE2,0x9B,0x89,0x80); MIDL_DEFINE_GUID(IID, LIBID_tstlib,0x013A8F97,0xF0CA,0x4F8E,0xBA,0x0E,0x75,0xB1,0xFE,0xB9,0xDF,0x79); MIDL_DEFINE_GUID(CLSID, CLSID_CDocumentsScore,0x98F35214,0xF66B,0x4BBF,0xB0,0x39,0x1A,0xA4,0xCA,0x34,0x4D,0xCF); MIDL_DEFINE_GUID(CLSID, CLSID_CTextIndex,0x8EC92961,0xCAB3,0x4CA6,0xA3,0x6E,0x46,0xC3,0x94,0x24,0xE8,0x0B); #undef MIDL_DEFINE_GUID #ifdef __cplusplus } #endif #endif /* !defined(_M_IA64) && !defined(_M_AMD64)*/ diff --git a/com/tstlib/_tstlib_p.c b/com/tstlib/_tstlib_p.c index fd0d8a9..d1a078a 100644 --- a/com/tstlib/_tstlib_p.c +++ b/com/tstlib/_tstlib_p.c @@ -1,519 +1,519 @@ /* this ALWAYS GENERATED file contains the proxy stub code */ /* File created by MIDL compiler version 6.00.0361 */ -/* at Sat Apr 01 15:31:23 2006 +/* at Sun Jul 16 11:58:43 2006 */ /* Compiler settings for _tstlib.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #if !defined(_M_IA64) && !defined(_M_AMD64) #pragma warning( disable: 4049 ) /* more than 64k source lines */ #if _MSC_VER >= 1200 #pragma warning(push) #endif #pragma warning( disable: 4100 ) /* unreferenced arguments in x86 call */ #pragma warning( disable: 4211 ) /* redefine extent to static */ #pragma warning( disable: 4232 ) /* dllimport identity*/ #define USE_STUBLESS_PROXY /* verify that the <rpcproxy.h> version is high enough to compile this file*/ #ifndef __REDQ_RPCPROXY_H_VERSION__ #define __REQUIRED_RPCPROXY_H_VERSION__ 475 #endif #include "rpcproxy.h" #ifndef __RPCPROXY_H_VERSION__ #error this stub requires an updated version of <rpcproxy.h> #endif // __RPCPROXY_H_VERSION__ #include "_tstlib.h" #define TYPE_FORMAT_STRING_SIZE 87 #define PROC_FORMAT_STRING_SIZE 481 #define TRANSMIT_AS_TABLE_SIZE 0 #define WIRE_MARSHAL_TABLE_SIZE 1 typedef struct _MIDL_TYPE_FORMAT_STRING { short Pad; unsigned char Format[ TYPE_FORMAT_STRING_SIZE ]; } MIDL_TYPE_FORMAT_STRING; typedef struct _MIDL_PROC_FORMAT_STRING { short Pad; unsigned char Format[ PROC_FORMAT_STRING_SIZE ]; } MIDL_PROC_FORMAT_STRING; static RPC_SYNTAX_IDENTIFIER _RpcTransferSyntax = {{0x8A885D04,0x1CEB,0x11C9,{0x9F,0xE8,0x08,0x00,0x2B,0x10,0x48,0x60}},{2,0}}; extern const MIDL_TYPE_FORMAT_STRING __MIDL_TypeFormatString; extern const MIDL_PROC_FORMAT_STRING __MIDL_ProcFormatString; extern const MIDL_STUB_DESC Object_StubDesc; extern const MIDL_SERVER_INFO IDocumentsScore_ServerInfo; extern const MIDL_STUBLESS_PROXY_INFO IDocumentsScore_ProxyInfo; extern const MIDL_STUB_DESC Object_StubDesc; extern const MIDL_SERVER_INFO ITextIndex_ServerInfo; extern const MIDL_STUBLESS_PROXY_INFO ITextIndex_ProxyInfo; extern const USER_MARSHAL_ROUTINE_QUADRUPLE UserMarshalRoutines[ WIRE_MARSHAL_TABLE_SIZE ]; #if !defined(__RPC_WIN32__) #error Invalid build platform for this stub. #endif #if !(TARGET_IS_NT50_OR_LATER) #error You need a Windows 2000 or later to run this stub because it uses these features: #error /robust command line switch. #error However, your C/C++ compilation flags indicate you intend to run this app on earlier systems. #error This app will die there with the RPC_X_WRONG_STUB_VERSION error. #endif static const MIDL_PROC_FORMAT_STRING __MIDL_ProcFormatString = { 0, { /* Procedure get_Size */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 2 */ NdrFcLong( 0x0 ), /* 0 */ /* 6 */ NdrFcShort( 0x7 ), /* 7 */ /* 8 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ /* 10 */ NdrFcShort( 0x0 ), /* 0 */ /* 12 */ NdrFcShort( 0x24 ), /* 36 */ /* 14 */ 0x44, /* Oi2 Flags: has return, has ext, */ 0x2, /* 2 */ /* 16 */ 0x8, /* 8 */ 0x1, /* Ext Flags: new corr desc, */ /* 18 */ NdrFcShort( 0x0 ), /* 0 */ /* 20 */ NdrFcShort( 0x0 ), /* 0 */ /* 22 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter pVal */ /* 24 */ NdrFcShort( 0x2150 ), /* Flags: out, base type, simple ref, srv alloc size=8 */ /* 26 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ /* 28 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Return value */ /* 30 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 32 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ /* 34 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure GetDocument */ /* 36 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 38 */ NdrFcLong( 0x0 ), /* 0 */ /* 42 */ NdrFcShort( 0x8 ), /* 8 */ /* 44 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ /* 46 */ NdrFcShort( 0x8 ), /* 8 */ /* 48 */ NdrFcShort( 0x8 ), /* 8 */ /* 50 */ 0x45, /* Oi2 Flags: srv must size, has return, has ext, */ 0x3, /* 3 */ /* 52 */ 0x8, /* 8 */ 0x3, /* Ext Flags: new corr desc, clt corr check, */ /* 54 */ NdrFcShort( 0x1 ), /* 1 */ /* 56 */ NdrFcShort( 0x0 ), /* 0 */ /* 58 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter index */ /* 60 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ /* 62 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ /* 64 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Parameter document */ /* 66 */ NdrFcShort( 0x2113 ), /* Flags: must size, must free, out, simple ref, srv alloc size=8 */ /* 68 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ /* 70 */ NdrFcShort( 0x24 ), /* Type Offset=36 */ /* Return value */ /* 72 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 74 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ /* 76 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure GetScore */ /* 78 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 80 */ NdrFcLong( 0x0 ), /* 0 */ /* 84 */ NdrFcShort( 0x9 ), /* 9 */ /* 86 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ /* 88 */ NdrFcShort( 0x8 ), /* 8 */ /* 90 */ NdrFcShort( 0x24 ), /* 36 */ /* 92 */ 0x44, /* Oi2 Flags: has return, has ext, */ 0x3, /* 3 */ /* 94 */ 0x8, /* 8 */ 0x1, /* Ext Flags: new corr desc, */ /* 96 */ NdrFcShort( 0x0 ), /* 0 */ /* 98 */ NdrFcShort( 0x0 ), /* 0 */ /* 100 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter index */ /* 102 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ /* 104 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ /* 106 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Parameter score */ /* 108 */ NdrFcShort( 0x2150 ), /* Flags: out, base type, simple ref, srv alloc size=8 */ /* 110 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ /* 112 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Return value */ /* 114 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 116 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ /* 118 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure AddWord */ /* 120 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 122 */ NdrFcLong( 0x0 ), /* 0 */ /* 126 */ NdrFcShort( 0x7 ), /* 7 */ /* 128 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ /* 130 */ NdrFcShort( 0x0 ), /* 0 */ /* 132 */ NdrFcShort( 0x8 ), /* 8 */ /* 134 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x3, /* 3 */ /* 136 */ 0x8, /* 8 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ /* 138 */ NdrFcShort( 0x0 ), /* 0 */ /* 140 */ NdrFcShort( 0x2 ), /* 2 */ /* 142 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter word */ /* 144 */ NdrFcShort( 0x10b ), /* Flags: must size, must free, in, simple ref, */ /* 146 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ /* 148 */ NdrFcShort( 0x36 ), /* Type Offset=54 */ /* Parameter document */ /* 150 */ NdrFcShort( 0x10b ), /* Flags: must size, must free, in, simple ref, */ /* 152 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ /* 154 */ NdrFcShort( 0x36 ), /* Type Offset=54 */ /* Return value */ /* 156 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 158 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ /* 160 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure AddText */ /* 162 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 164 */ NdrFcLong( 0x0 ), /* 0 */ /* 168 */ NdrFcShort( 0x8 ), /* 8 */ /* 170 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ /* 172 */ NdrFcShort( 0x0 ), /* 0 */ /* 174 */ NdrFcShort( 0x8 ), /* 8 */ /* 176 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x3, /* 3 */ /* 178 */ 0x8, /* 8 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ /* 180 */ NdrFcShort( 0x0 ), /* 0 */ /* 182 */ NdrFcShort( 0x2 ), /* 2 */ /* 184 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter text */ /* 186 */ NdrFcShort( 0x10b ), /* Flags: must size, must free, in, simple ref, */ /* 188 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ /* 190 */ NdrFcShort( 0x36 ), /* Type Offset=54 */ /* Parameter document */ /* 192 */ NdrFcShort( 0x10b ), /* Flags: must size, must free, in, simple ref, */ /* 194 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ /* 196 */ NdrFcShort( 0x36 ), /* Type Offset=54 */ /* Return value */ /* 198 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 200 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ /* 202 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure Pack */ /* 204 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 206 */ NdrFcLong( 0x0 ), /* 0 */ /* 210 */ NdrFcShort( 0x9 ), /* 9 */ /* 212 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ /* 214 */ NdrFcShort( 0x0 ), /* 0 */ /* 216 */ NdrFcShort( 0x8 ), /* 8 */ /* 218 */ 0x44, /* Oi2 Flags: has return, has ext, */ 0x1, /* 1 */ /* 220 */ 0x8, /* 8 */ 0x1, /* Ext Flags: new corr desc, */ /* 222 */ NdrFcShort( 0x0 ), /* 0 */ /* 224 */ NdrFcShort( 0x0 ), /* 0 */ /* 226 */ NdrFcShort( 0x0 ), /* 0 */ /* Return value */ /* 228 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 230 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ /* 232 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure FindWord */ /* 234 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 236 */ NdrFcLong( 0x0 ), /* 0 */ /* 240 */ NdrFcShort( 0xa ), /* 10 */ /* 242 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ /* 244 */ NdrFcShort( 0x0 ), /* 0 */ /* 246 */ NdrFcShort( 0x8 ), /* 8 */ /* 248 */ 0x47, /* Oi2 Flags: srv must size, clt must size, has return, has ext, */ 0x3, /* 3 */ /* 250 */ 0x8, /* 8 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ /* 252 */ NdrFcShort( 0x0 ), /* 0 */ /* 254 */ NdrFcShort( 0x1 ), /* 1 */ /* 256 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter word */ /* 258 */ NdrFcShort( 0x10b ), /* Flags: must size, must free, in, simple ref, */ /* 260 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ /* 262 */ NdrFcShort( 0x36 ), /* Type Offset=54 */ /* Parameter result */ /* 264 */ NdrFcShort( 0x13 ), /* Flags: must size, must free, out, */ /* 266 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ /* 268 */ NdrFcShort( 0x40 ), /* Type Offset=64 */ /* Return value */ /* 270 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 272 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ /* 274 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure FindTextA */ /* 276 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 278 */ NdrFcLong( 0x0 ), /* 0 */ /* 282 */ NdrFcShort( 0xb ), /* 11 */ /* 284 */ NdrFcShort( 0x14 ), /* x86 Stack size/offset = 20 */ /* 286 */ NdrFcShort( 0x8 ), /* 8 */ /* 288 */ NdrFcShort( 0x8 ), /* 8 */ /* 290 */ 0x47, /* Oi2 Flags: srv must size, clt must size, has return, has ext, */ 0x4, /* 4 */ /* 292 */ 0x8, /* 8 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ /* 294 */ NdrFcShort( 0x0 ), /* 0 */ /* 296 */ NdrFcShort( 0x1 ), /* 1 */ /* 298 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter text */ /* 300 */ NdrFcShort( 0x10b ), /* Flags: must size, must free, in, simple ref, */ /* 302 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ /* 304 */ NdrFcShort( 0x36 ), /* Type Offset=54 */ /* Parameter intersect */ /* 306 */ NdrFcShort( 0x48 ), /* Flags: in, base type, */ /* 308 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ /* 310 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Parameter result */ /* 312 */ NdrFcShort( 0x13 ), /* Flags: must size, must free, out, */ /* 314 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ /* 316 */ NdrFcShort( 0x40 ), /* Type Offset=64 */ /* Return value */ /* 318 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 320 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ /* 322 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure get_Version */ /* 324 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 326 */ NdrFcLong( 0x0 ), /* 0 */ /* 330 */ NdrFcShort( 0xc ), /* 12 */ /* 332 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ /* 334 */ NdrFcShort( 0x0 ), /* 0 */ /* 336 */ NdrFcShort( 0x8 ), /* 8 */ /* 338 */ 0x45, /* Oi2 Flags: srv must size, has return, has ext, */ 0x2, /* 2 */ /* 340 */ 0x8, /* 8 */ 0x3, /* Ext Flags: new corr desc, clt corr check, */ /* 342 */ NdrFcShort( 0x1 ), /* 1 */ /* 344 */ NdrFcShort( 0x0 ), /* 0 */ /* 346 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter pVal */ /* 348 */ NdrFcShort( 0x2113 ), /* Flags: must size, must free, out, simple ref, srv alloc size=8 */ /* 350 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ /* 352 */ NdrFcShort( 0x24 ), /* Type Offset=36 */ /* Return value */ /* 354 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 356 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ /* 358 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure Load */ /* 360 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 362 */ NdrFcLong( 0x0 ), /* 0 */ /* 366 */ NdrFcShort( 0xd ), /* 13 */ /* 368 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ /* 370 */ NdrFcShort( 0x0 ), /* 0 */ /* 372 */ NdrFcShort( 0x24 ), /* 36 */ /* 374 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x3, /* 3 */ /* 376 */ 0x8, /* 8 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ /* 378 */ NdrFcShort( 0x0 ), /* 0 */ /* 380 */ NdrFcShort( 0x1 ), /* 1 */ /* 382 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter filename */ /* 384 */ NdrFcShort( 0x10b ), /* Flags: must size, must free, in, simple ref, */ /* 386 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ /* 388 */ NdrFcShort( 0x36 ), /* Type Offset=54 */ /* Parameter result */ /* 390 */ NdrFcShort( 0x2150 ), /* Flags: out, base type, simple ref, srv alloc size=8 */ /* 392 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ /* 394 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Return value */ /* 396 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 398 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ /* 400 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure Save */ /* 402 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 404 */ NdrFcLong( 0x0 ), /* 0 */ /* 408 */ NdrFcShort( 0xe ), /* 14 */ /* 410 */ NdrFcShort( 0x10 ), /* x86 Stack size/offset = 16 */ /* 412 */ NdrFcShort( 0x0 ), /* 0 */ /* 414 */ NdrFcShort( 0x24 ), /* 36 */ /* 416 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x3, /* 3 */ /* 418 */ 0x8, /* 8 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ /* 420 */ NdrFcShort( 0x0 ), /* 0 */ /* 422 */ NdrFcShort( 0x1 ), /* 1 */ /* 424 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter filename */ /* 426 */ NdrFcShort( 0x10b ), /* Flags: must size, must free, in, simple ref, */ /* 428 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ /* 430 */ NdrFcShort( 0x36 ), /* Type Offset=54 */ /* Parameter result */ /* 432 */ NdrFcShort( 0x2150 ), /* Flags: out, base type, simple ref, srv alloc size=8 */ /* 434 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ /* 436 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Return value */ /* 438 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 440 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ /* 442 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ /* Procedure RemoveDocument */ /* 444 */ 0x33, /* FC_AUTO_HANDLE */ 0x6c, /* Old Flags: object, Oi2 */ /* 446 */ NdrFcLong( 0x0 ), /* 0 */ /* 450 */ NdrFcShort( 0xf ), /* 15 */ /* 452 */ NdrFcShort( 0xc ), /* x86 Stack size/offset = 12 */ /* 454 */ NdrFcShort( 0x0 ), /* 0 */ /* 456 */ NdrFcShort( 0x8 ), /* 8 */ /* 458 */ 0x46, /* Oi2 Flags: clt must size, has return, has ext, */ 0x2, /* 2 */ /* 460 */ 0x8, /* 8 */ 0x5, /* Ext Flags: new corr desc, srv corr check, */ /* 462 */ NdrFcShort( 0x0 ), /* 0 */ /* 464 */ NdrFcShort( 0x1 ), /* 1 */ /* 466 */ NdrFcShort( 0x0 ), /* 0 */ /* Parameter document */ /* 468 */ NdrFcShort( 0x10b ), /* Flags: must size, must free, in, simple ref, */ /* 470 */ NdrFcShort( 0x4 ), /* x86 Stack size/offset = 4 */ /* 472 */ NdrFcShort( 0x36 ), /* Type Offset=54 */ /* Return value */ /* 474 */ NdrFcShort( 0x70 ), /* Flags: out, return, base type, */ /* 476 */ NdrFcShort( 0x8 ), /* x86 Stack size/offset = 8 */ /* 478 */ 0x8, /* FC_LONG */ 0x0, /* 0 */ diff --git a/com/tstlib/tstlib.vcproj b/com/tstlib/tstlib.vcproj index a7f5f13..a66c97f 100644 --- a/com/tstlib/tstlib.vcproj +++ b/com/tstlib/tstlib.vcproj @@ -1,239 +1,239 @@ <?xml version="1.0" encoding="Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="7.10" Name="tstlib" ProjectGUID="{9109E041-F4CC-4EBC-9DC7-4C662BF0CBDC}" RootNamespace="tstlib" Keyword="AtlProj"> <Platforms> <Platform Name="Win32"/> </Platforms> <Configurations> <Configuration Name="Debug|Win32" OutputDirectory="Debug" IntermediateDirectory="Debug" ConfigurationType="2" UseOfATL="1" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="D:\projets\boost_1_33_1;..\..\include" PreprocessorDefinitions="WIN32;_WINDOWS;_DEBUG;_USRDLL;_ATL_ATTRIBUTES" MinimalRebuild="TRUE" BasicRuntimeChecks="3" RuntimeLibrary="3" UsePrecompiledHeader="3" WarningLevel="3" Detect64BitPortabilityProblems="TRUE" DebugInformationFormat="4"/> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" IgnoreImportLibrary="TRUE" AdditionalOptions="comsupp.lib" OutputFile="$(OutDir)/tstlib.dll" LinkIncremental="2" AdditionalLibraryDirectories="&quot;D:\projets\boost_1_33_1\bin\boost\libs\regex\build\libboost_regex.lib\vc-7_1\debug\threading-multi&quot;" MergedIDLBaseFileName="_tstlib.idl" GenerateDebugInformation="TRUE" SubSystem="2" ImportLibrary="$(OutDir)/tstlib.lib" TargetMachine="1"/> <Tool Name="VCMIDLTool" PreprocessorDefinitions="_DEBUG" MkTypLibCompatible="FALSE" TargetEnvironment="1" GenerateStublessProxies="TRUE" TypeLibraryName="$(IntDir)/tstlib.tlb" HeaderFileName="tstlib.h" DLLDataFileName="" InterfaceIdentifierFileName="tstlib_i.c" ProxyFileName="tstlib_p.c"/> <Tool Name="VCPostBuildEventTool" Description="Inscription en cours" CommandLine="regsvr32 /s /c &quot;$(TargetPath)&quot;"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="_DEBUG" Culture="1036" AdditionalIncludeDirectories="$(IntDir)"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCXMLDataGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <Tool Name="VCManagedWrapperGeneratorTool"/> <Tool Name="VCAuxiliaryManagedWrapperGeneratorTool"/> </Configuration> <Configuration Name="Release|Win32" OutputDirectory="Release" IntermediateDirectory="Release" ConfigurationType="2" UseOfATL="1" ATLMinimizesCRunTimeLibraryUsage="FALSE" CharacterSet="2"> <Tool Name="VCCLCompilerTool" - AdditionalIncludeDirectories="c:\projets\boost_1_33_1\;..\..\include" + AdditionalIncludeDirectories="d:\projets\boost_1_33_1\;..\..\include" PreprocessorDefinitions="WIN32;_WINDOWS;NDEBUG;_USRDLL;_ATL_ATTRIBUTES" RuntimeLibrary="2" UsePrecompiledHeader="3" WarningLevel="3" Detect64BitPortabilityProblems="TRUE" DebugInformationFormat="3"/> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" IgnoreImportLibrary="TRUE" AdditionalOptions="comsupp.lib" OutputFile="$(OutDir)/tstlib.dll" LinkIncremental="1" - AdditionalLibraryDirectories="&quot;c:\projets\boost_1_33_1\bin\boost\libs\regex\build\libboost_regex.lib\vc-7_1\release\threading-multi&quot;" + AdditionalLibraryDirectories="&quot;d:\projets\boost_1_33_1\bin\boost\libs\regex\build\libboost_regex.lib\vc-7_1\release\threading-multi&quot;" MergedIDLBaseFileName="_tstlib.idl" GenerateDebugInformation="TRUE" SubSystem="2" OptimizeReferences="2" EnableCOMDATFolding="2" ImportLibrary="$(OutDir)/tstlib.lib" TargetMachine="1"/> <Tool Name="VCMIDLTool" PreprocessorDefinitions="NDEBUG" MkTypLibCompatible="FALSE" TargetEnvironment="1" GenerateStublessProxies="TRUE" TypeLibraryName="$(IntDir)/tstlib.tlb" HeaderFileName="tstlib.h" DLLDataFileName="" InterfaceIdentifierFileName="tstlib_i.c" ProxyFileName="tstlib_p.c"/> <Tool Name="VCPostBuildEventTool" Description="Inscription en cours" CommandLine="regsvr32 /s /c &quot;$(TargetPath)&quot;"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool" PreprocessorDefinitions="NDEBUG" Culture="1036" AdditionalIncludeDirectories="$(IntDir)"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCXMLDataGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <Tool Name="VCManagedWrapperGeneratorTool"/> <Tool Name="VCAuxiliaryManagedWrapperGeneratorTool"/> </Configuration> </Configurations> <References> </References> <Files> <Filter Name="Source Files" Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> <File RelativePath=".\DocumentsScore.cpp"> </File> <File RelativePath=".\stdafx.cpp"> <FileConfiguration Name="Debug|Win32"> <Tool Name="VCCLCompilerTool" UsePrecompiledHeader="1"/> </FileConfiguration> <FileConfiguration Name="Release|Win32"> <Tool Name="VCCLCompilerTool" UsePrecompiledHeader="1"/> </FileConfiguration> </File> <File RelativePath=".\testcom.py"> </File> <File RelativePath=".\TextIndex.cpp"> </File> <File RelativePath=".\tstlib.cpp"> </File> </Filter> <Filter Name="Header Files" Filter="h;hpp;hxx;hm;inl;inc;xsd" UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"> <File RelativePath="..\..\include\debug.h"> </File> <File RelativePath=".\DocumentsScore.h"> </File> <File RelativePath="..\..\include\fundamentals.h"> </File> <File RelativePath="..\..\include\iterators.h"> </File> <File RelativePath="..\..\include\memory_storage.h"> </File> <File RelativePath=".\Resource.h"> </File> <File RelativePath=".\stdafx.h"> </File> <File - RelativePath="..\..\textindex\textindex.h"> + RelativePath=".\TextIndex.h"> </File> <File - RelativePath=".\TextIndex.h"> + RelativePath="..\..\textindex\textindex.h"> </File> <File RelativePath="..\..\include\tst.h"> </File> </Filter> <Filter Name="Resource Files" Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx" UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"> <File RelativePath=".\tstlib.rc"> </File> <File RelativePath=".\tstlib.rgs"> </File> </Filter> <File RelativePath=".\ReadMe.txt"> </File> </Files> <Globals> </Globals> </VisualStudioProject> diff --git a/com/tstlib/tstlibPS.vcproj.vspscc b/com/tstlib/tstlibPS.vcproj.vspscc index 6cb031b..abb1ef2 100644 --- a/com/tstlib/tstlibPS.vcproj.vspscc +++ b/com/tstlib/tstlibPS.vcproj.vspscc @@ -1,10 +1,13 @@ "" { "FILE_VERSION" = "9237" "ENLISTMENT_CHOICE" = "NEVER" "PROJECT_FILE_RELATIVE_PATH" = "" -"NUMBER_OF_EXCLUDED_FILES" = "0" +"NUMBER_OF_EXCLUDED_FILES" = "3" +"EXCLUDED_FILE0" = "_tstlib_p.c" +"EXCLUDED_FILE1" = "dlldata.c" +"EXCLUDED_FILE2" = "_tstlib_i.c" "ORIGINAL_PROJECT_FILE_PATH" = "" "NUMBER_OF_NESTED_PROJECTS" = "0" "SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROJECT" } diff --git a/include/tst.h b/include/tst.h index 4b108c0..f966336 100644 --- a/include/tst.h +++ b/include/tst.h @@ -927,555 +927,555 @@ template<typename charT,typename valueT,typename storageT,typename serializerT, walk_recurse(storage->get(other_index),current_key,filter,to_perform); } // ++KEY current_key.push_back(current_node->c); valueT data = current_node->data; if(data!=default_value) { if(filter) { data = filter->perform(current_key,0,data); } if(to_perform) { to_perform->perform(current_key,0,data); } } other_index=current_node->next; if(other_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(other_index),current_key,filter,to_perform); } // --KEY current_key.resize(current_key.size()-1); other_index=current_node->right; if(other_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(other_index),current_key,filter,to_perform); } } /**************************** prefix_match *************************************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::prefix_match(const stringT & string,filter<charT,valueT,stringT>* filter,action<charT,valueT,stringT>* to_perform) const { stringT current_key; size_t position=0; valueT biggest=default_value; int biggest_length=0; int current_index=root; tst_node<charT,valueT>* current_node; int diff; charT c; while(position<string.size()) { c = string[position]; ++position; current_key.push_back(c); while(current_index!=UNDEFINED_INDEX) { current_node=storage->get(current_index); diff=c-current_node->c; if(diff==0) { if(current_node->data!=default_value) { biggest=current_node->data; biggest_length=current_key.size(); if(filter) { biggest=filter->perform(current_key.substr(0,biggest_length),0,biggest); } } if(position<string.size()) { current_index=current_node->next; break; } else { if(biggest!=default_value && to_perform) { to_perform->perform(current_key.substr(0,biggest_length),0,biggest); } current_index=current_node->next; if(current_index!=UNDEFINED_INDEX) { walk_recurse(storage->get(current_index),current_key,filter,to_perform); } return to_perform->result(); } } else if(diff>0) { current_index=current_node->right; } else { current_index=current_node->left; } } if(current_index==UNDEFINED_INDEX) { break; } } if(biggest!=default_value && to_perform) { to_perform->perform(current_key.substr(0,biggest_length),0,biggest); } return to_perform->result(); } /**************************** scan *************************************/ #ifdef SCANNER template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::scan(const stringT & string,action<charT,valueT,stringT>* to_perform) { // Le premier caractère de la chaine ne correspondant pas à un match size_t si_non_match_start=0; // Le noeud pour lequel on a enregistré un match (noeud avec un objet associé) int ni_best_match=UNDEFINED_INDEX; // Le premier caractère de la chaine correspondant à un match int si_match_start=UNDEFINED_INDEX; // La position actuelle dans la chaîne (index) size_t si_current=0; // Le numéro du noeud actuel de l'arbre int ni_current=root; // Le noeud actuel de l'arbre tst_node<charT,valueT> *n_current; // Boucle principale while(1) { n_current = storage->get(ni_current); // On avance dans l'arbre d'un cran if(si_current<string.size()) { int diff=string[si_current]-n_current->c; if(diff>0) { ni_current=n_current->right; } else if(diff<0) { ni_current=n_current->left; } else { // ok, le caractère courant est accepté if(si_match_start==UNDEFINED_INDEX) { // Si on n'a pas encore enregistré un début de match // on le fait si_match_start=si_current; } if(n_current->data!=default_value) { // Si le noeud en cours contient une valeur // on l'enregistre ni_best_match=ni_current; } ++si_current; if(si_current<string.size()) { // Si on peut avancer, on avance ni_current=n_current->next; } else { // Fin de chaine ==> pas de match possible ni_current=UNDEFINED_INDEX; } } } else { // On est toujours en fin de chaine ==> pas de match possible ni_current=UNDEFINED_INDEX; } if(ni_current==UNDEFINED_INDEX) { // Le caractère courant n'est pas accepté if(ni_best_match!=UNDEFINED_INDEX) { // Si on a un match réussi en cours // Si le match en cours démarre après la zone de non-match // C'est qu'on a bien une zone de non-match int non_match_length = si_match_start-si_non_match_start; if(non_match_length>0) { // On l'envoie. to_perform->perform(string.substr(si_non_match_start,non_match_length),-non_match_length,default_value); } // On envoie maintenant le match // On connait sa longueur grâce à la position dans l'arbre // TODO: voir si on ne pourrait pas de passer de ça tst_node<charT,valueT> *match_node=storage->get(ni_best_match); int match_length = match_node->position+1; // On envoie le match to_perform->perform(string.substr(si_match_start,match_length),match_length,match_node->data); // On repositionne la zone de non-match juste après la fin du match si_non_match_start=si_match_start+match_length; // Annulation du match ni_best_match=UNDEFINED_INDEX; // On backtracke compute_backtrack(n_current,string,si_non_match_start,si_current); // Le backtrack nous donne là où on se trouve dans le noeud juste après le match... ni_current = n_current->backtrack; // ... et là où on avait notre meilleur match ni_best_match = n_current->backtrack_match_index; if(ni_current==root) { // quand on a un retour à la racine, on n'a aucun match en cours si_match_start=UNDEFINED_INDEX; } else { // sinon c'est qu'un match est en cours, on va recalculer son point de démarrage // grâce à la position du noeud n_current=storage->get(ni_current); si_match_start=si_current-n_current->position; } } else if(si_match_start!=UNDEFINED_INDEX) { if(si_current<string.size()) { // Si on n'est pas en fin de chaîne... // Si le caractère courant n'est pas accepté, qu'on avait commencé // un match mais que celui-ci n'avait pas réussi, on va backtracker. compute_backtrack(n_current,string,si_match_start+1,si_current); ni_current = n_current->backtrack; ni_best_match=n_current->backtrack_match_index; if(ni_current==root) { // Quand on a un retour à la racine, on n'a aucun match en cours si_match_start=UNDEFINED_INDEX; } else { // sinon c'est qu'un match est en cours, on va recalculer son point de démarrage // grâce à la position du noeud n_current=storage->get(ni_current); si_match_start=si_current-n_current->position; } } else { // Si on est en fin de chaîne, on sort. break; } } else { // le caractère courant n'est pas accepté et on n'avait pas de match en cours if(si_current<string.size()) { // si on peut avancer d'un caractère on le fait ++si_current; // on revient à la racine ni_current = root; } else { // si on est à la fin de la chaîne on sort de la boucle pour la fin. break; } } } else { // on avance tranquillement dans l'arbre... } } // on n'arrive ici que si on est arrivé à la fin de la chaine en entrée if((si_current - si_non_match_start)>0) { // charT'il y avait un non-match en cours // on l'envoie to_perform->perform(string.substr(si_non_match_start,si_current - si_non_match_start),-static_cast<int>(si_current - si_non_match_start),default_value); } return to_perform->result(); } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::compute_backtrack(tst_node<charT,valueT> *current_node,const stringT & string, int si_match_start, int si_match_end) { if(current_node->backtrack==UNDEFINED_INDEX) { while(si_match_start<si_match_end) { current_node->backtrack=root; current_node->backtrack_match_index=UNDEFINED_INDEX; find_node(&(current_node->backtrack),&(current_node->backtrack_match_index),string.substr(si_match_start,si_match_end-si_match_start)); if(current_node->backtrack==UNDEFINED_INDEX) { ++si_match_start; } else { current_node->backtrack=(storage->get(current_node->backtrack))->next; break; } } if(current_node->backtrack==UNDEFINED_INDEX) { current_node->backtrack=root; current_node->backtrack_match_index=UNDEFINED_INDEX; } } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> valueT tst<charT,valueT,storageT,serializerT,stringT>::scan_with_stop_chars(const stringT & string,const stringT& stop_chars,action<charT,valueT,stringT>* to_perform) const { // Le premier caractère de la chaine ne correspondant pas à un match size_t si_non_match_start=0; // Le noeud pour lequel on a enregistré un match (noeud avec un objet associé) int ni_best_match=UNDEFINED_INDEX; // Le premier caractère de la chaine correspondant à un match int si_match_start=UNDEFINED_INDEX; // La position actuelle dans la chaîne (index) size_t si_current=0; // Le numéro du noeud actuel de l'arbre int ni_current=root; // Le noeud actuel de l'arbre tst_node<charT,valueT> *n_current; // Boucle principale while(1) { n_current=storage->get(ni_current); // On avance dans l'arbre d'un cran if(si_current<string.size()) { int diff = string[si_current]-n_current->c; if(diff>0) { ni_current = n_current->right; } else if(diff<0) { ni_current = n_current->left; } else { // ok, le caractère courant est accepté if(si_match_start==UNDEFINED_INDEX) { // On teste si le début de match est le début de chaine ou après un stop_char if(si_current==0 || stop_chars.find(string[si_current-1])<stop_chars.size()) { // oui, on enregistre le début si_match_start=si_current; } else { // non, on passe à la suite ++si_current; } } if(si_match_start!=UNDEFINED_INDEX) { // si le démarrage a bien pris if(n_current->data!=default_value && (si_current==(string.size()-1) || stop_chars.find(string[si_current+1])<stop_chars.size())) { // on a une donnée dans le noeud courant // et on est en fin de chaîne ou le caractère précédent est un stop_char ni_best_match = ni_current; } ++si_current; if(si_current<string.size()) { // Si on peut avancer, on avance ni_current = n_current->next; } else { // Fin de chaine ==> pas de match possible ni_current = UNDEFINED_INDEX; } } } } else { // On est toujours en fin de chaine ==> pas de match possible ni_current = UNDEFINED_INDEX; } if(ni_current==UNDEFINED_INDEX) { // Le caractère courant n'est pas accepté if(ni_best_match!=UNDEFINED_INDEX) { // Si on a un match réussi en cours // Si le match en cours démarre après la zone de non-match // C'est qu'on a bien une zone de non-match int non_match_length = si_match_start-si_non_match_start; if(non_match_length>0) { // On l'envoie. to_perform->perform(string.substr(si_non_match_start,non_match_length),-non_match_length,default_value); } // On envoie maintenant le match // On connait sa longueur grâce à la position dans l'arbre // TODO: voir si on ne pourrait pas de passer de ça tst_node<charT,valueT> *match_node=storage->get(ni_best_match); int match_length = match_node->position+1; // On envoie le match to_perform->perform(string.substr(si_match_start,match_length),match_length,match_node->data); // On repositionne la zone de non-match juste après la fin du match si_non_match_start=si_match_start+match_length; // Annulation du match ni_best_match=UNDEFINED_INDEX; // On backtracke // backtrack de naze parce qu'on ne peut pas utiliser // les infos de backtrack à cause des séparateurs. si_current = si_non_match_start; ni_current = root; ni_best_match=UNDEFINED_INDEX; si_match_start=UNDEFINED_INDEX; } else if(si_match_start!=UNDEFINED_INDEX) { // Si le caractère courant n'est pas accepté, qu'on avait commencé // un match mais que celui-ci n'avait pas réussi, on va backtracker. // backtrack de naze parce qu'on ne peut pas utiliser // les infos de backtrack à cause des séparateurs. si_current=si_match_start+1; ni_current = root; ni_best_match=UNDEFINED_INDEX; si_match_start=UNDEFINED_INDEX; } else { // le caractère courant n'est pas accepté et on n'avait pas de match en cours if(si_current<string.size()) { // si on peut avancer d'un caractère on le fait ++si_current; // on revient à la racine ni_current = root; } else { // si on est à la fin de la chaîne on sort de la boucle pour la fin. break; } } } else { // on avance tranquillement dans l'arbre... } } // on n'arrive ici que si on est arrivé à la fin de la chaine en entrée if((si_current - si_non_match_start)>0) { // charT'il y avait un non-match en cours // on l'envoie to_perform->perform(string.substr(si_non_match_start,si_current - si_non_match_start),-static_cast<int>(si_current - si_non_match_start),default_value); } return to_perform->result(); } #endif /**************************** file I/O *************************************/ template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::read(std::istream& file) { // We check the version number int version_length; file.read((char*)(&version_length),sizeof(size_t)); char* version=(char*)tst_malloc(version_length+1); version[version_length]=0; assert(version); file.read(version,version_length); if(strcmp(TST_VERSION,version)!=0) { tst_free(version); throw TSTException("Invalid version number"); } else { tst_free(version); } serializerT reader; default_value = reader.read(file); // On efface le stockage storage->erase(); if(file.get()) { root = read_node(file,&reader,0); } else { node_info<charT,valueT> root_info; storage->new_node(&root_info); root = root_info.index; } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> int tst<charT,valueT,storageT,serializerT,stringT>::read_node(std::istream& file,serializerT* reader,int depth) { char bitmask = file.get(); node_info<charT,valueT> node_info; storage->new_node(&node_info); file.read((char*)(&(node_info.node->c)),sizeof(charT)); if(bitmask & 16) { node_info.node->store(reader->read(file)); } else { node_info.node->store(default_value); } #ifdef SCANNER // TODO : inutile, peut être recalculé ? file.read((char*)(&(node_info.node->position)),sizeof(int)); file.read((char*)(&(node_info.node->backtrack)),sizeof(int)); file.read((char*)(&(node_info.node->backtrack_match_index)),sizeof(int)); #endif int other_index; if(bitmask & 1) { // En deux étapes car le noeud peut bouger physiquement. // Normalement tout se passe bien mais c'est plus rassurant ainsi. other_index = read_node(file,reader,depth+1); storage->get(node_info.index)->next = other_index; } else { storage->get(node_info.index)->next = UNDEFINED_INDEX; } if(bitmask & 2) { other_index = read_node(file,reader,depth+1); storage->get(node_info.index)->left = other_index; } else { storage->get(node_info.index)->left = UNDEFINED_INDEX; } if(bitmask & 4) { other_index = read_node(file,reader,depth+1); storage->get(node_info.index)->right = other_index; } else { storage->get(node_info.index)->right = UNDEFINED_INDEX; } return node_info.index; } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::write(std::ostream& file) const { // We save the version number size_t version_length = strlen(TST_VERSION); file.write((char*)(&version_length),sizeof(size_t)); - file.write(TST_VERSION,version_length); + file.write(TST_VERSION,(std::streamsize)version_length); serializerT writer; writer.write(file,default_value); if(root!=UNDEFINED_INDEX) { file.put(1); write_node(file,&writer,root); } else { file.put(0); } } template<typename charT,typename valueT,typename storageT,typename serializerT, typename stringT> void tst<charT,valueT,storageT,serializerT,stringT>::write_node(std::ostream& file,serializerT* writer,int index) const { tst_node<charT,valueT>* node = storage->get(index); char bitmask=0; if(node->next!=UNDEFINED_INDEX) bitmask |= 1; if(node->left!=UNDEFINED_INDEX) bitmask |= 2; if(node->right!=UNDEFINED_INDEX) bitmask |= 4; if(node->data!=default_value) bitmask |=16; file.put(bitmask); file.write((char*)(&(node->c)),sizeof(charT)); if(bitmask & 16) { writer->write(file,node->data); } #ifdef SCANNER file.write((char*)(&(node->position)),sizeof(int)); file.write((char*)(&(node->backtrack)),sizeof(int)); file.write((char*)(&(node->backtrack_match_index)),sizeof(int)); #endif if(bitmask & 1) write_node(file,writer,node->next); if(bitmask & 2) write_node(file,writer,node->left); if(bitmask & 4) write_node(file,writer,node->right); } #endif diff --git a/python/build23.bat b/python/build23.bat index 1621818..b0a2b99 100644 --- a/python/build23.bat +++ b/python/build23.bat @@ -1,5 +1,5 @@ rmdir /s /q build include mkdir include & xcopy ..\include include swig -O -Iinclude -DSCANNER -c++ -python tst.i -e:\python23\python setup.py clean build --compile=mingw32 sdist bdist_wininst +c:\python23\python setup.py clean build --compile=mingw32 sdist bdist_wininst rmdir /s /q build include diff --git a/python/pythonTST.h b/python/pythonTST.h index 410d0d4..5d59902 100644 --- a/python/pythonTST.h +++ b/python/pythonTST.h @@ -1,324 +1,323 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define __PYTHON__BUILD__ #include "tst.h" #include "Python.h" #include "PythonReference.h" #include "qad_string.h" #include <iostream> #include <fstream> #ifdef ZIPPED_TREE #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/zlib.hpp> #endif typedef qad_string<char> string_type; - class CallableAction : public action<char,PythonReference,string_type > { public: CallableAction(PythonReference perform,PythonReference result) : _perform(perform), _result(result) { } virtual ~CallableAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { if(_perform.get()==Py_None) { return; } PythonReference tuple(Py_BuildValue("s#iO",string.data(),string.size(),remaining_distance,data.get()),0); Py_DECREF(PyObject_CallObject(_perform.get(),tuple.get())); } virtual PythonReference result() { if(_result.get()==Py_None) { return PythonReference(); } else { return PythonReference(PyObject_CallObject(_result.get(),0),0); } } private: PythonReference _perform,_result; }; class CallableFilter : public filter<char,PythonReference,string_type > { public: CallableFilter(PythonReference _callable) : callable(_callable) { } virtual ~CallableFilter() { } virtual PythonReference perform(const string_type& string,int remaining_distance,PythonReference data) { PythonReference tuple(Py_BuildValue("s#iO",string.data(),string.size(),remaining_distance,data.get()),0); return PythonReference(PyObject_CallObject(callable.get(),tuple.get()),0); } private: PythonReference callable; }; class DictAction : public action<char,PythonReference,string_type > { public: DictAction() : dict(PyDict_New(),0) { } virtual ~DictAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { PythonReference key(Py_BuildValue("s#",string.data(),string.size()),0); PyObject* old_tuple=PyDict_GetItem(dict.get(),key.get()); if(old_tuple!=0) { long value=PyInt_AsLong(PyTuple_GetItem(old_tuple,0)); if(value<remaining_distance) { return; } } PythonReference tuple(Py_BuildValue("iO",remaining_distance,data.get()),0); PyDict_SetItem(dict.get(),key.get(),tuple.get()); }; virtual PythonReference result() { return dict; } private: PythonReference dict; }; class ListAction : public action<char,PythonReference,string_type > { public: ListAction() : list(PyList_New(0),0) { } virtual ~ListAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { PyList_Append(list.get(),data.get()); } virtual PythonReference result() { return list; } private: PythonReference list; }; class TupleListAction : public action<char,PythonReference,string_type > { public: TupleListAction() : list(PyList_New(0),0){ } virtual ~TupleListAction() { } virtual void perform(const string_type& string,int remaining_distance,PythonReference data) { PythonReference tuple(Py_BuildValue("s#iO",string.data(),string.size(),remaining_distance,data.get()),0); PyList_Append(list.get(),tuple.get()); } virtual PythonReference result() { return list; } private: PythonReference list; }; class ObjectSerializer { public: ObjectSerializer(); void write(std::ostream& file,PythonReference data); PythonReference ObjectSerializer::read(std::istream& file); private: PythonReference dumps,loads; }; ObjectSerializer::ObjectSerializer() { PythonReference name(PyString_FromString("cPickle"),0); PythonReference cPickle(PyImport_Import(name.get()),0); dumps = PythonReference(PyObject_GetAttrString(cPickle.get(),"dumps"),0); loads = PythonReference(PyObject_GetAttrString(cPickle.get(),"loads"),0); } void ObjectSerializer::write(std::ostream& file,PythonReference data) { PythonReference call(Py_BuildValue("Oi",data.get(),2),0); PythonReference result(PyObject_CallObject(dumps.get(),call.get()),0); char *string; int length; PyString_AsStringAndSize(result.get(),&string,&length); file.write((char*)(&length),sizeof(int)); file.write(string,length); } PythonReference ObjectSerializer::read(std::istream& file) { int length; file.read((char*)(&length),sizeof(int)); char* string=(char*)tst_malloc(length); file.read(string,length); PythonReference dumped(PyString_FromStringAndSize(string,length),0); PythonReference call(Py_BuildValue("(O)",dumped.get()),0); PythonReference result(PyObject_CallObject(loads.get(),call.get()),0); tst_free(string); return result; } class TST; template <typename iterator_type> class TSTIterator { public: friend class TST; TSTIterator __iter__() { return *this; } PyObject* next() { typename iterator_type::value_type v(iterator.next()); if(v.second) { return Py_BuildValue("s#O",v.first.data(),v.first.size(),v.second->get()); } else { PythonReference exceptions(PyImport_ImportModule("exceptions"),0); PythonReference stop_iteration = exceptions.getattr("StopIteration"); PyErr_SetNone(stop_iteration.get()); return 0; } } private: TSTIterator(iterator_type i) : iterator(i) { } iterator_type iterator; }; typedef TSTIterator<lexical_iterator<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > > TSTLexicalIterator; typedef TSTIterator<match_iterator<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > > TSTCloseMatchIterator; class TST : private tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type > { public: TST() : tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >() { } virtual ~TST() { } virtual PythonReference write_to_file(PythonReference file) { if(!PyString_CheckExact(file.get())) { throw TSTException("Argument of write_to_file() must be a string object"); } std::ofstream out(PyString_AsString(file.get()),std::ofstream::binary|std::ofstream::out|std::ofstream::trunc); out.exceptions(std::ofstream::eofbit | std::ofstream::failbit | std::ofstream::badbit); #ifdef ZIPPED_TREE boost::iostreams::filtering_ostream fout; fout.push(boost::iostreams::zlib_compressor()); fout.push(out); this->write(fout); fout.strict_sync(); #else this->write(out); #endif out.close(); return PythonReference(); } virtual PythonReference read_from_file(PythonReference file) { if(!PyString_CheckExact(file.get())) { throw TSTException("Argument of read_from_file() must be a string object"); } std::ifstream in(PyString_AsString(file.get()),std::ifstream::binary|std::ifstream::in); in.exceptions(std::ifstream::eofbit | std::ifstream::failbit | std::ifstream::badbit); #ifdef ZIPPED_TREE boost::iostreams::filtering_istream fin; fin.push(boost::iostreams::zlib_decompressor()); fin.push(in); this->read(fin); #else this->read(in); #endif in.close(); return PythonReference(); } PythonReference __getitem__(const string_type& string) { return get(string); } PythonReference __setitem__(const string_type& string,PythonReference data) { return put(string,data); } void __delitem__(const string_type& string) { remove(string); } PythonReference __contains__(const string_type& string) { if(contains(string)) { return PythonReference(Py_False); } else { return PythonReference(Py_True); } } TSTLexicalIterator __iter__() { return TSTLexicalIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::iterator()); } TSTLexicalIterator iterator() { return TSTLexicalIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::iterator()); } TSTLexicalIterator iterator(const string_type& string) { return TSTLexicalIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::iterator(string)); } TSTCloseMatchIterator close_match_iterator(const string_type& string, int distance) { return TSTCloseMatchIterator(tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::close_match_iterator(string,distance)); } using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::put; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::get; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::pack; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::walk; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::close_match; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::match; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::scan; using tst<char,PythonReference,memory_storage<char,PythonReference>,ObjectSerializer,string_type >::scan_with_stop_chars; }; diff --git a/python/with_boost/Jamrules b/python/with_boost/Jamrules index 3d40ca3..ae368d6 100644 --- a/python/with_boost/Jamrules +++ b/python/with_boost/Jamrules @@ -1,36 +1,36 @@ # Copyright David Abrahams 2003. See accompanying LICENSE for terms # and conditions of use. # If you move this example from its place in the Boost tree, edit this # path to point at the root directory of your Boost installation (the # one containing a subdirectory called "boost/" and a sub-subdirectory # "boost/python/" full of .hpp files). Absolute paths work, too. # -path-global BOOST_ROOT : c:/projets/boost_1_33_1 ; +path-global BOOST_ROOT : d:/projets/boost_1_33_1 ; # Boost.Python configuration variables, as described in # http://www.boost.org/libs/python/doc/building.html#configuration. # Usually you don't need to set these; the defaults will work. If you # do set them, try to change as few of them as possible, starting with # the first ones. # PYTHON_VERSION = <the two-part Major.Minor version number, e.g. 2.2> ; # PYTHON_ROOT = <root directory of your Python installation, e.g. /usr> ; # PYTHON_INCLUDES = <path to Python #include directories> ; # PYTHON_LIB_PATH = <path to Python library object> ; # You may need to configure your compiler toolset, especially if you # want to build with a compiler that is not the "system default" or if # it is installed in a nonstandard place; see # http://www.boost.org/more/getting_started.html#Configuring for # details. # Makes a project id for boost so that other Boost.Build projects can # refer to it by name. # project boost : $(BOOST_ROOT) ; # Change this setting to have all your built products placed under a # single directory: # # ALL_LOCATE_TARGET = <root directory for all built products> diff --git a/python/with_boost/boost-build.jam b/python/with_boost/boost-build.jam index 6f5beaa..559216c 100644 --- a/python/with_boost/boost-build.jam +++ b/python/with_boost/boost-build.jam @@ -1,6 +1,6 @@ # Copyright David Abrahams 2003. See accompanying LICENSE for terms # and conditions of use. # Edit this path to point at the tools/build/v1 subdirectory of your # Boost installation. Absolute paths work, too. -boost-build c:/projets/boost_1_33_1/tools/build/v1 ; +boost-build d:/projets/boost_1_33_1/tools/build/v1 ; diff --git a/python/with_boost/build.bat b/python/with_boost/build.bat index 5262269..0ac640c 100644 --- a/python/with_boost/build.bat +++ b/python/with_boost/build.bat @@ -1,4 +1,4 @@ -bjam -sPYTHON_VERSION=2.4 -sZLIB_SOURCE=c:\projets\httpd-2.2.0\srclib\zlib -sPYTHON_ROOT=e:\python24 -sBUILD=release %* +bjam -sPYTHON_VERSION=2.4 -sZLIB_SOURCE=d:\projets\zlib-1.2.3 -sPYTHON_ROOT=c:\python24 -sBUILD=release %* copy bin\boost\libs\python\build\boost_python.dll\vc-7_1\release\threading-multi\boost_python.dll . copy bin\with_boost\tst.pyd\vc-7_1\release\threading-multi\tst.pyd . python zipit.py diff --git a/python/with_boost/tst.pyd b/python/with_boost/tst.pyd index aaaa63e..1fd1181 100644 Binary files a/python/with_boost/tst.pyd and b/python/with_boost/tst.pyd differ diff --git a/textindex/Jamrules b/textindex/Jamrules index 3d40ca3..ae368d6 100644 --- a/textindex/Jamrules +++ b/textindex/Jamrules @@ -1,36 +1,36 @@ # Copyright David Abrahams 2003. See accompanying LICENSE for terms # and conditions of use. # If you move this example from its place in the Boost tree, edit this # path to point at the root directory of your Boost installation (the # one containing a subdirectory called "boost/" and a sub-subdirectory # "boost/python/" full of .hpp files). Absolute paths work, too. # -path-global BOOST_ROOT : c:/projets/boost_1_33_1 ; +path-global BOOST_ROOT : d:/projets/boost_1_33_1 ; # Boost.Python configuration variables, as described in # http://www.boost.org/libs/python/doc/building.html#configuration. # Usually you don't need to set these; the defaults will work. If you # do set them, try to change as few of them as possible, starting with # the first ones. # PYTHON_VERSION = <the two-part Major.Minor version number, e.g. 2.2> ; # PYTHON_ROOT = <root directory of your Python installation, e.g. /usr> ; # PYTHON_INCLUDES = <path to Python #include directories> ; # PYTHON_LIB_PATH = <path to Python library object> ; # You may need to configure your compiler toolset, especially if you # want to build with a compiler that is not the "system default" or if # it is installed in a nonstandard place; see # http://www.boost.org/more/getting_started.html#Configuring for # details. # Makes a project id for boost so that other Boost.Build projects can # refer to it by name. # project boost : $(BOOST_ROOT) ; # Change this setting to have all your built products placed under a # single directory: # # ALL_LOCATE_TARGET = <root directory for all built products> diff --git a/textindex/_xapian.dll b/textindex/_xapian.dll new file mode 100644 index 0000000..9f29863 Binary files /dev/null and b/textindex/_xapian.dll differ diff --git a/textindex/boost-build.jam b/textindex/boost-build.jam index 6f5beaa..559216c 100644 --- a/textindex/boost-build.jam +++ b/textindex/boost-build.jam @@ -1,6 +1,6 @@ # Copyright David Abrahams 2003. See accompanying LICENSE for terms # and conditions of use. # Edit this path to point at the tools/build/v1 subdirectory of your # Boost installation. Absolute paths work, too. -boost-build c:/projets/boost_1_33_1/tools/build/v1 ; +boost-build d:/projets/boost_1_33_1/tools/build/v1 ; diff --git a/textindex/boost_python.dll b/textindex/boost_python.dll index ec733ca..f09547d 100644 Binary files a/textindex/boost_python.dll and b/textindex/boost_python.dll differ diff --git a/textindex/build.bat b/textindex/build.bat index 307931f..04bc35b 100644 --- a/textindex/build.bat +++ b/textindex/build.bat @@ -1,3 +1,3 @@ -bjam -sPYTHON_VERSION=2.4 -sPYTHON_ROOT=e:\python24 -sBUILD=release %1 %2 %3 %4 %5 %6 %7 %8 %9 +bjam -sPYTHON_VERSION=2.4 -sPYTHON_ROOT=c:\python24 -sBUILD=release %1 %2 %3 %4 %5 %6 %7 %8 %9 copy bin\boost\libs\python\build\boost_python.dll\vc-7_1\release\threading-multi\boost_python.dll . copy bin\textindex\textindex.pyd\vc-7_1\release\threading-multi\textindex.pyd . diff --git a/textindex/mp3tag.py b/textindex/mp3tag.py new file mode 100644 index 0000000..f8a9017 --- /dev/null +++ b/textindex/mp3tag.py @@ -0,0 +1,107 @@ +if __name__ == "__main__": + import sys + from time import time + import linecache + import glob + from textindex import textindex + import traceback + import linecache + from mutagen.mp3 import MP3 + import os + + ti = textindex() + + try: + start = time() + ti.read('mp3.ti') + print 'Loading time : %.2fs'%(time()-start) + except: + traceback.print_exc() + + start = time() + lines = 0 + + for root, dirnames, filenames in os.walk(sys.argv[1]): + for filename in filenames: + if filename[-4:].lower() == '.mp3': + try: + full_filename = os.path.join(root,filename) + mp3 = MP3(full_filename) + title = mp3.get('TIT2') + artist = mp3.get('TPE2') + album = mp3.get('TALB') + if title: + title = title.text[0].decode('iso-8859-1').lower() + ti.put_text(title,full_filename) + else: + ti.put_text(filename[:-4].lower(),mp3) + if artist: + artist = artist.text[0].decode('iso-8859-1').lower() + ti.put_text(artist,full_filename) + if album: + album = album.text[0].decode('iso-8859-1').lower() + ti.put_text(album,full_filename) + print title, album, artist + except: + pass + + ti.pack() + print 'Indexing time : %.2fs for %i lines'%(time()-start,lines) + + ti.write('mp3.ti') + + def lines(text,intersection=True): + for ln, r in ti.find_text(text.lower(),intersection): + print '%02i:%s'%( + r, + ln + ), + + def ilines(text,intersection=True): + for ln, r in ti.find_text(text.lower(),intersection): + print '%02i:%s'%( + r, + ln, + ), + + if len(sys.argv)>1 and sys.argv[-1]=='gui': + from Tkinter import * + class Explorer(object): + def __init__(self,master): + self.frame = Frame(master) + self.frame.pack(fill=BOTH, expand=1) + + self.entry = Entry(self.frame, name='input') + self.entry.pack(fill=X) + self.entry.bind('<KeyRelease>',self.keyPressed) + + frame = Frame(self.frame) + frame.pack(fill=BOTH, expand=1) + scrollbar = Scrollbar(frame, orient=VERTICAL) + self.list = Listbox(frame, name='list', yscrollcommand=scrollbar.set) + scrollbar.config(command=self.list.yview) + scrollbar.pack(side=RIGHT, fill=Y) + self.list.pack(side=LEFT, fill=BOTH, expand=1) + + self.label = Label(self.frame, name='count') + self.label.pack() + + def keyPressed(self,event): + self.list.delete(0,END) + start = time() + result = ti.find_text(self.entry.get().lower(),True) + # result.sort(key=lambda i : -i[1]) + elapsed = time() - start + for ln, r in result[:100]: + self.list.insert(END,'%02i:%s'%( + r, + ln + )) + self.label.config(text = '%i lines in %.2fs'%( + len(result), + elapsed + )) + + root = Tk() + explorer = Explorer(root) + root.mainloop() diff --git a/textindex/test.py b/textindex/test.py index f2f5a46..4560a95 100644 --- a/textindex/test.py +++ b/textindex/test.py @@ -1,94 +1,94 @@ if __name__ == "__main__": import sys from time import time import linecache import glob from textindex import textindex import traceback import linecache ti = textindex() try: start = time() ti.read('text.ti') print 'Loading time : %.2fs'%(time()-start) except: traceback.print_exc() start = time() lines = 0 for f in glob.glob('*.txt'): print f, for linenumber, line in enumerate(file(f,'rb')): lines += 1 line = line.strip() ti.put_text(line.lower().decode('iso-8859-1'),'%12s:%04i'%(f,linenumber)) if linenumber % 100 == 0: sys.stdout.write('.') print 'OK' ti.pack() print 'Indexing time : %.2fs for %i lines'%(time()-start,lines) ti.write('text.ti') def lines(text,intersection=True): for ln, r in ti.find_text(text.lower(),intersection): print '%02i:%s'%( r, ln ), def ilines(text,intersection=True): for ln, r in ti.find_text(text.lower(),intersection): print '%02i:%s'%( r, ln, ), if len(sys.argv)>1 and sys.argv[1]=='gui': from Tkinter import * class Explorer(object): def __init__(self,master): self.frame = Frame(master) self.frame.pack(fill=BOTH, expand=1) self.entry = Entry(self.frame, name='input') self.entry.pack(fill=X) - self.entry.bind('<Key>',self.keyPressed) + self.entry.bind('<KeyRelease>',self.keyPressed) frame = Frame(self.frame) frame.pack(fill=BOTH, expand=1) scrollbar = Scrollbar(frame, orient=VERTICAL) self.list = Listbox(frame, name='list', yscrollcommand=scrollbar.set) scrollbar.config(command=self.list.yview) scrollbar.pack(side=RIGHT, fill=Y) self.list.pack(side=LEFT, fill=BOTH, expand=1) self.label = Label(self.frame, name='count') self.label.pack() def keyPressed(self,event): self.list.delete(0,END) start = time() result = ti.find_text(self.entry.get().lower(),True) # result.sort(key=lambda i : -i[1]) elapsed = time() - start for ln, r in result[:100]: i = ln.rindex(':') d = ln[:i].strip() l = int(ln[i+1:]) self.list.insert(END,'%02i:%s:%i:%s'%( r, d, l, linecache.getline(d,l+1).strip() )) self.label.config(text = '%i lines in %.2fs'%( len(result), elapsed )) root = Tk() explorer = Explorer(root) root.mainloop() diff --git a/textindex/testxapian.py b/textindex/testxapian.py new file mode 100644 index 0000000..07662fc --- /dev/null +++ b/textindex/testxapian.py @@ -0,0 +1,87 @@ +if __name__ == "__main__": + import sys + from time import time + import linecache + import glob + import traceback + import linecache + import xapian + import re + + stem = xapian.Stem("french") + ti = xapian.inmemory_open() + ti = xapian.WritableDatabase("test.ti", xapian.DB_CREATE_OR_OPEN) + # ti = xapian.quartz_open('test.idx') + +# start = time() +# lines = 0 +# for f in glob.glob('*.txt'): +# print f, +# for linenumber, line in enumerate(file(f,'rb')): +# lines += 1 +# line = line.strip() +# doc = xapian.Document() +# doc.set_data('%12s:%04i'%(f,linenumber)) +# for word_number, word in enumerate(re.findall(r'\w+',line.lower())): +# doc.add_posting(word,word_number) +# ti.add_document(doc) +# if linenumber % 100 == 0: +# sys.stdout.write('.') +# print 'OK' +# print 'Indexing time : %.2fs for %i lines'%(time()-start,lines) + + if len(sys.argv)>1 and sys.argv[1]=='gui': + from Tkinter import * + class Explorer(object): + def __init__(self,master): + self.frame = Frame(master) + self.frame.pack(fill=BOTH, expand=1) + + self.entry = Entry(self.frame, name='input') + self.entry.pack(fill=X) + self.entry.bind('<Key>',self.keyPressed) + + frame = Frame(self.frame) + frame.pack(fill=BOTH, expand=1) + scrollbar = Scrollbar(frame, orient=VERTICAL) + self.list = Listbox(frame, name='list', yscrollcommand=scrollbar.set) + scrollbar.config(command=self.list.yview) + scrollbar.pack(side=RIGHT, fill=Y) + self.list.pack(side=LEFT, fill=BOTH, expand=1) + + self.label = Label(self.frame, name='count') + self.label.pack() + + def keyPressed(self,event): + self.list.delete(0,END) + start = time() + if self.entry.get(): + query_parser = xapian.QueryParser() + enq = xapian.Enquire(ti) + query = query_parser.parse_query(self.entry.get(),query_parser.FLAG_WILDCARD) + print query.get_description() + enq.set_query(query) + elapsed = time() - start + result = enq.get_mset(0,100) + count = 0 + for doc in result: + count += 1 + ln = doc[4].get_data() + r = doc[1] + i = ln.rindex(':') + d = ln[:i].strip() + l = int(ln[i+1:]) + self.list.insert(END,'%.2f:%s:%i:%s'%( + r, + d, + l, + linecache.getline(d,l+1).strip() + )) + self.label.config(text = '%i lines in %.2fs'%( + count, + elapsed + )) + + root = Tk() + explorer = Explorer(root) + root.mainloop() diff --git a/textindex/textindex.cpp b/textindex/textindex.cpp index 7c4bfea..8cbc801 100644 --- a/textindex/textindex.cpp +++ b/textindex/textindex.cpp @@ -1,145 +1,157 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <string> #include <iostream> #include <fstream> -#include <boost/iostreams/filtering_stream.hpp> -#include <boost/iostreams/filter/zlib.hpp> #include <boost/python.hpp> using namespace boost::python; +#define COMPRESS_INDEX_FILE +#ifdef COMPRESS_INDEX_FILE +#include <boost/iostreams/filtering_stream.hpp> +#include <boost/iostreams/filter/zlib.hpp> +#endif + #define __PYTHON__BUILD__ #include "textindex.h" + class object_serializer { public: object_serializer(); void write(std::ostream& file,object data); object object_serializer::read(std::istream& file); private: object dumps,loads; }; object_serializer::object_serializer() { object cPickle(handle<>(PyImport_ImportModule("cPickle"))); dumps = cPickle.attr("dumps"); loads = cPickle.attr("loads"); } void object_serializer::write(std::ostream& file,object data) { str result = (str)dumps(data,2); char *string; int length; PyString_AsStringAndSize(result.ptr(),&string,&length); file.write((char*)(&length),sizeof(int)); file.write(string,length); } object object_serializer::read(std::istream& file) { int length; file.read((char*)(&length),sizeof(int)); char* string=(char*)tst_malloc(length); file.read(string,length); str dumped(string,length); object result = loads(dumped); tst_free(string); return result; } template <typename character_type> class python_textindex : public textindex<character_type,object,object_serializer> { public: list find_word(std::basic_string<character_type> word) { return to_list(textindex<character_type,object,object_serializer>::find_word(word)); } list find_text(std::basic_string<character_type> word,bool intersection) { return to_list(textindex<character_type,object,object_serializer>::find_text(word,intersection)); } list __getitem__1(std::basic_string<character_type> word) { return to_list(textindex<character_type,object,object_serializer>::find_text(word,true)); } list __getitem__2(tuple item) { return to_list(textindex<character_type,object,object_serializer>::find_text(extract<std::basic_string<character_type> >(item[0]),item[1])); } void write_to_file(str file) { std::ofstream out(PyString_AsString(file.ptr()),std::ofstream::binary|std::ofstream::out|std::ofstream::trunc); - boost::iostreams::filtering_ostream fout; - fout.push(boost::iostreams::zlib_compressor()); - fout.push(out); - write(fout); - fout.strict_sync(); - // out.close(); + out.exceptions(std::ofstream::eofbit | std::ofstream::failbit | std::ofstream::badbit); + #ifdef COMPRESS_INDEX_FILE + boost::iostreams::filtering_ostream fout; + fout.push(boost::iostreams::zlib_compressor()); + fout.push(out); + write(fout); + fout.strict_sync(); + #else + write(out); + #endif } void read_from_file(object file) { std::ifstream in(PyString_AsString(file.ptr()),std::ifstream::binary|std::ifstream::in); in.exceptions(std::ifstream::eofbit | std::ifstream::failbit | std::ifstream::badbit); - boost::iostreams::filtering_istream fin; - fin.push(boost::iostreams::zlib_decompressor()); - fin.push(in); - read(fin); - // in.close(); + #ifdef COMPRESS_INDEX_FILE + boost::iostreams::filtering_istream fin; + fin.push(boost::iostreams::zlib_decompressor()); + fin.push(in); + read(fin); + #else + read(in); + #endif } protected: list to_list(result_pointer entries) { list result; for(result_pointer::element_type::iterator item(entries->begin()),end(entries->end());item!=end;++item) { result.append(make_tuple(item->first,item->second)); } return result; } }; BOOST_PYTHON_MODULE(textindex) { scope().attr("TST_VERSION") = std::string(TST_VERSION)+"-Boost.Python"; class_< python_textindex<wchar_t> >("textindex") .def("put_word",&python_textindex<wchar_t>::put_word) .def("put_text",&python_textindex<wchar_t>::put_text) .def("remove_document",&python_textindex<wchar_t>::remove_document) .def("__setitem__",&python_textindex<wchar_t>::put_text) .def("find_word",&python_textindex<wchar_t>::find_word) .def("find_text",&python_textindex<wchar_t>::find_text) .def("__getitem__",&python_textindex<wchar_t>::__getitem__1) .def("__getitem__",&python_textindex<wchar_t>::__getitem__2) .def("pack",&python_textindex<wchar_t>::pack) .def("write",&python_textindex<wchar_t>::write_to_file) .def("read",&python_textindex<wchar_t>::read_from_file) ; /*class_< documents_scores<std::basic_string<wchar_t> > >("documents_scores") .def("add_document",&documents_scores<std::basic_string<wchar_t> >::add_document) .def("merge_with",&documents_scores<std::basic_string<wchar_t> >::merge_with) .def("intersect_with",&documents_scores<std::basic_string<wchar_t> >::intersect_with) .def("size",&documents_scores<std::basic_string<wchar_t> >::size) .def("get_document",&documents_scores<std::basic_string<wchar_t> >::get_document) .def("get_score",&documents_scores<std::basic_string<wchar_t> >::get_score) ;*/ } diff --git a/textindex/textindex.h b/textindex/textindex.h index b7985d4..05478ff 100644 --- a/textindex/textindex.h +++ b/textindex/textindex.h @@ -1,463 +1,470 @@ /* # $Id$ # Copyright (C) 2004-2005 Nicolas Lehuen <nicolas@lehuen.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __TEXTINDEX__H_INCLUDED__ #define __TEXTINDEX__H_INCLUDED__ #include "tst.h" #include <hash_map> #include <boost/shared_ptr.hpp> #include <boost/regex.hpp> #include <iostream> -template <class pair> inline bool sort_by_document(const pair& lhs, const pair& rhs) +template <class pair> +inline bool sort_by_document(const pair& lhs, const pair& rhs) { return lhs.first < rhs.first; } -template <class pair> inline bool sort_by_score(const pair& lhs, const pair& rhs) +template <class pair> +inline bool sort_by_score(const pair& lhs, const pair& rhs) { return lhs.second > rhs.second; } -template <class item> inline bool sort_by_first_item_length_desc(const item& lhs, const item& rhs) { +template <class item> +inline bool sort_by_first_item_length_desc(const item& lhs, const item& rhs) { return lhs.begin()->length() > rhs.begin()->length(); } -template <typename document_id_type, typename score_type> class documents_scores { +template <typename document_id_type, typename score_type> +class documents_scores { public: typedef std::pair<document_id_type,score_type> pair_type; typedef std::map<document_id_type,score_type> storage_type; typedef typename storage_type::const_iterator const_iterator; typedef boost::shared_ptr< typename documents_scores > shared_ptr; documents_scores(typename storage_type::size_type size = 0) : documents() { } int add_document(const document_id_type &document, const score_type score) { return (documents[document] += score); } typename storage_type::size_type remove_document(const document_id_type &document) { return documents.erase(document); } void merge_with(const documents_scores &other,const documents_scores* intersect=0) { storage_type::iterator lhs(documents.begin()); storage_type::const_iterator rhs(other.documents.begin()); while(lhs!=documents.end() && rhs!=other.documents.end()) { if(lhs->first < rhs->first) { ++lhs; } else if(lhs->first == rhs->first) { lhs->second += rhs->second; ++lhs; ++rhs; } else { if(intersect==0 || intersect->documents.find(rhs->first)!=intersect->documents.end()) { documents.insert(*rhs); } ++rhs; } } while(rhs!=other.documents.end()) { if(intersect==0 || intersect->documents.find(rhs->first)!=intersect->documents.end()) { documents.insert(*rhs); } ++rhs; } } void intersect_with(const documents_scores &other) { storage_type::iterator lhs(documents.begin()); storage_type::const_iterator rhs(other.documents.begin()); while(lhs!=documents.end() && rhs!=other.documents.end()) { if(lhs->first < rhs->first) { lhs = documents.erase(lhs); } else if(lhs->first == rhs->first) { lhs->second += rhs->second; ++lhs; ++rhs; } else { ++rhs; } } documents.erase(lhs,documents.end()); } const typename storage_type::size_type size() const { return documents.size(); } const const_iterator begin() const { return documents.begin(); } const const_iterator end() const { return documents.end(); } class serializer { public: void write(std::ostream& file, shared_ptr value) { documents_scores* ds = value.get(); if(ds!=0) { size_t size = ds->size(); file.write((char*)(&size),sizeof(size_t)); for(storage_type::iterator iterator(ds->documents.begin()),end(ds->documents.end());iterator!=end;++iterator) { file.write((char*)(&(iterator->first)),sizeof(document_id_type)); file.write((char*)(&(iterator->second)),sizeof(score_type)); } } else { size_t size=0; file.write((char*)(&size),sizeof(size_t)); } } shared_ptr read(std::istream& file) { size_t size; file.read((char*)(&size),sizeof(size_t)); if(size>0) { documents_scores* result = new documents_scores(size); for(size_t i=0;i<size;++i) { document_id_type document_id; file.read((char*)(&document_id),sizeof(document_id_type)); score_type score; file.read((char*)(&score),sizeof(score_type)); result->documents[document_id]=score; } return shared_ptr(result); } else { return shared_ptr(); } } }; private: storage_type documents; }; -template < typename character_type, typename document_type, typename reader_writer, typename document_id_type = unsigned int, typename score_type = unsigned int > class textindex { +template < typename character_type, typename document_type, typename reader_writer, typename document_id_type = unsigned int, typename score_type = unsigned int> +class textindex { public: + // Chaînes de caractères + typedef std::basic_string<typename character_type> string_type; // Mapping document <=> id typedef std::map< typename document_type, document_id_type > documents_ids_type; typedef std::map< document_id_type, typename document_type > reversed_documents_ids_type; // Types nécessaire à la construction du TST typedef documents_scores< typename document_id_type, typename score_type > documents_scores_type; typedef typename documents_scores_type::shared_ptr documents_scores_pointer; typedef typename documents_scores_type::serializer documents_scores_serializer; - typedef string_tst < character_type, typename documents_scores_pointer, memory_storage<character_type, typename documents_scores_pointer>, documents_scores_serializer > tree_type; + typedef tst < character_type, typename documents_scores_pointer, memory_storage<character_type, typename documents_scores_pointer>, documents_scores_serializer, typename string_type > tree_type; // Résultat des requêtes typedef std::pair< document_type, score_type > pair_type; typedef std::vector< pair_type > result_type; typedef boost::shared_ptr< result_type > result_pointer; // Regexes typedef boost::basic_regex < character_type > regex_type; - typedef boost::regex_iterator<typename std::basic_string<character_type>::const_iterator> regex_type_iterator; + typedef boost::regex_iterator<typename string_type::const_iterator> regex_type_iterator; - class collector : public action< typename character_type, typename documents_scores_pointer > { + class collector : public action< typename character_type, typename documents_scores_pointer, typename string_type> { public: collector(collector* _intersect=0) : intersect(_intersect), entries(new documents_scores_type(0)) { } - virtual void perform(const character_type* string, size_t string_length, int remaining_distance, typename documents_scores_pointer data) { + virtual void perform(const typename string_type& string, int remaining_distance, typename documents_scores_pointer data) { entries->merge_with(*data,intersect ? intersect->entries.get() : 0); } virtual typename documents_scores_pointer result() { return entries; } void set_intersect(bool _intersect) { intersect = _intersect; } void merge_with(collector& c) { entries->merge_with(*(c.entries),intersect ? intersect->entries.get() : 0); } void intersect_with(collector& c) { entries->intersect_with(*(c.entries)); } private: collector* intersect; documents_scores_pointer entries; }; - class eraser : public action< typename character_type, typename documents_scores_pointer > { + class eraser : public action< typename character_type, typename documents_scores_pointer, typename string_type > { public: eraser(document_id_type _document_id) : document_id(_document_id) { } - virtual void perform(const character_type* string, size_t string_length, int remaining_distance, typename documents_scores_pointer data) { + virtual void perform(const typename string_type& string, int remaining_distance, typename documents_scores_pointer data) { data->remove_document(document_id); } virtual typename documents_scores_pointer result() { return documents_scores_pointer(); } private: document_id_type document_id; }; - class cleaner : public action< typename character_type, typename documents_scores_pointer > { + class cleaner : public action< typename character_type, typename documents_scores_pointer, typename string_type > { public: - typedef boost::shared_ptr< std::vector< std::basic_string< typename character_type > > > result_type; + typedef boost::shared_ptr< std::vector< typename string_type > > result_type; - cleaner(typename tree_type* _tree) : tree(_tree), empty_words(new std::vector< std::basic_string< character_type > >() ) { + cleaner(typename tree_type* _tree) : tree(_tree), empty_words(new std::vector< typename string_type >() ) { } - virtual void perform(const character_type* string, size_t string_length, int remaining_distance, typename documents_scores_pointer data) { + virtual void perform(const typename string_type& string, int remaining_distance, typename documents_scores_pointer data) { if(data->size()==0) { - empty_words->push_back(std::basic_string< typename character_type >(string,string_length)); + empty_words->push_back(string); } } virtual typename documents_scores_pointer result() { for(cleaner::result_type::element_type::const_iterator item(empty_words->begin()),end(empty_words->end());item!=end;++item) { tree->remove(*item); } return documents_scores_pointer(); } private: typename tree_type* tree; typename result_type empty_words; }; - class documents_scores_type_factory : public filter< character_type, documents_scores_pointer > { + class documents_scores_type_factory : public filter< character_type, documents_scores_pointer, typename string_type > { public: - virtual documents_scores_pointer perform(const character_type* string, size_t string_length, int remaining_distance, typename documents_scores_pointer data) { + virtual documents_scores_pointer perform(const typename string_type& string, int remaining_distance, typename documents_scores_pointer data) { return typename documents_scores_pointer(new documents_scores_type(0)); } }; textindex() : tree(), tokenizer(L"[\\w\\?\\*\\-]+"), factory(), next_document_id(0) { } - int put_word(const std::basic_string< character_type >& word,const document_type& document) { + int put_word(const typename string_type& word,const document_type& document) { if(word.size()>2) { documents_scores_pointer scores(tree.get_or_build(word,&factory)); return scores->add_document(get_document_id(document),1); } else { return 0; } } - int put_text(const std::basic_string< character_type >& text,const document_type& document) { + int put_text(const typename string_type& text,const document_type& document) { typename regex_type_iterator token(text.begin(),text.end(),tokenizer); typename regex_type_iterator end; int count = 0; document_id_type document_id(get_document_id(document)); while(token != end) { documents_scores_pointer scores(tree.get_or_build(token->begin()->str(),&factory)); count += scores->add_document(document_id,1); ++token; } return count; } void remove_document(const document_type& document) { documents_ids_type::iterator document_position(ids.find(document)); if(document_position != ids.end()) { document_id_type document_id(document_position->second); ids.erase(document_position); reversed_ids.erase(document_id); eraser e(document_id); - tree.walk1(0,&e); + tree.walk(0,&e); } } - result_pointer find_word(const std::basic_string< character_type >& word) { + result_pointer find_word(const typename string_type& word) { collector c; tree.match(word,0,&c); return convert_to_result(c); } - result_pointer find_text(const std::basic_string< character_type >& text,bool intersection) { + result_pointer find_text(const typename string_type& text,bool intersection) { typename regex_type_iterator token(text.begin(),text.end(),tokenizer); typename regex_type_iterator end; if(token!=end) { if(intersection) { // On va trier les tokens par ordre décroissant de longueur afin // de mettre le plus limitant en premier std::vector< regex_type_iterator::value_type > tokens(token,end); std::sort(tokens.begin(),tokens.end(),sort_by_first_item_length_desc<regex_type_iterator::value_type>); std::vector< regex_type_iterator::value_type >::const_iterator tokens_iterator(tokens.begin()); collector c; // Le mot le plus long doit faire au moins 3 caractères. if(tokens_iterator->begin()->length()>2) { tree.match(tokens_iterator->begin()->str(),0,&c); ++tokens_iterator; while(tokens_iterator != tokens.end()) { // on se fiche de la longueur des autres mots collector c2(&c); tree.match(tokens_iterator->begin()->str(),0,&c2); c.intersect_with(c2); ++tokens_iterator; } } return convert_to_result(c); } else { collector c; while(token != end) { if(token->begin()->length()>2) { - std::basic_string<character_type> word = token->begin()->str(); + typename string_type word = token->begin()->str(); tree.match(word,0,&c); } ++token; } return convert_to_result(c); } } else { return result_pointer(new result_type()); } } void pack() { cleaner c(&tree); - tree.walk1(NULL,&c); + tree.walk(NULL,&c); tree.pack(); } void write(std::ostream& file) const { // On écrit l'arbre tree.write(file); // On écrit le prochain id de document file.write((char*)(&next_document_id),sizeof(document_id_type)); // On écrit la taille du lexique documents_ids_type::size_type size = ids.size(); file.write((char*)(&size),sizeof(documents_ids_type::size_type)); // On écrit le lexique reader_writer rw; for(documents_ids_type::const_iterator item(ids.begin()),end(ids.end());item!=end;item++) { rw.write(file,item->first); file.write((char*)(&(item->second)),sizeof(document_id_type)); } } void read(std::istream& file) { // On lit l'arbre tree.read(file); // On lit le prochain id de document file.read((char*)(&next_document_id),sizeof(document_id_type)); // On lit la taille du lexique documents_ids_type::size_type size; file.read((char*)(&size),sizeof(documents_ids_type::size_type)); // On lit le lexique dans de nouveaux objets reader_writer rw; documents_ids_type new_ids; reversed_documents_ids_type new_reversed_ids; for(;size>0;--size) { document_type document(rw.read(file)); document_id_type document_id; file.read((char*)(&document_id),sizeof(document_id_type)); new_ids[document] = document_id; new_reversed_ids[document_id] = document; } // On met les nouveaux objets en place ids.swap(new_ids); reversed_ids.swap(new_reversed_ids); } private: const document_id_type get_document_id(const document_type& document) { documents_ids_type::const_iterator document_id(ids.find(document)); if(document_id == ids.end()) { document_id_type new_id = next_document_id++; ids[document] = new_id; reversed_ids[new_id] = document; return new_id; } else { return document_id->second; } } const document_type get_document(const document_id_type& document_id) const { reversed_documents_ids_type::const_iterator document(reversed_ids.find(document_id)); if(document == reversed_ids.end()) { return document_type(); } else { return document->second; } } const result_pointer convert_to_result(collector& to_convert) const { documents_scores_type* scores(to_convert.result().get()); result_type* p_result = new result_type(); result_pointer result(p_result); p_result->reserve(scores->size()); for(documents_scores_type::const_iterator item(scores->begin()),end(scores->end());item!=end;++item) { document_type document = get_document(item->first); p_result->push_back(pair_type(document,item->second)); } std::sort(p_result->begin(),p_result->end(),sort_by_score<pair_type>); return result; } // Données à sauver document_id_type next_document_id; documents_ids_type ids; tree_type tree; // Données transitoires reversed_documents_ids_type reversed_ids; // Utilitaires const regex_type tokenizer; documents_scores_type_factory factory; }; #endif diff --git a/textindex/textindex.pyd b/textindex/textindex.pyd index 2000783..8b75037 100644 Binary files a/textindex/textindex.pyd and b/textindex/textindex.pyd differ diff --git a/textindex/xapian.py b/textindex/xapian.py new file mode 100644 index 0000000..0e85028 --- /dev/null +++ b/textindex/xapian.py @@ -0,0 +1,725 @@ +# This file was created automatically by SWIG 1.3.29. +# Don't modify this file, modify the SWIG interface instead. + +import _xapian +import new +new_instancemethod = new.instancemethod +def _swig_setattr_nondynamic(self,class_type,name,value,static=1): + if (name == "thisown"): return self.this.own(value) + if (name == "this"): + if type(value).__name__ == 'PySwigObject': + self.__dict__[name] = value + return + method = class_type.__swig_setmethods__.get(name,None) + if method: return method(self,value) + if (not static) or hasattr(self,name): + self.__dict__[name] = value + else: + raise AttributeError("You cannot add attributes to %s" % self) + +def _swig_setattr(self,class_type,name,value): + return _swig_setattr_nondynamic(self,class_type,name,value,0) + +def _swig_getattr(self,class_type,name): + if (name == "thisown"): return self.this.own() + method = class_type.__swig_getmethods__.get(name,None) + if method: return method(self) + raise AttributeError,name + +def _swig_repr(self): + try: strthis = "proxy of " + self.this.__repr__() + except: strthis = "" + return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) + +import types +try: + _object = types.ObjectType + _newclass = 1 +except AttributeError: + class _object : pass + _newclass = 0 +del types + + +def _swig_setattr_nondynamic_method(set): + def set_attr(self,name,value): + if (name == "thisown"): return self.this.own(value) + if hasattr(self,name) or (name == "this"): + set(self,name,value) + else: + raise AttributeError("You cannot add attributes to %s" % self) + return set_attr + + +try: + import weakref + weakref_proxy = weakref.proxy +except: + weakref_proxy = lambda x: x + + +class PySwigIterator(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + def __init__(self): raise AttributeError, "No constructor defined" + __repr__ = _swig_repr + __swig_destroy__ = _xapian.delete_PySwigIterator + def __iter__(self): return self +PySwigIterator.value = new_instancemethod(_xapian.PySwigIterator_value,None,PySwigIterator) +PySwigIterator.incr = new_instancemethod(_xapian.PySwigIterator_incr,None,PySwigIterator) +PySwigIterator.decr = new_instancemethod(_xapian.PySwigIterator_decr,None,PySwigIterator) +PySwigIterator.distance = new_instancemethod(_xapian.PySwigIterator_distance,None,PySwigIterator) +PySwigIterator.equal = new_instancemethod(_xapian.PySwigIterator_equal,None,PySwigIterator) +PySwigIterator.copy = new_instancemethod(_xapian.PySwigIterator_copy,None,PySwigIterator) +PySwigIterator.next = new_instancemethod(_xapian.PySwigIterator_next,None,PySwigIterator) +PySwigIterator.previous = new_instancemethod(_xapian.PySwigIterator_previous,None,PySwigIterator) +PySwigIterator.advance = new_instancemethod(_xapian.PySwigIterator_advance,None,PySwigIterator) +PySwigIterator.__eq__ = new_instancemethod(_xapian.PySwigIterator___eq__,None,PySwigIterator) +PySwigIterator.__ne__ = new_instancemethod(_xapian.PySwigIterator___ne__,None,PySwigIterator) +PySwigIterator.__iadd__ = new_instancemethod(_xapian.PySwigIterator___iadd__,None,PySwigIterator) +PySwigIterator.__isub__ = new_instancemethod(_xapian.PySwigIterator___isub__,None,PySwigIterator) +PySwigIterator.__add__ = new_instancemethod(_xapian.PySwigIterator___add__,None,PySwigIterator) +PySwigIterator.__sub__ = new_instancemethod(_xapian.PySwigIterator___sub__,None,PySwigIterator) +PySwigIterator_swigregister = _xapian.PySwigIterator_swigregister +PySwigIterator_swigregister(PySwigIterator) + +MSET_DID = _xapian.MSET_DID +MSET_WT = _xapian.MSET_WT +MSET_RANK = _xapian.MSET_RANK +MSET_PERCENT = _xapian.MSET_PERCENT +MSET_DOCUMENT = _xapian.MSET_DOCUMENT +ESET_TNAME = _xapian.ESET_TNAME +ESET_WT = _xapian.ESET_WT +class MatchDecider(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + __swig_destroy__ = _xapian.delete_MatchDecider + def __init__(self, *args): + if self.__class__ == MatchDecider: + args = (None,) + args + else: + args = (self,) + args + _xapian.MatchDecider_swiginit(self,_xapian.new_MatchDecider(*args)) + def __disown__(self): + self.this.disown() + _xapian.disown_MatchDecider(self) + return weakref_proxy(self) +MatchDecider.__call__ = new_instancemethod(_xapian.MatchDecider___call__,None,MatchDecider) +MatchDecider_swigregister = _xapian.MatchDecider_swigregister +MatchDecider_swigregister(MatchDecider) + +version_string = _xapian.version_string +major_version = _xapian.major_version +minor_version = _xapian.minor_version +revision = _xapian.revision +xapian_version_string = _xapian.xapian_version_string +xapian_major_version = _xapian.xapian_major_version +xapian_minor_version = _xapian.xapian_minor_version +xapian_revision = _xapian.xapian_revision +class PositionIterator(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.PositionIterator_swiginit(self,_xapian.new_PositionIterator(*args)) + __swig_destroy__ = _xapian.delete_PositionIterator +PositionIterator.get_termpos = new_instancemethod(_xapian.PositionIterator_get_termpos,None,PositionIterator) +PositionIterator.next = new_instancemethod(_xapian.PositionIterator_next,None,PositionIterator) +PositionIterator.equals = new_instancemethod(_xapian.PositionIterator_equals,None,PositionIterator) +PositionIterator.skip_to = new_instancemethod(_xapian.PositionIterator_skip_to,None,PositionIterator) +PositionIterator.get_description = new_instancemethod(_xapian.PositionIterator_get_description,None,PositionIterator) +PositionIterator.__eq__ = new_instancemethod(_xapian.PositionIterator___eq__,None,PositionIterator) +PositionIterator.__ne__ = new_instancemethod(_xapian.PositionIterator___ne__,None,PositionIterator) +PositionIterator_swigregister = _xapian.PositionIterator_swigregister +PositionIterator_swigregister(PositionIterator) + +class PostingIterator(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.PostingIterator_swiginit(self,_xapian.new_PostingIterator(*args)) + __swig_destroy__ = _xapian.delete_PostingIterator +PostingIterator.get_docid = new_instancemethod(_xapian.PostingIterator_get_docid,None,PostingIterator) +PostingIterator.next = new_instancemethod(_xapian.PostingIterator_next,None,PostingIterator) +PostingIterator.equals = new_instancemethod(_xapian.PostingIterator_equals,None,PostingIterator) +PostingIterator.skip_to = new_instancemethod(_xapian.PostingIterator_skip_to,None,PostingIterator) +PostingIterator.get_doclength = new_instancemethod(_xapian.PostingIterator_get_doclength,None,PostingIterator) +PostingIterator.get_wdf = new_instancemethod(_xapian.PostingIterator_get_wdf,None,PostingIterator) +PostingIterator.positionlist_begin = new_instancemethod(_xapian.PostingIterator_positionlist_begin,None,PostingIterator) +PostingIterator.positionlist_end = new_instancemethod(_xapian.PostingIterator_positionlist_end,None,PostingIterator) +PostingIterator.get_description = new_instancemethod(_xapian.PostingIterator_get_description,None,PostingIterator) +PostingIterator.__eq__ = new_instancemethod(_xapian.PostingIterator___eq__,None,PostingIterator) +PostingIterator.__ne__ = new_instancemethod(_xapian.PostingIterator___ne__,None,PostingIterator) +PostingIterator_swigregister = _xapian.PostingIterator_swigregister +PostingIterator_swigregister(PostingIterator) + +class TermIterator(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.TermIterator_swiginit(self,_xapian.new_TermIterator(*args)) + __swig_destroy__ = _xapian.delete_TermIterator +TermIterator.get_term = new_instancemethod(_xapian.TermIterator_get_term,None,TermIterator) +TermIterator.next = new_instancemethod(_xapian.TermIterator_next,None,TermIterator) +TermIterator.equals = new_instancemethod(_xapian.TermIterator_equals,None,TermIterator) +TermIterator.skip_to = new_instancemethod(_xapian.TermIterator_skip_to,None,TermIterator) +TermIterator.get_wdf = new_instancemethod(_xapian.TermIterator_get_wdf,None,TermIterator) +TermIterator.get_termfreq = new_instancemethod(_xapian.TermIterator_get_termfreq,None,TermIterator) +TermIterator.positionlist_begin = new_instancemethod(_xapian.TermIterator_positionlist_begin,None,TermIterator) +TermIterator.positionlist_end = new_instancemethod(_xapian.TermIterator_positionlist_end,None,TermIterator) +TermIterator.get_description = new_instancemethod(_xapian.TermIterator_get_description,None,TermIterator) +TermIterator.__eq__ = new_instancemethod(_xapian.TermIterator___eq__,None,TermIterator) +TermIterator.__ne__ = new_instancemethod(_xapian.TermIterator___ne__,None,TermIterator) +TermIterator_swigregister = _xapian.TermIterator_swigregister +TermIterator_swigregister(TermIterator) + +class ValueIterator(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.ValueIterator_swiginit(self,_xapian.new_ValueIterator(*args)) + __swig_destroy__ = _xapian.delete_ValueIterator +ValueIterator.get_value = new_instancemethod(_xapian.ValueIterator_get_value,None,ValueIterator) +ValueIterator.next = new_instancemethod(_xapian.ValueIterator_next,None,ValueIterator) +ValueIterator.equals = new_instancemethod(_xapian.ValueIterator_equals,None,ValueIterator) +ValueIterator.get_valueno = new_instancemethod(_xapian.ValueIterator_get_valueno,None,ValueIterator) +ValueIterator.get_description = new_instancemethod(_xapian.ValueIterator_get_description,None,ValueIterator) +ValueIterator.__eq__ = new_instancemethod(_xapian.ValueIterator___eq__,None,ValueIterator) +ValueIterator.__ne__ = new_instancemethod(_xapian.ValueIterator___ne__,None,ValueIterator) +ValueIterator_swigregister = _xapian.ValueIterator_swigregister +ValueIterator_swigregister(ValueIterator) + +class Document(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.Document_swiginit(self,_xapian.new_Document(*args)) + __swig_destroy__ = _xapian.delete_Document +Document.get_value = new_instancemethod(_xapian.Document_get_value,None,Document) +Document.add_value = new_instancemethod(_xapian.Document_add_value,None,Document) +Document.remove_value = new_instancemethod(_xapian.Document_remove_value,None,Document) +Document.clear_values = new_instancemethod(_xapian.Document_clear_values,None,Document) +Document.get_data = new_instancemethod(_xapian.Document_get_data,None,Document) +Document.set_data = new_instancemethod(_xapian.Document_set_data,None,Document) +Document.add_posting = new_instancemethod(_xapian.Document_add_posting,None,Document) +Document.add_term = new_instancemethod(_xapian.Document_add_term,None,Document) +Document.add_term_nopos = new_instancemethod(_xapian.Document_add_term_nopos,None,Document) +Document.remove_posting = new_instancemethod(_xapian.Document_remove_posting,None,Document) +Document.remove_term = new_instancemethod(_xapian.Document_remove_term,None,Document) +Document.clear_terms = new_instancemethod(_xapian.Document_clear_terms,None,Document) +Document.termlist_count = new_instancemethod(_xapian.Document_termlist_count,None,Document) +Document.termlist_begin = new_instancemethod(_xapian.Document_termlist_begin,None,Document) +Document.termlist_end = new_instancemethod(_xapian.Document_termlist_end,None,Document) +Document.values_count = new_instancemethod(_xapian.Document_values_count,None,Document) +Document.values_begin = new_instancemethod(_xapian.Document_values_begin,None,Document) +Document.values_end = new_instancemethod(_xapian.Document_values_end,None,Document) +Document.get_description = new_instancemethod(_xapian.Document_get_description,None,Document) +Document_swigregister = _xapian.Document_swigregister +Document_swigregister(Document) + +class MSet(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.MSet_swiginit(self,_xapian.new_MSet(*args)) + __swig_destroy__ = _xapian.delete_MSet + items = property(_xapian.MSet_items_get) +MSet.fetch = new_instancemethod(_xapian.MSet_fetch,None,MSet) +MSet.convert_to_percent = new_instancemethod(_xapian.MSet_convert_to_percent,None,MSet) +MSet.get_termfreq = new_instancemethod(_xapian.MSet_get_termfreq,None,MSet) +MSet.get_termweight = new_instancemethod(_xapian.MSet_get_termweight,None,MSet) +MSet.get_firstitem = new_instancemethod(_xapian.MSet_get_firstitem,None,MSet) +MSet.get_matches_lower_bound = new_instancemethod(_xapian.MSet_get_matches_lower_bound,None,MSet) +MSet.get_matches_estimated = new_instancemethod(_xapian.MSet_get_matches_estimated,None,MSet) +MSet.get_matches_upper_bound = new_instancemethod(_xapian.MSet_get_matches_upper_bound,None,MSet) +MSet.get_max_possible = new_instancemethod(_xapian.MSet_get_max_possible,None,MSet) +MSet.get_max_attained = new_instancemethod(_xapian.MSet_get_max_attained,None,MSet) +MSet.size = new_instancemethod(_xapian.MSet_size,None,MSet) +MSet.empty = new_instancemethod(_xapian.MSet_empty,None,MSet) +MSet.is_empty = new_instancemethod(_xapian.MSet_is_empty,None,MSet) +MSet.begin = new_instancemethod(_xapian.MSet_begin,None,MSet) +MSet.end = new_instancemethod(_xapian.MSet_end,None,MSet) +MSet.back = new_instancemethod(_xapian.MSet_back,None,MSet) +MSet.get_hit = new_instancemethod(_xapian.MSet_get_hit,None,MSet) +MSet.get_document_percentage = new_instancemethod(_xapian.MSet_get_document_percentage,None,MSet) +MSet.get_document = new_instancemethod(_xapian.MSet_get_document,None,MSet) +MSet.get_docid = new_instancemethod(_xapian.MSet_get_docid,None,MSet) +MSet.get_document_id = new_instancemethod(_xapian.MSet_get_document_id,None,MSet) +MSet.get_description = new_instancemethod(_xapian.MSet_get_description,None,MSet) +MSet.__cmp__ = new_instancemethod(_xapian.MSet___cmp__,None,MSet) +MSet_swigregister = _xapian.MSet_swigregister +MSet_swigregister(MSet) + +class MSetIterator(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.MSetIterator_swiginit(self,_xapian.new_MSetIterator(*args)) + __swig_destroy__ = _xapian.delete_MSetIterator +MSetIterator.get_docid = new_instancemethod(_xapian.MSetIterator_get_docid,None,MSetIterator) +MSetIterator.next = new_instancemethod(_xapian.MSetIterator_next,None,MSetIterator) +MSetIterator.prev = new_instancemethod(_xapian.MSetIterator_prev,None,MSetIterator) +MSetIterator.equals = new_instancemethod(_xapian.MSetIterator_equals,None,MSetIterator) +MSetIterator.get_document = new_instancemethod(_xapian.MSetIterator_get_document,None,MSetIterator) +MSetIterator.get_rank = new_instancemethod(_xapian.MSetIterator_get_rank,None,MSetIterator) +MSetIterator.get_weight = new_instancemethod(_xapian.MSetIterator_get_weight,None,MSetIterator) +MSetIterator.get_collapse_count = new_instancemethod(_xapian.MSetIterator_get_collapse_count,None,MSetIterator) +MSetIterator.get_percent = new_instancemethod(_xapian.MSetIterator_get_percent,None,MSetIterator) +MSetIterator.get_description = new_instancemethod(_xapian.MSetIterator_get_description,None,MSetIterator) +MSetIterator.__eq__ = new_instancemethod(_xapian.MSetIterator___eq__,None,MSetIterator) +MSetIterator.__ne__ = new_instancemethod(_xapian.MSetIterator___ne__,None,MSetIterator) +MSetIterator_swigregister = _xapian.MSetIterator_swigregister +MSetIterator_swigregister(MSetIterator) + +class ESet(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.ESet_swiginit(self,_xapian.new_ESet(*args)) + __swig_destroy__ = _xapian.delete_ESet + items = property(_xapian.ESet_items_get) +ESet.get_ebound = new_instancemethod(_xapian.ESet_get_ebound,None,ESet) +ESet.size = new_instancemethod(_xapian.ESet_size,None,ESet) +ESet.empty = new_instancemethod(_xapian.ESet_empty,None,ESet) +ESet.is_empty = new_instancemethod(_xapian.ESet_is_empty,None,ESet) +ESet.begin = new_instancemethod(_xapian.ESet_begin,None,ESet) +ESet.end = new_instancemethod(_xapian.ESet_end,None,ESet) +ESet.back = new_instancemethod(_xapian.ESet_back,None,ESet) +ESet.get_description = new_instancemethod(_xapian.ESet_get_description,None,ESet) +ESet_swigregister = _xapian.ESet_swigregister +ESet_swigregister(ESet) + +class ESetIterator(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.ESetIterator_swiginit(self,_xapian.new_ESetIterator(*args)) + __swig_destroy__ = _xapian.delete_ESetIterator +ESetIterator.get_termname = new_instancemethod(_xapian.ESetIterator_get_termname,None,ESetIterator) +ESetIterator.next = new_instancemethod(_xapian.ESetIterator_next,None,ESetIterator) +ESetIterator.prev = new_instancemethod(_xapian.ESetIterator_prev,None,ESetIterator) +ESetIterator.equals = new_instancemethod(_xapian.ESetIterator_equals,None,ESetIterator) +ESetIterator.get_weight = new_instancemethod(_xapian.ESetIterator_get_weight,None,ESetIterator) +ESetIterator.get_description = new_instancemethod(_xapian.ESetIterator_get_description,None,ESetIterator) +ESetIterator.__eq__ = new_instancemethod(_xapian.ESetIterator___eq__,None,ESetIterator) +ESetIterator.__ne__ = new_instancemethod(_xapian.ESetIterator___ne__,None,ESetIterator) +ESetIterator_swigregister = _xapian.ESetIterator_swigregister +ESetIterator_swigregister(ESetIterator) + +class RSet(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.RSet_swiginit(self,_xapian.new_RSet(*args)) + __swig_destroy__ = _xapian.delete_RSet +RSet.size = new_instancemethod(_xapian.RSet_size,None,RSet) +RSet.empty = new_instancemethod(_xapian.RSet_empty,None,RSet) +RSet.is_empty = new_instancemethod(_xapian.RSet_is_empty,None,RSet) +RSet.add_document = new_instancemethod(_xapian.RSet_add_document,None,RSet) +RSet.remove_document = new_instancemethod(_xapian.RSet_remove_document,None,RSet) +RSet.contains = new_instancemethod(_xapian.RSet_contains,None,RSet) +RSet.get_description = new_instancemethod(_xapian.RSet_get_description,None,RSet) +RSet_swigregister = _xapian.RSet_swigregister +RSet_swigregister(RSet) + +class Enquire(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.Enquire_swiginit(self,_xapian.new_Enquire(*args)) + __swig_destroy__ = _xapian.delete_Enquire + ASCENDING = _xapian.Enquire_ASCENDING + DESCENDING = _xapian.Enquire_DESCENDING + DONT_CARE = _xapian.Enquire_DONT_CARE +Enquire.set_query = new_instancemethod(_xapian.Enquire_set_query,None,Enquire) +Enquire.get_query = new_instancemethod(_xapian.Enquire_get_query,None,Enquire) +Enquire.set_weighting_scheme = new_instancemethod(_xapian.Enquire_set_weighting_scheme,None,Enquire) +Enquire.set_collapse_key = new_instancemethod(_xapian.Enquire_set_collapse_key,None,Enquire) +Enquire.set_docid_order = new_instancemethod(_xapian.Enquire_set_docid_order,None,Enquire) +Enquire.set_sort_forward = new_instancemethod(_xapian.Enquire_set_sort_forward,None,Enquire) +Enquire.set_cutoff = new_instancemethod(_xapian.Enquire_set_cutoff,None,Enquire) +Enquire.set_sorting = new_instancemethod(_xapian.Enquire_set_sorting,None,Enquire) +Enquire.set_sort_by_relevance = new_instancemethod(_xapian.Enquire_set_sort_by_relevance,None,Enquire) +Enquire.set_sort_by_value = new_instancemethod(_xapian.Enquire_set_sort_by_value,None,Enquire) +Enquire.set_sort_by_value_then_relevance = new_instancemethod(_xapian.Enquire_set_sort_by_value_then_relevance,None,Enquire) +Enquire.set_sort_by_relevance_then_value = new_instancemethod(_xapian.Enquire_set_sort_by_relevance_then_value,None,Enquire) +Enquire.set_bias = new_instancemethod(_xapian.Enquire_set_bias,None,Enquire) +Enquire.get_mset = new_instancemethod(_xapian.Enquire_get_mset,None,Enquire) +Enquire.get_eset = new_instancemethod(_xapian.Enquire_get_eset,None,Enquire) +Enquire.get_matching_terms_begin = new_instancemethod(_xapian.Enquire_get_matching_terms_begin,None,Enquire) +Enquire.get_matching_terms_end = new_instancemethod(_xapian.Enquire_get_matching_terms_end,None,Enquire) +Enquire.register_match_decider = new_instancemethod(_xapian.Enquire_register_match_decider,None,Enquire) +Enquire.get_matching_terms = new_instancemethod(_xapian.Enquire_get_matching_terms,None,Enquire) +Enquire.get_description = new_instancemethod(_xapian.Enquire_get_description,None,Enquire) +Enquire_swigregister = _xapian.Enquire_swigregister +Enquire_swigregister(Enquire) + +class Weight(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + def __init__(self): raise AttributeError, "No constructor defined" + __repr__ = _swig_repr + __swig_destroy__ = _xapian.delete_Weight +Weight.name = new_instancemethod(_xapian.Weight_name,None,Weight) +Weight.serialise = new_instancemethod(_xapian.Weight_serialise,None,Weight) +Weight.unserialise = new_instancemethod(_xapian.Weight_unserialise,None,Weight) +Weight.get_sumpart = new_instancemethod(_xapian.Weight_get_sumpart,None,Weight) +Weight.get_maxpart = new_instancemethod(_xapian.Weight_get_maxpart,None,Weight) +Weight.get_sumextra = new_instancemethod(_xapian.Weight_get_sumextra,None,Weight) +Weight.get_maxextra = new_instancemethod(_xapian.Weight_get_maxextra,None,Weight) +Weight.get_sumpart_needs_doclength = new_instancemethod(_xapian.Weight_get_sumpart_needs_doclength,None,Weight) +Weight_swigregister = _xapian.Weight_swigregister +Weight_swigregister(Weight) + +class BoolWeight(Weight): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.BoolWeight_swiginit(self,_xapian.new_BoolWeight(*args)) + __swig_destroy__ = _xapian.delete_BoolWeight +BoolWeight.clone = new_instancemethod(_xapian.BoolWeight_clone,None,BoolWeight) +BoolWeight.unserialise = new_instancemethod(_xapian.BoolWeight_unserialise,None,BoolWeight) +BoolWeight_swigregister = _xapian.BoolWeight_swigregister +BoolWeight_swigregister(BoolWeight) + +class BM25Weight(Weight): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.BM25Weight_swiginit(self,_xapian.new_BM25Weight(*args)) + __swig_destroy__ = _xapian.delete_BM25Weight +BM25Weight.clone = new_instancemethod(_xapian.BM25Weight_clone,None,BM25Weight) +BM25Weight.unserialise = new_instancemethod(_xapian.BM25Weight_unserialise,None,BM25Weight) +BM25Weight_swigregister = _xapian.BM25Weight_swigregister +BM25Weight_swigregister(BM25Weight) + +class TradWeight(Weight): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.TradWeight_swiginit(self,_xapian.new_TradWeight(*args)) + __swig_destroy__ = _xapian.delete_TradWeight +TradWeight.clone = new_instancemethod(_xapian.TradWeight_clone,None,TradWeight) +TradWeight.unserialise = new_instancemethod(_xapian.TradWeight_unserialise,None,TradWeight) +TradWeight_swigregister = _xapian.TradWeight_swigregister +TradWeight_swigregister(TradWeight) + +class Database(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + __swig_destroy__ = _xapian.delete_Database + def __init__(self, *args): + _xapian.Database_swiginit(self,_xapian.new_Database(*args)) +Database.add_database = new_instancemethod(_xapian.Database_add_database,None,Database) +Database.reopen = new_instancemethod(_xapian.Database_reopen,None,Database) +Database.get_description = new_instancemethod(_xapian.Database_get_description,None,Database) +Database.postlist_begin = new_instancemethod(_xapian.Database_postlist_begin,None,Database) +Database.postlist_end = new_instancemethod(_xapian.Database_postlist_end,None,Database) +Database.termlist_begin = new_instancemethod(_xapian.Database_termlist_begin,None,Database) +Database.termlist_end = new_instancemethod(_xapian.Database_termlist_end,None,Database) +Database.positionlist_begin = new_instancemethod(_xapian.Database_positionlist_begin,None,Database) +Database.positionlist_end = new_instancemethod(_xapian.Database_positionlist_end,None,Database) +Database.allterms_begin = new_instancemethod(_xapian.Database_allterms_begin,None,Database) +Database.allterms_end = new_instancemethod(_xapian.Database_allterms_end,None,Database) +Database.get_doccount = new_instancemethod(_xapian.Database_get_doccount,None,Database) +Database.get_lastdocid = new_instancemethod(_xapian.Database_get_lastdocid,None,Database) +Database.get_avlength = new_instancemethod(_xapian.Database_get_avlength,None,Database) +Database.get_termfreq = new_instancemethod(_xapian.Database_get_termfreq,None,Database) +Database.term_exists = new_instancemethod(_xapian.Database_term_exists,None,Database) +Database.get_collection_freq = new_instancemethod(_xapian.Database_get_collection_freq,None,Database) +Database.get_doclength = new_instancemethod(_xapian.Database_get_doclength,None,Database) +Database.keep_alive = new_instancemethod(_xapian.Database_keep_alive,None,Database) +Database.get_document = new_instancemethod(_xapian.Database_get_document,None,Database) +Database_swigregister = _xapian.Database_swigregister +Database_swigregister(Database) + +class WritableDatabase(Database): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + __swig_destroy__ = _xapian.delete_WritableDatabase + def __init__(self, *args): + _xapian.WritableDatabase_swiginit(self,_xapian.new_WritableDatabase(*args)) +WritableDatabase.flush = new_instancemethod(_xapian.WritableDatabase_flush,None,WritableDatabase) +WritableDatabase.begin_transaction = new_instancemethod(_xapian.WritableDatabase_begin_transaction,None,WritableDatabase) +WritableDatabase.commit_transaction = new_instancemethod(_xapian.WritableDatabase_commit_transaction,None,WritableDatabase) +WritableDatabase.cancel_transaction = new_instancemethod(_xapian.WritableDatabase_cancel_transaction,None,WritableDatabase) +WritableDatabase.add_document = new_instancemethod(_xapian.WritableDatabase_add_document,None,WritableDatabase) +WritableDatabase.delete_document = new_instancemethod(_xapian.WritableDatabase_delete_document,None,WritableDatabase) +WritableDatabase.replace_document = new_instancemethod(_xapian.WritableDatabase_replace_document,None,WritableDatabase) +WritableDatabase.get_description = new_instancemethod(_xapian.WritableDatabase_get_description,None,WritableDatabase) +WritableDatabase_swigregister = _xapian.WritableDatabase_swigregister +WritableDatabase_swigregister(WritableDatabase) + +DB_CREATE_OR_OPEN = _xapian.DB_CREATE_OR_OPEN +DB_CREATE = _xapian.DB_CREATE +DB_CREATE_OR_OVERWRITE = _xapian.DB_CREATE_OR_OVERWRITE +DB_OPEN = _xapian.DB_OPEN +open_stub = _xapian.open_stub +inmemory_open = _xapian.inmemory_open +class Query(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + OP_AND = _xapian.Query_OP_AND + OP_OR = _xapian.Query_OP_OR + OP_AND_NOT = _xapian.Query_OP_AND_NOT + OP_XOR = _xapian.Query_OP_XOR + OP_AND_MAYBE = _xapian.Query_OP_AND_MAYBE + OP_FILTER = _xapian.Query_OP_FILTER + OP_NEAR = _xapian.Query_OP_NEAR + OP_PHRASE = _xapian.Query_OP_PHRASE + OP_ELITE_SET = _xapian.Query_OP_ELITE_SET + def __init__(self, *args): + _xapian.Query_swiginit(self,_xapian.new_Query(*args)) + __swig_destroy__ = _xapian.delete_Query +Query.get_length = new_instancemethod(_xapian.Query_get_length,None,Query) +Query.get_terms_begin = new_instancemethod(_xapian.Query_get_terms_begin,None,Query) +Query.get_terms_end = new_instancemethod(_xapian.Query_get_terms_end,None,Query) +Query.empty = new_instancemethod(_xapian.Query_empty,None,Query) +Query.is_empty = new_instancemethod(_xapian.Query_is_empty,None,Query) +Query.get_description = new_instancemethod(_xapian.Query_get_description,None,Query) +Query_swigregister = _xapian.Query_swigregister +Query_swigregister(Query) +open = _xapian.open +quartz_open = _xapian.quartz_open +open_da = _xapian.open_da +open_db = _xapian.open_db +remote_open = _xapian.remote_open + +class Stopper(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + __swig_destroy__ = _xapian.delete_Stopper + def __init__(self, *args): + if self.__class__ == Stopper: + args = (None,) + args + else: + args = (self,) + args + _xapian.Stopper_swiginit(self,_xapian.new_Stopper(*args)) + def __disown__(self): + self.this.disown() + _xapian.disown_Stopper(self) + return weakref_proxy(self) +Stopper.__call__ = new_instancemethod(_xapian.Stopper___call__,None,Stopper) +Stopper.get_description = new_instancemethod(_xapian.Stopper_get_description,None,Stopper) +Stopper_swigregister = _xapian.Stopper_swigregister +Stopper_swigregister(Stopper) + +class SimpleStopper(Stopper): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.SimpleStopper_swiginit(self,_xapian.new_SimpleStopper(*args)) + __swig_destroy__ = _xapian.delete_SimpleStopper +SimpleStopper.add = new_instancemethod(_xapian.SimpleStopper_add,None,SimpleStopper) +SimpleStopper_swigregister = _xapian.SimpleStopper_swigregister +SimpleStopper_swigregister(SimpleStopper) + +class QueryParser(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + FLAG_BOOLEAN = _xapian.QueryParser_FLAG_BOOLEAN + FLAG_PHRASE = _xapian.QueryParser_FLAG_PHRASE + FLAG_LOVEHATE = _xapian.QueryParser_FLAG_LOVEHATE + FLAG_BOOLEAN_ANY_CASE = _xapian.QueryParser_FLAG_BOOLEAN_ANY_CASE + FLAG_WILDCARD = _xapian.QueryParser_FLAG_WILDCARD + STEM_NONE = _xapian.QueryParser_STEM_NONE + STEM_SOME = _xapian.QueryParser_STEM_SOME + STEM_ALL = _xapian.QueryParser_STEM_ALL + def __init__(self, *args): + _xapian.QueryParser_swiginit(self,_xapian.new_QueryParser(*args)) + __swig_destroy__ = _xapian.delete_QueryParser +QueryParser.set_stemmer = new_instancemethod(_xapian.QueryParser_set_stemmer,None,QueryParser) +QueryParser.set_stemming_strategy = new_instancemethod(_xapian.QueryParser_set_stemming_strategy,None,QueryParser) +QueryParser.set_stopper = new_instancemethod(_xapian.QueryParser_set_stopper,None,QueryParser) +QueryParser.set_default_op = new_instancemethod(_xapian.QueryParser_set_default_op,None,QueryParser) +QueryParser.get_default_op = new_instancemethod(_xapian.QueryParser_get_default_op,None,QueryParser) +QueryParser.set_database = new_instancemethod(_xapian.QueryParser_set_database,None,QueryParser) +QueryParser.parse_query = new_instancemethod(_xapian.QueryParser_parse_query,None,QueryParser) +QueryParser.add_prefix = new_instancemethod(_xapian.QueryParser_add_prefix,None,QueryParser) +QueryParser.add_boolean_prefix = new_instancemethod(_xapian.QueryParser_add_boolean_prefix,None,QueryParser) +QueryParser.stoplist_begin = new_instancemethod(_xapian.QueryParser_stoplist_begin,None,QueryParser) +QueryParser.stoplist_end = new_instancemethod(_xapian.QueryParser_stoplist_end,None,QueryParser) +QueryParser.unstem_begin = new_instancemethod(_xapian.QueryParser_unstem_begin,None,QueryParser) +QueryParser.unstem_end = new_instancemethod(_xapian.QueryParser_unstem_end,None,QueryParser) +QueryParser.get_description = new_instancemethod(_xapian.QueryParser_get_description,None,QueryParser) +QueryParser_swigregister = _xapian.QueryParser_swigregister +QueryParser_swigregister(QueryParser) + +class Stem(object): + thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') + __repr__ = _swig_repr + def __init__(self, *args): + _xapian.Stem_swiginit(self,_xapian.new_Stem(*args)) + __swig_destroy__ = _xapian.delete_Stem + get_available_languages = staticmethod(_xapian.Stem_get_available_languages) +Stem.__call__ = new_instancemethod(_xapian.Stem___call__,None,Stem) +Stem.stem_word = new_instancemethod(_xapian.Stem_stem_word,None,Stem) +Stem.get_description = new_instancemethod(_xapian.Stem_get_description,None,Stem) +Stem_swigregister = _xapian.Stem_swigregister +Stem_swigregister(Stem) +Stem_get_available_languages = _xapian.Stem_get_available_languages + +# Python-style iterators to mirror the C++ ones +class MSetIter: + def __init__(self, start, end): + self.iter = start + self.end = end + + def __iter__(self): + return self + + def next(self): + if self.iter==self.end: + raise StopIteration + else: + r = [self.iter.get_docid(), self.iter.get_weight(), self.iter.get_rank(), self.iter.get_percent(), self.iter.get_document()] + self.iter.next() + return r + +class ESetIter: + def __init__(self, start, end): + self.iter = start + self.end = end + + def __iter__(self): + return self + + def next(self): + if self.iter==self.end: + raise StopIteration + else: + r = [self.iter.get_termname(), self.iter.get_weight()] + self.iter.next() + return r + +class TermIter: + HAS_NOTHING = 0 + HAS_TERMFREQS = 1 + HAS_POSITIONS = 2 + + def __init__(self, start, end, has = HAS_NOTHING): + self.iter = start + self.end = end + self.has = has + + def __iter__(self): + return self + + def next(self): + if self.iter==self.end: + raise StopIteration + else: + termfreq = 0 + if self.has & TermIter.HAS_TERMFREQS: + termfreq = self.iter.get_termfreq() + if self.has & TermIter.HAS_POSITIONS: + positer = PositionIter(self.iter.positionlist_begin(), self.iter.positionlist_end()) + else: + positer = PositionIter() + r = [self.iter.get_term(), self.iter.get_wdf(), termfreq, positer] + self.iter.next() + return r + +class PostingIter: + def __init__(self, start, end): + self.iter = start + self.end = end + + def __iter__(self): + return self + + def next(self): + if self.iter==self.end: + raise StopIteration + else: + r = [self.iter.get_docid(), self.iter.get_doclength(), self.iter.get_wdf(), PositionIter(self.iter.positionlist_begin(), self.iter.positionlist_end())] + self.iter.next() + return r + +class PositionIter: + def __init__(self, start = 0, end = 0): + self.iter = start + self.end = end + + def __iter__(self): + return self + + def next(self): + if self.iter==self.end: + raise StopIteration + else: + r = self.iter.get_termpos() + self.iter.next() + return r + +class ValueIter: + def __init__(self, start, end): + self.iter = start + self.end = end + + def __iter__(self): + return self + + def next(self): + if self.iter==self.end: + raise StopIteration + else: + r = [self.iter.get_valueno(), self.iter.get_value()] + self.iter.next() + return r + +# Bind the Python iterators into the shadow classes +def mset_gen_iter(self): + return MSetIter(self.begin(), self.end()) + +MSet.__iter__ = mset_gen_iter + +def eset_gen_iter(self): + return ESetIter(self.begin(), self.end()) + +ESet.__iter__ = eset_gen_iter + +def enquire_gen_iter(self, which): + return TermIter(self.get_matching_terms_begin(which), self.get_matching_terms_end(which)) + +Enquire.matching_terms = enquire_gen_iter + +def query_gen_iter(self): + return TermIter(self.get_terms_begin(), self.get_terms_end()) + +Query.__iter__ = query_gen_iter + +def database_gen_allterms_iter(self): + return TermIter(self.allterms_begin(), self.allterms_end(), TermIter.HAS_TERMFREQS) + +Database.__iter__ = database_gen_allterms_iter + +def database_gen_postlist_iter(self, tname): + return PostingIter(self.postlist_begin(tname), self.postlist_end(tname)) +def database_gen_termlist_iter(self, docid): + return TermIter(self.termlist_begin(docid), self.termlist_end(docid), TermIter.HAS_TERMFREQS|TermIter.HAS_POSITIONS) +def database_gen_positionlist_iter(self, docid, tname): + return PositionIter(self.positionlist_begin(docid, tname), self.positionlist_end(docid, tname)) + +Database.allterms = database_gen_allterms_iter +Database.postlist = database_gen_postlist_iter +Database.termlist = database_gen_termlist_iter +Database.positionlist = database_gen_positionlist_iter + +def document_gen_termlist_iter(self): + return TermIter(self.termlist_begin(), self.termlist_end(), TermIter.HAS_POSITIONS) +def document_gen_values_iter(self): + return ValueIter(self.values_begin(), self.values_end()) + +Document.__iter__ = document_gen_termlist_iter +Document.termlist = document_gen_termlist_iter +Document.values = document_gen_values_iter + +def queryparser_gen_stoplist_iter(self): + return TermIter(self.stoplist_begin(), self.stoplist_end()) +def queryparser_gen_unstemlist_iter(self, tname): + return TermIter(self.unstem_begin(tname), self.unstem_end(tname)) + +QueryParser.stoplist = queryparser_gen_stoplist_iter +QueryParser.unstemlist = queryparser_gen_unstemlist_iter + + + +
nlehuen/pytst
dc1b3b95361241b6643497d6a5f683cb29dc8224
Version finale de remove()
diff --git a/python/compacttst.py b/python/compacttst.py index 43e9af1..274fcec 100644 --- a/python/compacttst.py +++ b/python/compacttst.py @@ -1,718 +1,769 @@ # -*- coding: iso-8859-1 -*- from array import array import sys # Tant qu'à faire vu qu'ici le nombre de caractères par noeud est complètement # dynamique, on peut se lâcher, mettre 1024 caractère ou plus CHARS_PER_NODE = 16 class tst_node(object): """ classe représentant un noeud du TST """ # __slots__ est une optimisation permettant de créer des objets Python # non dynamiques, ce qui utilise moins de mémoire __slots__ = ['chars','data','next','left','right'] instances = 0 def __init__(self): tst_node.instances += 1 self.chars = array('c') self.data = None self.next = None self.left = None self.right = None def __repr__(self): return "node(%s,data=%s,%i,%i,%i)"%( self.chars, self.data, self.left is not None and 1 or 0, self.next is not None and 1 or 0, self.right is not None and 1 or 0, ) class balance_info(object): __slots__ = ['did_balance','height','balance','right_balance','left_balance'] def __init__(self,did_balance=False,height=0,balance=0,right_balance=0,left_balance=0): self.did_balance = did_balance self.height = height self.balance = balance self.right_balance = right_balance self.left_balance = left_balance def __repr__(self): return "balance_info(d=%s,h=%s,b=%s,l=%s,r=%s)"%( self.did_balance, self.height, self.balance, self.left_balance, self.right_balance ) class compact_tst(object): """ Implémentation d'un TST compact """ def __init__(self): self.root = None def __getitem__(self,string): """ Lit dans l'arbre selon la syntaxe tst[string] """ # ATTENTION : ce code est intentionnellement dupliqué dans la méthode # visit(). Ne pas oublier de mettre celle-ci à jour lorsqu'il est modifié # ici. node = self.root index = 0 while node is not None: local_index = 0 # On avance tant qu'il y a égalité diff = 0 while local_index < len(node.chars) and index < len(string): diff = cmp(string[index],node.chars[local_index]) if diff == 0: local_index += 1 index += 1 else: break if diff != 0: # On a une différence de caractère if local_index < len(node.chars) - 1: # on s'est arrêté avant le dernier caractère du noeud, # il n'y a donc pas de match possible (sinon il y aurait eu # split à l'insertion) return None else: # différence au dernier caractère du noeud if diff>0: node = node.left elif diff<0: node = node.right elif local_index == len(node.chars): # On est au bout des caractères du noeud if index == len(string): # On est également au bout de la clé # C'est qu'on a de la chance ! return node.data else: # On avance d'un cran node = node.next else: # On n'est pas au bout des caractères, c'est qu'on est au # bout de la clé, et donc qu'il n'y a pas de match, sinon # il y aurait eu un split assert index == len(string) return None # node is None ==> pas de match return None def __setitem__(self,string,value): """ Ecrit dans l'arbre selon la syntaxe tst[string] = value """ self.root, discard = self._insert(string,value,0,self.root) assert self[string] == value def _insert(self,string,value,index,node): if node is None: return self._new_node(string,value,index) local_index = 0 # On avance tant qu'il y a égalité diff = 0 while local_index < len(node.chars) and index<len(string): diff = cmp(string[index],node.chars[local_index]) if diff == 0: local_index += 1 index += 1 else: break if diff!=0: assert local_index < len(node.chars) and index<len(string) # On a trouvé un point de divergence avant le dernier caractère du # noeud, et de la clé, il va donc falloir splitter if local_index < len(node.chars) - 1: node, balance = self._split_node(node,local_index) assert balance.height == self._compute_balance(node).height # On peut essayer de joindre le noeud suivant au noeud d'après # car le split peut permettre de compléter un noeud pas totalement # remplit node.next, discard = self._compact_node(node.next,None) # Maintenant que le split est fait, on peut continuer à positionner # la nouvelle clé balance = balance_info() if diff>0: node.left, left_balance = self._insert(string,value,index,node.left) assert not (len(node.left.chars)>1 and left_balance.height!=1) balance.did_balance = left_balance.did_balance right_balance = self._compute_balance(node.right) else: node.right, right_balance = self._insert(string,value,index,node.right) assert not (len(node.right.chars)>1 and right_balance.height!=1) balance.did_balance = right_balance.did_balance left_balance = self._compute_balance(node.left) # On calcule la nouvelle balance en tenant compte des modifs if len(node.chars)>1: balance.height = 1 else: balance.height = max(left_balance.height, right_balance.height) + 1 balance.balance = left_balance.height - right_balance.height balance.left_balance = left_balance.balance balance.right_balance = right_balance.balance assert balance.height == self._compute_balance(node).height assert left_balance.height == self._compute_balance(node.left).height assert right_balance.height == self._compute_balance(node.right).height if not balance.did_balance: # On effectue la balance si elle n'a pas déjà été effectuée node, balance = self._balance(node,balance) if len(node.chars)!=1: # Si à l'issue de la balance on se retrouve avec plusieurs # caractères, alors la hauteur du nouveau noeud est 1. balance.height = 1 balance.balance = 0 balance.left_balance = 0 balance.right_balance = 0 assert balance.height == self._compute_balance(node).height return node, balance elif local_index == len(node.chars): # On est arrivé au bout des caractères du noeud # sans différence if index == len(string): # On est également au bout de la clé # C'est qu'on a de la chance ! node.data = value else: # On n'est pas au bout de la clé node.next, next_balance = self._insert(string,value,index,node.next) # Suite à un split du noeud suivant, il est peut-être possible # de le recoller à ce noeud ? node, discard = self._compact_node(node, None) return node, self._compute_balance(node) else: # On est arrivé au bout de la clé, mais pas au bout des caractères # du noeud assert index == len(string) # On est au bout de la clé, mais avant la fin des caractères du # noeud ; il faut donc splitter, mais au local_index précédent car # on a bêtement avancé les deux à la fois aux lignes 105 - 106 node, balance = self._split_node(node,local_index-1) # On peut essayer de joindre le noeud suivant au noeud d'après node.next, discard = self._compact_node(node.next,None) # On stocke ensuite la clé et la valeur node.data = value return node, balance def __delitem__(self,string): - self.root, discard = self._remove(string,0,self.root) + self.root, discard = self._remove(string,0,self.root) def _remove(self,string,index,node): if node is None: return None local_index = 0 # On avance tant qu'il y a égalité diff = 0 while local_index < len(node.chars) and index<len(string): diff = cmp(string[index],node.chars[local_index]) if diff == 0: local_index += 1 index += 1 else: break if diff!=0: assert local_index < len(node.chars) and index<len(string) # On a trouvé un point de divergence avant le dernier caractère du # noeud, et de la clé, il va donc falloir splitter if local_index < len(node.chars) - 1: return node, self._compute_balance(node) # Maintenant que le split est fait, on peut continuer à positionner # la nouvelle clé balance = balance_info() if diff>0: node.left, left_balance = self._remove(string,index,node.left) - assert not (len(node.left.chars)>1 and left_balance.height!=1) + assert not (node.left and len(node.left.chars)>1 and left_balance.height!=1) balance.did_balance = left_balance.did_balance right_balance = self._compute_balance(node.right) else: node.right, right_balance = self._remove(string,index,node.right) - assert not (len(node.right.chars)>1 and right_balance.height!=1) + assert not (node.right and len(node.right.chars)>1 and right_balance.height!=1) balance.did_balance = right_balance.did_balance left_balance = self._compute_balance(node.left) # On calcule la nouvelle balance en tenant compte des modifs if len(node.chars)>1: balance.height = 1 else: balance.height = max(left_balance.height, right_balance.height) + 1 balance.balance = left_balance.height - right_balance.height balance.left_balance = left_balance.balance balance.right_balance = right_balance.balance assert balance.height == self._compute_balance(node).height assert left_balance.height == self._compute_balance(node.left).height assert right_balance.height == self._compute_balance(node.right).height if not balance.did_balance: # On effectue la balance si elle n'a pas déjà été effectuée - # node, balance = self._balance(node,balance) + node, balance = self._balance(node,balance) if len(node.chars)!=1: # Si à l'issue de la balance on se retrouve avec plusieurs # caractères, alors la hauteur du nouveau noeud est 1. balance.height = 1 balance.balance = 0 balance.left_balance = 0 balance.right_balance = 0 assert balance.height == self._compute_balance(node).height return self._compact_node(node,balance) elif local_index == len(node.chars): # On est arrivé au bout des caractères du noeud # sans différence if index == len(string): # On est également au bout de la clé # C'est qu'on a de la chance ! node.data = None else: # On n'est pas au bout de la clé node.next, next_balance = self._remove(string,index,node.next) # Suite à un split du noeud suivant, il est peut-être possible # de le recoller à ce noeud ? # node, discard = self._compact_node(node, None) return self._compact_node(node,self._compute_balance(node)) else: # On est arrivé au bout de la clé, mais pas au bout des caractères # du noeud assert index == len(string) # On est au bout de la clé, mais avant la fin des caractères du # noeud return node, balance def _compute_balance(self,node): if node is not None: if len(node.chars)>1: # La hauteur d'un noeud contenant plusieurs caractères # est forcément 1 return balance_info(height=1) else: balance = balance_info() # Récursion sur les noeuds fils left_balance = self._compute_balance(node.left) right_balance = self._compute_balance(node.right) balance.did_balance = False balance.height = max(left_balance.height, right_balance.height) + 1 balance.balance = left_balance.height - right_balance.height balance.left_balance = left_balance.balance balance.right_balance = right_balance.balance return balance else: # La hauteur d'un noeud non existant est 0, ce qui fait # que la hauteur d'une feuille est 1 return balance_info() def _balance(self,node,balance): assert balance.height == self._compute_balance(node).height assert len(node.chars)>1 or balance.balance == self._compute_balance(node).balance, "%s : %s != %s"%(node,balance,self._compute_balance(node)) assert balance.left_balance == self._compute_balance(node.left).balance assert balance.right_balance == self._compute_balance(node.right).balance + assert -3 < balance.balance < 3 + # Assure le critère AVL if balance.balance > 1: if balance.left_balance > 0: node, balance = self._ll(node,balance) else: node, balance = self._lr(node,balance) balance.did_balance = True elif balance.balance < -1: if balance.right_balance < 0: node, balance = self._rr(node,balance) else: node, balance = self._rl(node,balance) balance.did_balance = True - assert -2 < balance.balance < 2 assert -2 < self._compute_balance(node).balance < 2 + assert -2 < balance.balance < 2 return node, balance def _ll(self,node,balance): # Un déséquilibre LL n'est possible qu'avec un noeud de gauche # n'ayant qu'un caractère assert len(node.left.chars) == 1 # On fait la rotation au niveau des liens left_node = node.left node.left = left_node.right left_node.right = node # Et maintenant on ramène tous les caractères du noeud d'origine sauf son # dernier, et on les insère au début du noeud de gauche. # En gros si dans le noeud d'origine on a abcdefG # et dans le noeud de gauche on a juste B # A la fin on a dans le noeud d'origine juste G # et dans le noeud de gauche abcdefB new_char = node.chars.pop() node.chars.append(left_node.chars.pop()) left_node.chars.append(new_char) node.chars, left_node.chars = left_node.chars, node.chars # Il est possible que le noeud d'origine soit concaténable avec la suite left_node.right, discard = self._compact_node(left_node.right,None) # On ajuste la balance en fonction de l'opération effectuée balance.height -= 1 balance.balance = 0 balance.left_balance = 0 # Le noeud de gauche prend la place du noeud d'origine dans l'arbre return left_node, self._compute_balance(left_node) def _rr(self,node,balance): assert len(node.right.chars) == 1 right_node = node.right node.right = right_node.left right_node.left = node new_char = node.chars.pop() node.chars.append(right_node.chars.pop()) right_node.chars.append(new_char) node.chars, right_node.chars = right_node.chars, node.chars right_node.left, discard = self._compact_node(right_node.left,None) balance.height -= 1 balance.balance = 0 balance.right_balance = 0 return right_node, self._compute_balance(right_node) def _lr(self,node,balance): if len(node.left.right.chars)>1: node.left.right, discard = self._split_node(node.left.right,0) node.left, discard = self._rr(node.left,balance_info()) node, balance = self._ll(node,balance) return node, balance def _rl(self,node,balance): if len(node.right.left.chars)>1: node.right.left, discard = self._split_node(node.right.left,0) node.right, discard = self._ll(node.right,balance_info()) node, balance = self._rr(node,balance) return node, balance def _split_node(self,node,local_index): """ Découpe un noeud à l'index donné """ assert local_index < len(node.chars) # On crée un nouveau noeud new_node = tst_node() # On prend tout le début du segment de clé du noeud y compris # le caractère qui diffère et on les met dans le nouveau noeud new_node.chars = node.chars[0:local_index + 1] # La suite de ce nouveau noeud est l'ancien noeud new_node.next = node # On adapte la chaîne dans l'ancien noeud, c'est le restant de # la chaîne après le split node.chars = node.chars[local_index + 1:] return new_node, balance_info(height=1) def _compact_node(self,node,balance,debug=False): """ Tente de ressouder un noeud à son noeud suivant si cela est possible """ if node is None: - return None + return None, balance_info() + elif node.data is not None: + return node, balance elif ( node.next is not None and node.left is None and node.right is None - and node.data is None and len(node.chars)+len(node.next.chars)<CHARS_PER_NODE ): # Les quatre conditions ci dessus sont : # - on a un noeud suivant # - le noeud actuel n'est pas un pivot (dans ce cas la concaténation # serait impossible) # - le noeud actuel ne contient pas de données (idem) # - il y a de la place pour les caractères du noeud courant dans # le noeud suivant if debug: print "CAT", node, node.next, node.chars.extend(node.next.chars) node.next.chars = node.chars if debug: print '=>',node.next return node.next, balance_info(did_balance=(balance and balance.did_balance) or False,height=1) + elif ( + node.next is None + and (node.left is None or node.right is None) + ): + if node.left is None and node.right is None: + if debug: print "CAT2", node, "=>", None + return None, balance_info() + else: + # On prend le noeud restant + new_node = node.left or node.right + + if len(node.chars)+len(new_node.chars) - 1 < CHARS_PER_NODE: + if debug: print "CAT3", node, new_node, + # On supprime le dernier caractère du noeud + node.chars.pop() + # On ajoute les caractères du nouveau noeud + node.chars.extend(new_node.chars) + # On met le résultat dans le nouveau noeud + new_node.chars = node.chars + if debug: print '=>',new_node + return new_node, self._compute_balance(new_node) + else: + return node, balance else: return node, balance def _new_node(self,string,value,index): new_node = tst_node() # On remplit le segment du noeud avec un maximum de caractères de la clé # en partant de l'index donné length = min(len(string)-index,CHARS_PER_NODE) new_node.chars.extend(string[index:index+length]) if index+length<len(string): # s'il reste des caractères dans la clé après ce segment... new_node.next, discard = self._new_node(string,value,index+length) else: # sinon on met la clé et la donnée dans ce noeud new_node.data = value return new_node, balance_info(height=1) def stats(self,node,acc): if node == None : return acc['nodes'] = acc.get('nodes',0) + 1 acc['total_chars'] = acc.get('total_chars',0) + len(node.chars) key = ('nbchars',len(node.chars)) acc[key] = acc.get(key,0) + 1 links = ((node.left is not None and 1) or 0) + ((node.next is not None and 1) or 0) + ((node.right is not None and 1) or 0) key = ('links',links) acc[key] = acc.get(key,0) + 1 self.stats(node.left,acc) self.stats(node.next,acc) self.stats(node.right,acc) return acc def visit(self,callback,string=None): if string is not None: # Ce code est copié / collé depuis _find_node(). # C'est fait exprès, car cela évite d'avoir instanciation d'un # tuple pour retour de valeur multiple à chaque appel de __getitem__. node = self.root index = 0 while node is not None: local_index = 0 # On avance tant qu'il y a égalité diff = 0 while local_index < len(node.chars) and index < len(string): diff = cmp(string[index],node.chars[local_index]) if diff == 0: local_index += 1 index += 1 else: break if diff != 0: # On a une différence de caractère if local_index < len(node.chars) - 1: # on s'est arrêté avant le dernier caractère du noeud, # il n'y a donc pas de match possible (sinon il y aurait eu # split à l'insertion) node = None break else: # différence au dernier caractère du noeud if diff>0: node = node.left elif diff<0: node = node.right elif local_index == len(node.chars): # On est au bout des caractères du noeud if index == len(string): # On est également au bout de la clé # C'est qu'on a de la chance ! break else: # On avance d'un cran node = node.next else: # On n'est pas au bout des caractères, c'est qu'on est au # bout de la clé, et donc qu'il n'y a pas de match, sinon # il y aurait eu un split assert index == len(string) # On retourne le noeud quand même car il va être utile pour # le visiteur, simplement il n'y a aucune donnée dedans break if node is None: return False else: key = string[:len(string)-local_index] return self._visit(node,array('c',key),callback,local_index<len(node.chars)) else: return self._visit(self.root,array('c'),callback,True) def _visit(self,node,string,callback,visit_left_right): if node is None: return False # D'abord à droite pour obtenir un ordre lexicographique if visit_left_right and self._visit(node.right,string+node.chars[:-1],callback,True): return True # Maintenant le noeud en cours if node.data is not None and callback(string+node.chars,node.data): return True # Puis le noeud suivant if self._visit(node.next,string+node.chars,callback,True): return True # Puis à gauche if visit_left_right and self._visit(node.left,string+node.chars[:-1],callback,True): return True return False def cat(self,node,debug=False): """ Méthode forçant la concaténation des noeuds, inutile sauf en cas de bug. """ if node == None : return node.left = self.cat(node.left,debug) node.next = self.cat(node.next,debug) node.right = self.cat(node.right,debug) node, discard = self._compact_node(node,None,debug) return node def debug(self,node,indentation=0): print node.chars,node.data if node.left is not None: print ' '*(indentation+1),'LEFT', self.debug(node.left,indentation+1) if node.next is not None: print ' '*(indentation+1),'NEXT', self.debug(node.next,indentation+1) if node.right is not None: print ' '*(indentation+1),'RIGHT', self.debug(node.right,indentation+1) if __name__ == '__main__': -# urls = compact_tst() -# -# def callback(key,value): -# assert urls[key] == value, "%s : %s != %s"%(key,urls[key],value) -# print key, value -# return False -# -# n = 0 -# try: -# chars = 0 -# for n, l in enumerate(file('url_1000000.csv','rb')): -# if n == 9999: break -# if n%1000==0 : print n -# key = l.rstrip() -# chars += len(key) -# urls[key] = 0 -# finally: -# stats = {} -# urls.stats(urls.root,stats) -# print n+1, "lignes", chars, "caracteres" -# for key in sorted(stats.keys()): -# print "%16s\t%6i\t%6.2f%%"%( -# key, -# stats[key], -# (key=='total_chars' and 100.0 * stats[key] / chars) or (100.0 * stats[key] / stats['nodes']) -# ) -# -# urls.root = urls.cat(urls.root,True) -# -# # On recalcule les stats après concaténation forcée des noeuds. -# # Si qqchose a changé c'est un bug ! -# stats = {} -# urls.stats(urls.root,stats) -# print n+1, "lignes", chars, "caracteres" -# for key in sorted(stats.keys()): -# print "%16s\t%6i\t%6.2f%%"%( -# key, -# stats[key], -# (key=='total_chars' and 100.0 * stats[key] / chars) or (100.0 * stats[key] / stats['nodes']) -# ) -# -# for n, l in enumerate(file('url_1000000.csv','rb')): -# if n == 9999: break -# if n%1000==0 : print 'Check ',n -# key = l.rstrip() -# assert urls[key] == 0 + urls = compact_tst() + + def callback(key,value): + assert urls[key] == value, "%s : %s != %s"%(key,urls[key],value) + print key, value + return False + + n = 0 + try: + chars = 0 + for n, l in enumerate(file('url_1000000.csv','rb')): + if n == 9999: break + if n%1000==0 : print n + key = l.rstrip() + chars += len(key) + urls[key] = 0 + finally: + stats = {} + urls.stats(urls.root,stats) + print n+1, "lignes", chars, "caracteres" + for key in sorted(stats.keys()): + print "%16s\t%6i\t%6.2f%%"%( + key, + stats[key], + (key=='total_chars' and 100.0 * stats[key] / chars) or (100.0 * stats[key] / stats['nodes']) + ) + + urls.root = urls.cat(urls.root,True) + + # On recalcule les stats après concaténation forcée des noeuds. + # Si qqchose a changé c'est un bug ! + stats = {} + urls.stats(urls.root,stats) + print n+1, "lignes", chars, "caracteres" + for key in sorted(stats.keys()): + print "%16s\t%6i\t%6.2f%%"%( + key, + stats[key], + (key=='total_chars' and 100.0 * stats[key] / chars) or (100.0 * stats[key] / stats['nodes']) + ) + + for n, l in enumerate(file('url_1000000.csv','rb')): + if n == 9999: break + if n%1000==0 : print 'Delete ',n + key = l.rstrip() + if n%2 == 0 : del urls[key] + + urls.root = urls.cat(urls.root,True) + + for n, l in enumerate(file('url_1000000.csv','rb')): + if n == 9999: break + if n%1000==0 : print 'Check ',n + key = l.rstrip() + if n%2==1: + assert urls[key] == 0 + else: + assert urls[key] is None + + # On recalcule les stats après concaténation forcée des noeuds. + # Si qqchose a changé c'est un bug ! + stats = {} + urls.stats(urls.root,stats) + print n+1, "lignes", chars, "caracteres" + for key in sorted(stats.keys()): + print "%16s\t%6i\t%6.2f%%"%( + key, + stats[key], + (key=='total_chars' and 100.0 * stats[key] / chars) or (100.0 * stats[key] / stats['nodes']) + ) t = compact_tst() t['nicolas'] = 'nicolas' t['laurent'] = 'laurent' t['nicolas lehuen'] = 'nicolas lehuen' t['laurent querel'] = 'laurent querel' assert 'nicolas' == t['nicolas'] assert 'nicolas lehuen' == t['nicolas lehuen'] assert 'laurent' == t['laurent'] assert 'laurent querel' == t['laurent querel'] import random t = compact_tst() data = range(1000) - random.Random(654).shuffle(data) + seed = random.randint(-5000000,5000000) + print 'Seed is ',seed + random.Random(seed).shuffle(data) for i, d in enumerate(data): if i%100==0: print i t[str(d)] = d for i2, d2 in enumerate(data[:i]): assert t[str(d2)] == d2 for i, d in enumerate(data): if i%100==0: print i - if i%3==0: del t[str(d)] + if d%3==0: del t[str(d)] t.root = t.cat(t.root,True) for i,d in enumerate(data): - if i%3==0 : + if d%3==0 : assert t[str(d)] == None, "%s => %s != %s"%(d,None,t[str(d)]) else: assert t[str(d)] == d, "%s => %s != %s"%(d,i,t[str(d)])
nlehuen/pytst
88844ad3c27a38862137596951b7705ed29304d1
Mise en place du critère AVL.
diff --git a/python/compacttst.py b/python/compacttst.py index 0e94b97..ea2bb70 100644 --- a/python/compacttst.py +++ b/python/compacttst.py @@ -1,259 +1,407 @@ # -*- coding: iso-8859-1 -*- from array import array import sys # Tant qu'à faire vu qu'ici le nombre de caractères par noeud est complètement # dynamique, on peut se lâcher, mettre 1024 caractère, ce qui revient à une # implémentation de Patricia avec en plus le partage des caractères de préfixe # commun CHARS_PER_NODE = 1024 class tst_node(object): """ classe représentant un noeud du TST """ # __slots__ est une optimisation permettant de créer des objets Python # non dynamiques, ce qui utilise moins de mémoire __slots__ = ['chars','data','next','left','right'] instances = 0 def __init__(self): tst_node.instances += 1 self.chars = array('c') self.data = None self.next = None self.left = None self.right = None def __repr__(self): return "node(%s,data=%s,%i,%i,%i)"%( self.chars, self.data, self.left is not None and 1 or 0, self.next is not None and 1 or 0, self.right is not None and 1 or 0, ) +class balance_info(object): + __slots__ = ['did_balance','height','balance','right_balance','left_balance'] + + def __init__(self,did_balance=False,height=0,balance=0,right_balance=0,left_balance=0): + self.did_balance = did_balance + self.height = height + self.balance = balance + self.right_balance = right_balance + self.left_balance = left_balance + + def __repr__(self): + return "balance_info(d=%s,h=%s,b=%s,l=%s,r=%s)"%( + self.did_balance, + self.height, + self.balance, + self.left_balance, + self.right_balance + ) +7 class compact_tst(object): """ Implémentation d'un TST compact """ def __init__(self): self.root = None def __getitem__(self,string): """ Lit dans l'arbre selon la syntaxe tst[string] """ node = self.root index = 0 while node is not None: local_index = 0 # On avance tant qu'il y a égalité diff = 0 while local_index < len(node.chars) and index < len(string): diff = cmp(string[index],node.chars[local_index]) if diff == 0: local_index += 1 index += 1 else: break if local_index < len(node.chars) - 1: # on s'est arrêté avant le dernier caractère du noeud, # il n'y a donc pas de match possible (sinon il y aurait eu # split à l'insertion) return None elif local_index == len(node.chars) - 1: # différence au dernier caractère du noeud # on va donc aller soit à droite, soit à gauche if diff>0: node = node.left elif diff<0: node = node.right else: node = node.next else: # tous les caractères du noeud correspondent à ceux de la chaîne if index == len(string): # si on est en fin de chaîne, on retourne la donnée stockée # dans le noeud, si elle existe return node.data else: # sinon, on passe au noeud suivant node = node.next # node is None ==> pas de match return None def __setitem__(self,string,value): """ Ecrit dans l'arbre selon la syntaxe tst[string] = value """ - self.root = self._insert(string,value,0,self.root) + self.root, balance = self._insert(string,value,0,self.root) assert self[string] == value def _insert(self,string,value,index,node): if node is None: return self._new_node(string,value,index) local_index = 0 # On avance tant qu'il y a égalité diff = 0 while local_index < len(node.chars) and index<len(string): diff = cmp(string[index],node.chars[local_index]) if diff == 0: local_index += 1 index += 1 else: break if diff!=0: assert local_index < len(node.chars) and index<len(string) # On a trouvé un point de divergence avant le dernier caractère du # noeud, et de la clé, il va donc falloir splitter if local_index < len(node.chars) - 1: - node = self._split_node(node,local_index) - + node, balance = self._split_node(node,local_index) + assert balance.height == self._compute_balance(node).height, "%s != %s"%(balance, self._compute_balance(node)) + # Maintenant que le split est fait, on peut continuer à positionner # la nouvelle clé + balance = balance_info() if diff>0: - node.left = self._insert(string,value,index,node.left) + node.left, left_balance = self._insert(string,value,index,node.left) + assert not (len(node.left.chars)>1 and left_balance.height!=1) + balance.did_balance = left_balance.did_balance + right_balance = self._compute_balance(node.right) else: - node.right = self._insert(string,value,index,node.right) + node.right, right_balance = self._insert(string,value,index,node.right) + assert not (len(node.right.chars)>1 and right_balance.height!=1) + balance.did_balance = right_balance.did_balance + left_balance = self._compute_balance(node.left) + + balance.height = (len(node.chars)>1 and 1) or max(left_balance.height, right_balance.height) + 1 + balance.balance = left_balance.height - right_balance.height + balance.left_balance = left_balance.balance + balance.right_balance = right_balance.balance + + assert balance.height == self._compute_balance(node).height, "%s != %s --- %s, %s"%(balance, self._compute_balance(node), left_balance, right_balance) + + if not balance.did_balance: + node, balance = self._balance(node,balance) - # Puisqu'on vient d'effectuer une opération qui a pu perturber - # l'équilibre du noeud, on le rétablit. Bien sûr cela peut changer - # le noeud devant être retourné à l'appelant. - node = self._balance_node(node) + if len(node.chars)!=1: + balance.height = 1 + balance.balance = 0 + balance.left_balance = 0 + balance.right_balance = 0 - return node + return node, balance elif local_index == len(node.chars): # On est arrivé au bout des caractères du noeud # sans différence if index == len(string): # On est également au bout de la clé # C'est qu'on a de la chance ! node.data = value else: # On n'est pas au bout de la clé - node.next = self._insert(string,value,index,node.next) + node.next, next_balance = self._insert(string,value,index,node.next) - return node + return node, self._compute_balance(node) else: # On est arrivé au bout de la clé, mais pas au bout des caractères # du noeud assert index == len(string) # On est au bout de la clé, mais avant la fin des caractères du # noeud ; il faut donc splitter, mais au local_index précédent car # on a bêtement avancé les deux à la fois aux lignes 105 - 106 - node = self._split_node(node,local_index-1) + node, balance = self._split_node(node,local_index-1) # On stocke ensuite la clé et la valeur node.data = value - return node + return node, balance + + def _compute_balance(self,node): + + if node is not None: + if len(node.chars)>1: + return balance_info(height=1) + else: + balance = balance_info() + + left_balance = self._compute_balance(node.left) + right_balance = self._compute_balance(node.right) + + balance.did_balance = False + balance.height = max(left_balance.height, right_balance.height) + 1 + balance.balance = left_balance.height - right_balance.height + balance.left_balance = left_balance.balance + balance.right_balance = right_balance.balance + + return balance + else: + return balance_info() + + def _balance(self,node,balance): + if balance.balance > 1: + if balance.left_balance > 0: + node, balance = self._ll(node,balance) + else: + node, balance = self._lr(node,balance) + balance.did_balance = True + elif balance.balance < -1: + if balance.right_balance < 0: + node, balance = self._rr(node,balance) + else: + node, balance = self._rl(node,balance) + balance.did_balance = True + + assert -2 < balance.balance < 2, "Noeud non balancé : %s"%balance + assert -2 < self._compute_balance(node).balance < 2, "Noeud non balancé : %s"%self._compute_balance(node) + + return node, balance + + def _ll(self,node,balance): + # Un déséquilibre LL n'est possible qu'avec un noeud de gauche + # n'ayant qu'un caractère + assert len(node.left.chars) == 1 + + # On fait la rotation au niveau des liens + left_node = node.left + node.left = left_node.right + left_node.right = node + + # Et maintenant on ramène tous les caractères du noeud d'origine sauf son + # dernier, et on les insère au début du noeud de gauche. + # En gros si dans le noeud d'origine on a abcdefG + # et dans le noeud de gauche on a juste B + # A la fin on a dans le noeud d'origine juste G + # et dans le noeud de gauche abcdefB + new_char = node.chars.pop() + node.chars.append(left_node.chars.pop()) + left_node.chars.append(new_char) + node.chars, left_node.chars = left_node.chars, node.chars + + # On ajuste la balance en fonction de l'opération effectuée + balance.height -= 1 + balance.balance = 0 + balance.left_balance = 0 + + # Le noeud de gauche prend la place du noeud d'origine dans l'arbre + return left_node, balance + + def _rr(self,node,balance): + assert len(node.right.chars) == 1 + + right_node = node.right + node.right = right_node.left + right_node.left = node + + new_char = node.chars.pop() + node.chars.append(right_node.chars.pop()) + right_node.chars.append(new_char) + node.chars, right_node.chars = right_node.chars, node.chars + + balance.height -= 1 + balance.balance = 0 + balance.right_balance = 0 + + return right_node, balance + + def _lr(self,node,balance): + if len(node.left.right.chars)>1: + node.left.right, right_balance = self._split_node(node.left.right,0) + node.left, left_balance = self._rr(node.left,balance_info()) + node, balance = self._ll(node,balance) + return node, balance + + def _rl(self,node,balance): + if len(node.right.left.chars)>1: + node.right.left, left_balance = self._split_node(node.right.left,0) + node.right, right_balance = self._ll(node.right,balance_info()) + node, balance = self._rr(node,balance) + return node, balance def _split_node(self,node,local_index): assert local_index < len(node.chars) # On crée un nouveau noeud new_node = tst_node() # On prend tout le début du segment de clé du noeud y compris # le caractère qui diffère et on les met dans le nouveau noeud new_node.chars = node.chars[0:local_index + 1] # La suite de ce nouveau noeud est l'ancien noeud new_node.next = node # On adapte la chaîne dans l'ancien noeud, c'est le restant de # la chaîne après le split node.chars = node.chars[local_index + 1:] - return new_node + return new_node, balance_info(height=1) + + def _cat_node(self,node,balance): + if node is None: + return None + elif node.next is not None and node.left is None and node.right is None and node.data is None: + node.chars.extend(node.next.chars) + node.next.chars = node.chars + return node.next, balance_info(height=1) + else: + return node, balance def _new_node(self,string,value,index): new_node = tst_node() # On remplit le segment du noeud avec un maximum de caractères de la clé # en partant de l'index donné length = min(len(string)-index,CHARS_PER_NODE) new_node.chars.extend(string[index:index+length]) if index+length<len(string): # s'il reste des caractères dans la clé après ce segment... new_node.next = self._new_node(string,value,index+length) else: # sinon on met la clé et la donnée dans ce noeud new_node.data = value - return new_node - - def _balance_node(self,node): - # ici vérifier le critère AVL et faire une rotation LL, RR, RL ou LR - # si nécessaire - return node + return new_node, balance_info(height=1) def stats(self,node,acc): if node == None : return acc['nodes'] = acc.get('nodes',0) + 1 key = ('nbchars',len(node.chars)) acc[key] = acc.get(key,0) + 1 links = ((node.left is not None and 1) or 0) + ((node.next is not None and 1) or 0) + ((node.right is not None and 1) or 0) key = ('links',links) acc[keys] = acc.get(key,0) + 1 self.stats(node.left,acc) self.stats(node.next,acc) self.stats(node.right,acc) if __name__ == '__main__': - urls = compact_tst() - try: - chars = 0 - for n, l in enumerate(file('url-list.txt','rb')): - if n%1000==0 : print n - key = l.rstrip() - chars += len(key) - urls[key] = 0 - finally: - stats = {} - urls.stats(urls.root,stats) - print n+1, "lignes", chars, "caracteres" - for key in sorted(stats.keys()): - print "%16s\t%6i\t%6.2f%%"%( - key, - stats[key], - 100.0 * stats[key] / stats['nodes'] - ) +# urls = compact_tst() +# try: +# chars = 0 +# for n, l in enumerate(file('url_1000000.csv','rb')): +# if n%1000==0 : print n +# key = l.rstrip() +# chars += len(key) +# urls[key] = 0 +# finally: +# stats = {} +# urls.stats(urls.root,stats) +# print n+1, "lignes", chars, "caracteres" +# for key in sorted(stats.keys()): +# print "%16s\t%6i\t%6.2f%%"%( +# key, +# stats[key], +# 100.0 * stats[key] / stats['nodes'] +# ) t = compact_tst() t['nicolas'] = 'nicolas' t['laurent'] = 'laurent' t['nicolas lehuen'] = 'nicolas lehuen' t['laurent querel'] = 'laurent querel' assert 'nicolas' == t['nicolas'] assert 'nicolas lehuen' == t['nicolas lehuen'] assert 'laurent' == t['laurent'] assert 'laurent querel' == t['laurent querel'] import random t = compact_tst() data = range(100000) random.shuffle(data) for i, d in enumerate(data): - t[str(d)] = i + print d + t[str(d)] = d +# for i2, d2 in enumerate(data[:i]): +# assert t[str(d2)] == d2 + for i,d in enumerate(data): - assert t[str(d)] == i, "%s => %s != %s"%(d,i,t[str(d)]) + assert t[str(d)] == d, "%s => %s != %s"%(d,i,t[str(d)])
jumanjiman/policy-based-routing
dd4c4570513b2d31f0acff6a316e94f44b89634f
add scenario to deal with public ip space hijacking
diff --git a/ip-space-hijacking/README.asciidoc b/ip-space-hijacking/README.asciidoc new file mode 100644 index 0000000..7d72b62 --- /dev/null +++ b/ip-space-hijacking/README.asciidoc @@ -0,0 +1,103 @@ +== IP number-space hijacking == + +=== Challenge === + +In this scenario, a network hijacked public IP +space for its internal network, but must provide +services via `bond0.450` to customers with real +public IP addresses. + +The trick with policy-based routing is that +responses to any request coming from the real public IP space +must be returned via `bond0.450`. + +.Diagram +---- + hijacked public ip spaces + ^ ^ + | | + ib0 | | ib1 + +--+--+----+ +----------+ + | this | | public | + | machine | | ip space | + +-+------+-+ +-----+----+ + eth0 | | eth1 | + +-+--+-+ | + bond0 | | bond0.450 +----+----+ + | | | | + | +----------------+ router | + | | | + | +---------+ + | + +---+---+ default gateway + |router | with hijacked public ip space + +-------+ +---- + +In the above diagram, the IPs are: + +---- +$ ip -4 addr sho +1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue + inet 127.0.0.1/8 scope host lo +4: ib0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 2044 qdisc pfifo_fast qlen 256 + inet 11.3.252.165/23 brd 11.3.253.255 scope global ib0 +5: ib1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 2044 qdisc pfifo_fast qlen 256 + inet 11.3.254.165/23 brd 11.3.255.255 scope global ib1 +6: bond0: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP> mtu 1500 qdisc noqueue + inet 11.3.20.51/24 brd 11.3.20.255 scope global bond0 +10: bond0.450@bond0: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP> mtu 1500 qdisc noqueue + inet 207.231.196.5/26 brd 207.231.196.63 scope global bond0.450 +---- + +The 'normal' routing table looks like: + +---- +$ ip route +207.231.196.0/26 dev bond0.450 proto kernel scope link src 207.231.196.5 +11.3.20.0/24 dev bond0 proto kernel scope link src 11.3.20.51 +11.3.252.0/23 dev ib0 proto kernel scope link src 11.3.252.165 +11.3.254.0/23 dev ib1 proto kernel scope link src 11.3.254.165 +default via 11.3.20.1 dev bond0 +---- + +=== Solution === + +An IP rule is the basis for the policy: + +---- +$ ip rule show +0: from all lookup 255 +32765: from 207.231.196.5 lookup vlan450 +32766: from all lookup main +32767: from all lookup default +---- + +The new routing table is: + +---- +$ ip route show table vlan450 +207.231.196.0/26 via 207.231.196.5 dev bond0.450 +default via 207.231.196.1 dev bond0.450 +---- + +`/etc/iproute2/rt_tables` contains: + +---- +# +# reserved values +# +255 local +254 main +253 default +0 unspec +# +# local +# +#1 inr.ruhep +50 vlan450 +---- + +NOTE: The platform is Red Hat Enterprise Linux Server release 5.4 (Tikanga) +running kernel `2.6.24.7-139.el5rt`. + diff --git a/ip-space-hijacking/ifcfg-bond0 b/ip-space-hijacking/ifcfg-bond0 new file mode 100644 index 0000000..852d7b6 --- /dev/null +++ b/ip-space-hijacking/ifcfg-bond0 @@ -0,0 +1,7 @@ +BONDING_OPTS="miimon=100 mode=1 primary=eth0" +BOOTPROTO=static +DEVICE=bond0 +# management interface +IPADDR=11.3.20.51 +NETMASK=255.255.255.0 +ONBOOT=yes diff --git a/ip-space-hijacking/ifcfg-bond0.450 b/ip-space-hijacking/ifcfg-bond0.450 new file mode 100644 index 0000000..64b1a97 --- /dev/null +++ b/ip-space-hijacking/ifcfg-bond0.450 @@ -0,0 +1,6 @@ +BOOTPROTO=static +DEVICE=bond0.450 +IPADDR=207.231.196.5 +NETMASK=255.255.255.192 +# tagged vlan +VLAN=yes diff --git a/ip-space-hijacking/ifcfg-eth0 b/ip-space-hijacking/ifcfg-eth0 new file mode 100644 index 0000000..87af622 --- /dev/null +++ b/ip-space-hijacking/ifcfg-eth0 @@ -0,0 +1,6 @@ +BOOTPROTO=static +DEVICE=eth0 +HWADDR=00:26:55:22:F0:A8 +MASTER=bond0 +ONBOOT=yes +SLAVE=yes diff --git a/ip-space-hijacking/ifcfg-eth1 b/ip-space-hijacking/ifcfg-eth1 new file mode 100644 index 0000000..39fa64d --- /dev/null +++ b/ip-space-hijacking/ifcfg-eth1 @@ -0,0 +1,6 @@ +BOOTPROTO=static +DEVICE=eth1 +HWADDR=00:26:55:22:F0:AC +MASTER=bond0 +ONBOOT=yes +SLAVE=yes diff --git a/ip-space-hijacking/ifcfg-ib0 b/ip-space-hijacking/ifcfg-ib0 new file mode 100644 index 0000000..1ca68fb --- /dev/null +++ b/ip-space-hijacking/ifcfg-ib0 @@ -0,0 +1,6 @@ +BOOTPROTO=static +DEVICE=ib0 +IPADDR=11.3.252.165 +NETMASK=255.255.254.0 +ONBOOT=yes +TYPE=Infiniband diff --git a/ip-space-hijacking/ifcfg-ib1 b/ip-space-hijacking/ifcfg-ib1 new file mode 100644 index 0000000..29509e7 --- /dev/null +++ b/ip-space-hijacking/ifcfg-ib1 @@ -0,0 +1,6 @@ +BOOTPROTO=static +DEVICE=ib1 +IPADDR=11.3.254.165 +NETMASK=255.255.254.0 +ONBOOT=yes +TYPE=Infiniband diff --git a/ip-space-hijacking/route-bond0.450 b/ip-space-hijacking/route-bond0.450 new file mode 100644 index 0000000..10a7af6 --- /dev/null +++ b/ip-space-hijacking/route-bond0.450 @@ -0,0 +1,2 @@ +default via 207.231.196.1 table 50 +207.231.196.0/26 via 207.231.196.5 table 50 diff --git a/ip-space-hijacking/rt_tables b/ip-space-hijacking/rt_tables new file mode 100644 index 0000000..5a4fe09 --- /dev/null +++ b/ip-space-hijacking/rt_tables @@ -0,0 +1,12 @@ +# +# reserved values +# +255 local +254 main +253 default +0 unspec +# +# local +# +#1 inr.ruhep +50 vlan450 diff --git a/ip-space-hijacking/rule-bond0.450 b/ip-space-hijacking/rule-bond0.450 new file mode 100644 index 0000000..f95938a --- /dev/null +++ b/ip-space-hijacking/rule-bond0.450 @@ -0,0 +1 @@ +from 207.231.196.5 table 50
jumanjiman/policy-based-routing
18f8e06fecc4fe51f9ae00597ef16d25e58eb9ef
disclaimer
diff --git a/README.asciidoc b/README.asciidoc index 8d07749..f7f6291 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -1,169 +1,171 @@ == Policy-Based Routing in Linux == === Goals === These examples use advanced routing techniques to solve real-world routing challenges in Linux. Each scenario is in a separate directory with a README. RHEL supports `rule-$dev` files in `/etc/sysconfig/network-scripts`, but these examples use `/sbin/ifup-local` to do various loops. === Troubleshooting routes === . To get the route to an IP, use `ip route get` + ---- /sbin/ip route get 1.2.3.4 ---- + The above command may show output similar to: + ---- 1.2.3.4 via 10.0.1.1 dev wlan0 src 10.0.1.202 cache mtu 1500 advmss 1460 hoplimit 64 ---- + The output shows the next hop (`10.0.1.1`), the outbound interface (`wlan0`), and the default source IP for packets (`10.0.1.202`). . If you see something you don't expect, try these other commands: + * `ip rule show` * `ip route show table all` * `ip address show <device>` * `ip link show` * `ip link show up` * `ip help` TIP: Avoid the `ifconfig` command since it works only on labelled interfaces. TIP: Avoid the `route` command. === Additional resources === ==== System docs ==== Policy routing is documented in `/usr/share/doc/iproute-*`, but you'll have to make pdf's from the ps files. ---- cd /usr/share/doc/iproute-* for file in $(ls *.ps); do ps2pdf $file done ---- ==== Third-party docs ==== A really good tutorial is available as a free (as in beer) download at http://www.policyrouting.org/PolicyRoutingBook[] === Rules without routes === This is a quick example of using rules 'without' an extra routing table. Technically it's not policy-based routing, but it's based on similar principles. Suppose you want to block access to Facebook and don't want to use NetFilter or other mechanisms. . Find the current IP addresses + ---- $ dig +short facebook.com 69.63.189.16 69.63.181.11 69.63.181.12 69.63.189.11 ---- . Find the netmask + ---- $ ipcalc -m 69.63.189.16 NETMASK=255.0.0.0 ---- . Add a rule on-the-fly + ---- $ sudo /sbin/ip rule add to 69.0.0.0/8 unreachable ---- ++ +NOTE: Yes, this is sloppy and excludes other hosts. . Test that it's effective + ---- $ ping facebook.com connect: Network is unreachable ---- If faced with that scenario, how would you troubleshoot? . Show the normal routing table(s) + ---- $ /sbin/ip route show 209.132.183.53 via 172.21.13.1 dev eth0 proto static 172.21.13.0/24 dev eth0 proto kernel scope link src 172.21.13.20 metric 1 192.168.122.0/24 dev virbr0 proto kernel scope link src 192.168.122.1 10.3.224.0/20 dev tun0 proto kernel scope link src 10.3.225.96 172.16.0.0/16 dev tun0 proto static scope link 10.0.0.0/8 dev tun0 proto static scope link default via 172.21.13.1 dev eth0 proto static ---- . But I have a default gateway! WTF?! .. Ah, but bring out the real net-foo: + ---- $ /sbin/ip route get 69.63.189.16 RTNETLINK answers: Network is unreachable ---- .. Show the rules + ---- $ /sbin/ip rule show 0: from all lookup local 32765: from all to 69.0.0.0/8 unreachable 32766: from all lookup main 32767: from all lookup default ---- + NOTE: New rules are added *before* the existing main and default tables. You can even persist these in RHEL: ---- $ cd /etc/sysconfig/network-scripts/ $ grep -i 'ip rule' * ifdown-routes: /sbin/ip rule del $line ifup-routes: /sbin/ip rule add $line ---- Closer inspection of those two scripts reveals that you can create `rule-<ifname>` files. The relevant line from `ifup-routes` is: ---- FILES="/etc/sysconfig/network-scripts/rule-$1" ---- In a real-world scenario, you'd probably want to use the `ip` command to create a table, then rules to direct various combos of source and destination into that table to annoy your users... scratch that...protect your assets. Now, if you want to get fancy...you can combine FWMARK with ip rules to target specific source and destination combinations. IP rules will also get you out of a jam in those scenarios where a facility is using the same IP subnet that you use for your private backend network.
jumanjiman/policy-based-routing
d8738526052d37dfb409609f7a2d8671f2fbd841
quick tutorial steps
diff --git a/README.asciidoc b/README.asciidoc index 53a368e..8d07749 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -1,66 +1,169 @@ == Policy-Based Routing in Linux == === Goals === These examples use advanced routing techniques to solve real-world routing challenges in Linux. Each scenario is in a separate directory with a README. RHEL supports `rule-$dev` files in `/etc/sysconfig/network-scripts`, but these examples use `/sbin/ifup-local` to do various loops. === Troubleshooting routes === . To get the route to an IP, use `ip route get` + ---- /sbin/ip route get 1.2.3.4 ---- + The above command may show output similar to: + ---- 1.2.3.4 via 10.0.1.1 dev wlan0 src 10.0.1.202 cache mtu 1500 advmss 1460 hoplimit 64 ---- + The output shows the next hop (`10.0.1.1`), the outbound interface (`wlan0`), and the default source IP for packets (`10.0.1.202`). . If you see something you don't expect, try these other commands: + * `ip rule show` * `ip route show table all` * `ip address show <device>` * `ip link show` * `ip link show up` * `ip help` TIP: Avoid the `ifconfig` command since it works only on labelled interfaces. TIP: Avoid the `route` command. === Additional resources === ==== System docs ==== Policy routing is documented in `/usr/share/doc/iproute-*`, but you'll have to make pdf's from the ps files. ---- cd /usr/share/doc/iproute-* for file in $(ls *.ps); do ps2pdf $file done ---- ==== Third-party docs ==== -A really good reference is available +A really good tutorial is available as a free (as in beer) download at http://www.policyrouting.org/PolicyRoutingBook[] +=== Rules without routes === + +This is a quick example of using rules 'without' +an extra routing table. Technically it's not +policy-based routing, but it's based on similar principles. + +Suppose you want to block access to Facebook +and don't want to use NetFilter or other mechanisms. + +. Find the current IP addresses ++ +---- +$ dig +short facebook.com +69.63.189.16 +69.63.181.11 +69.63.181.12 +69.63.189.11 +---- + +. Find the netmask ++ +---- +$ ipcalc -m 69.63.189.16 +NETMASK=255.0.0.0 +---- + +. Add a rule on-the-fly ++ +---- +$ sudo /sbin/ip rule add to 69.0.0.0/8 unreachable +---- + +. Test that it's effective ++ +---- +$ ping facebook.com +connect: Network is unreachable +---- + + +If faced with that scenario, how would you troubleshoot? + +. Show the normal routing table(s) ++ +---- +$ /sbin/ip route show +209.132.183.53 via 172.21.13.1 dev eth0 proto static +172.21.13.0/24 dev eth0 proto kernel scope link src 172.21.13.20 +metric 1 +192.168.122.0/24 dev virbr0 proto kernel scope link src 192.168.122.1 +10.3.224.0/20 dev tun0 proto kernel scope link src 10.3.225.96 +172.16.0.0/16 dev tun0 proto static scope link +10.0.0.0/8 dev tun0 proto static scope link +default via 172.21.13.1 dev eth0 proto static +---- + +. But I have a default gateway! WTF?! +.. Ah, but bring out the real net-foo: ++ +---- +$ /sbin/ip route get 69.63.189.16 +RTNETLINK answers: Network is unreachable +---- + +.. Show the rules ++ +---- +$ /sbin/ip rule show +0: from all lookup local +32765: from all to 69.0.0.0/8 unreachable +32766: from all lookup main +32767: from all lookup default +---- ++ +NOTE: New rules are added *before* the existing main and default +tables. + +You can even persist these in RHEL: + +---- +$ cd /etc/sysconfig/network-scripts/ +$ grep -i 'ip rule' * +ifdown-routes: /sbin/ip rule del $line +ifup-routes: /sbin/ip rule add $line +---- + +Closer inspection of those two scripts reveals that you can +create `rule-<ifname>` files. The relevant line from `ifup-routes` is: + +---- +FILES="/etc/sysconfig/network-scripts/rule-$1" +---- + +In a real-world scenario, you'd probably want to use the `ip` command +to create a table, then rules to direct various combos of +source and destination into that table to annoy your users... +scratch that...protect your assets. + +Now, if you want to get fancy...you can combine FWMARK with ip rules +to target specific source and destination combinations. IP rules will +also get you out of a jam in those scenarios where a facility +is using the same IP subnet that you use for your private backend network. +
jumanjiman/policy-based-routing
cdbd0d34085eb2f52fbf8cf69d679d16d7207f4d
tips and references
diff --git a/README.asciidoc b/README.asciidoc index e17f860..53a368e 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -1,9 +1,66 @@ == Policy-Based Routing in Linux == +=== Goals === + These examples use advanced routing techniques to solve real-world routing challenges in Linux. Each scenario is in a separate directory with a README. RHEL supports `rule-$dev` files in `/etc/sysconfig/network-scripts`, but these examples use `/sbin/ifup-local` to do various loops. + +=== Troubleshooting routes === + +. To get the route to an IP, use `ip route get` ++ +---- +/sbin/ip route get 1.2.3.4 +---- ++ +The above command may show output similar to: ++ +---- +1.2.3.4 via 10.0.1.1 dev wlan0 src 10.0.1.202 + cache mtu 1500 advmss 1460 hoplimit 64 +---- ++ +The output shows the next hop (`10.0.1.1`), the +outbound interface (`wlan0`), and the default source IP +for packets (`10.0.1.202`). + +. If you see something you don't expect, +try these other commands: ++ +* `ip rule show` +* `ip route show table all` +* `ip address show <device>` +* `ip link show` +* `ip link show up` +* `ip help` + +TIP: Avoid the `ifconfig` command since it works only +on labelled interfaces. + +TIP: Avoid the `route` command. + +=== Additional resources === + +==== System docs ==== + +Policy routing is documented in `/usr/share/doc/iproute-*`, but you'll +have to make pdf's from the ps files. + +---- +cd /usr/share/doc/iproute-* +for file in $(ls *.ps); do + ps2pdf $file +done +---- + +==== Third-party docs ==== + +A really good reference is available +as a free (as in beer) download at +http://www.policyrouting.org/PolicyRoutingBook[] +
jumanjiman/policy-based-routing
7757b1f96c4567dfb05728da3d7470f74a5861c9
github does not allow includes in asciidoc
diff --git a/ntp-special/README.asciidoc b/ntp-special/README.asciidoc index 1fc2fe5..2112a07 100644 --- a/ntp-special/README.asciidoc +++ b/ntp-special/README.asciidoc @@ -1,32 +1,20 @@ == Special NTP Route == For whatever reason, a host needs a special route to reach its upstream NTP server. Perhaps this conflicts with the 'normal' routing tables on the host. .Procedure -. Create `/etc/iproute2/rt_tables` as: -+ ----- -include::rt_tables[] ----- +. Create `/etc/iproute2/rt_tables` as shown in the attached file -. Create `/etc/sysconfig/network-scripts/route-eth1` as: -+ ----- -include::route-eth1[] ----- +. Create `/etc/sysconfig/network-scripts/route-eth1` as in the attached file -. Create `/etc/sysconfig/network-scripts/rule-eth1` as: -+ ----- -include::rule-eth1[] ----- +. Create `/etc/sysconfig/network-scripts/rule-eth1` as in the attached file . Bounce `eth1` + ---- ifdown eth1; ifup eth1 ----
jumanjiman/policy-based-routing
8a2bc6801b8b974a1357711e0acf76f338fad8d9
new scenario
diff --git a/ntp-special/README.asciidoc b/ntp-special/README.asciidoc new file mode 100644 index 0000000..1fc2fe5 --- /dev/null +++ b/ntp-special/README.asciidoc @@ -0,0 +1,32 @@ + +== Special NTP Route == + +For whatever reason, a host needs a special route +to reach its upstream NTP server. Perhaps this conflicts +with the 'normal' routing tables on the host. + +.Procedure + +. Create `/etc/iproute2/rt_tables` as: ++ +---- +include::rt_tables[] +---- + +. Create `/etc/sysconfig/network-scripts/route-eth1` as: ++ +---- +include::route-eth1[] +---- + +. Create `/etc/sysconfig/network-scripts/rule-eth1` as: ++ +---- +include::rule-eth1[] +---- + +. Bounce `eth1` ++ +---- +ifdown eth1; ifup eth1 +---- diff --git a/ntp-special/route-eth1 b/ntp-special/route-eth1 new file mode 100644 index 0000000..58a1822 --- /dev/null +++ b/ntp-special/route-eth1 @@ -0,0 +1,2 @@ +10.2.89.0/24 dev eth1 src 10.2.89.81 table ntp +default via 10.2.89.1 dev eth1 table ntp diff --git a/ntp-special/rt_tables b/ntp-special/rt_tables new file mode 100644 index 0000000..a772eee --- /dev/null +++ b/ntp-special/rt_tables @@ -0,0 +1,12 @@ +# +# reserved values +# +255 local +254 main +253 default +0 unspec +# +# local +# +#1 inr.ruhep +1 ntp diff --git a/ntp-special/rule-eth1 b/ntp-special/rule-eth1 new file mode 100644 index 0000000..5f36ac0 --- /dev/null +++ b/ntp-special/rule-eth1 @@ -0,0 +1,2 @@ +from 10.2.89.81/32 table ntp +to 10.2.89.81/32 table ntp
jumanjiman/policy-based-routing
c03002f2ca3c2af91f6d5ba81a383262558fda7d
changed READMEs to asciidoc format for github viewing
diff --git a/frontend-same-as-backend/README b/frontend-same-as-backend/README deleted file mode 100755 index 1896da5..0000000 --- a/frontend-same-as-backend/README +++ /dev/null @@ -1,29 +0,0 @@ -scenario -Ensure that all traffic coming in on INTERNAL interface -is answered on INTERNAL interface. This is needed for -facilities where the eth1 interface subnet -conflicts with the backend subnets. - - 10.100.x.y/16 (frontend subnet) - | - | eth1 - +-----+----+ - | this | - | machine | - +-----+----+ - | eth0 (INTERNAL) - | - 192.168.0.0/24 - | - +-----------+ - | | - +---+---+ +---+---+ - | | | | - +---+---+ +---+---+ - | | - 10.100.1.0/24 10.100.2.0/24 (backend subnets) - | | - +---+---+ +---+---+ - | | | | - +-------+ +-------+ - diff --git a/frontend-same-as-backend/README.asciidoc b/frontend-same-as-backend/README.asciidoc new file mode 100755 index 0000000..97776d5 --- /dev/null +++ b/frontend-same-as-backend/README.asciidoc @@ -0,0 +1,35 @@ +== Scenario == + +Ensure that all traffic coming in on 'INTERNAL' interface +is answered on 'INTERNAL' interface. This is needed for +facilities where the `eth1` interface subnet +conflicts with the backend subnets. + +---- + + 10.100.x.y/16 (frontend subnet) + | + | eth1 + +-----+----+ + | this | + | machine | + +-----+----+ + | eth0 (INTERNAL) + | + 192.168.0.0/24 + | + +-----------+ + | | + +---+---+ +---+---+ internal + | | | | workstations + +---+---+ +---+---+ + | | + 10.100.1.0/24 10.100.2.0/24 (backend subnets) + | | + +---+---+ +---+---+ + | | | | + +-------+ +-------+ + + backend workstations + +---- diff --git a/same-subnet-eth0-eth1/README b/same-subnet-eth0-eth1/README deleted file mode 100644 index a546335..0000000 --- a/same-subnet-eth0-eth1/README +++ /dev/null @@ -1,26 +0,0 @@ -This scenario assumes that 192.168.0.0/24 is on -both eth0 and eth1. - - - Internet - +-----+----+ - | router | - +-----+----+ - | 192.168.0.1/24 - | - 192.168.0.0/24 - | - | eth1=192.168.0.2/24 - +-----+----+ - | this | - | machine | - +-----+----+ - | eth0 (INTERNAL) = 192.168.0.254 - | - 192.168.0.0/24 - | - +-----------+ - | | - +---+---+ +---+---+ - | | | | - +-------+ +-------+ diff --git a/same-subnet-eth0-eth1/README.asciidoc b/same-subnet-eth0-eth1/README.asciidoc new file mode 100644 index 0000000..5b7d006 --- /dev/null +++ b/same-subnet-eth0-eth1/README.asciidoc @@ -0,0 +1,31 @@ +== Same subnet on `eth0` and `eth1` == + +This scenario assumes that 192.168.0.0/24 is on +both eth0 and eth1. + +---- + + Internet + +-----+----+ + | router | + +-----+----+ + | 192.168.0.1/24 + | + 192.168.0.0/24 + | + | eth1=192.168.0.2/24 + +-----+----+ + | this | + | machine | + +-----+----+ + | eth0 (INTERNAL) = 192.168.0.254 + | + 192.168.0.0/24 + | + +-----------+ + | | + +---+---+ +---+---+ + | | | | + +-------+ +-------+ + +---- diff --git a/tunnel-routing/README b/tunnel-routing/README.asciidoc similarity index 83% rename from tunnel-routing/README rename to tunnel-routing/README.asciidoc index 3dacb80..775da2e 100644 --- a/tunnel-routing/README +++ b/tunnel-routing/README.asciidoc @@ -1,86 +1,94 @@ -scenario: -This machine runs a vpn client (such as openvpn) to +== Scenario == + +This machine runs a vpn client (such as `openvpn`) to establish a connection to a remote network on 172.16.0.0/16, but the Internet-facing interface on this machine is on 172.16.0.0/x. Local workstations need to route through this machine to reach tunnel network. +.Diagram +---- + 172.16.0.0/16 (tunnel network) | +-----+----+ | vpn | +-----+----+ | REMOTE_OUTER=10.8.1.42 +--------+ | | Internet | +-----+----+ | | router | | +-----+----+ | | | 172.16.0.0/16 (frontend subnet) | | +-----+ | tun0 | | eth1 +--+--+----+ | this | | machine | +-----+----+ | eth0 (INTERNAL) | 192.168.0.0/24 | +-----------+ | | +---+---+ +---+---+ | | | | local workstations +-------+ +-------+ +---- To work around this, do something like: ----------------------------------------------------------- -1. assign a name to routing table 36 - - echo -e '36\tremote' >> /etc/iproute2/rt_tables - ----------------------------------------------------------- -2. Create /sbin/ifup-local and chmod 755: +. assign a name to routing table `36` ++ +---- +echo -e '36\tremote' >> /etc/iproute2/rt_tables +---- +. Create `/sbin/ifup-local` and `chmod 755` ++ +---- #!/bin/bash # facility gateway, outbound on eth1 FACILITY_GW=172.16.0.1 FACILITY_GW="$(ip ro sho table main | grep default | cut -d\ -f3)" # cert-specific gateway for openvpn SERVER_GW="$(ip addr show tun0 | grep -oh 'peer\ [0-9.]\+' | cut -d\ -f2)" if [ $1 == tun0 ]; then ip route add default via $SERVER_GW dev tun0 table remote ip rule add to $FACILITY_GW table main ip rule add to 172.16.0.0/16 table remote WARNING="Cluster $FACILITY_GW will be unavailable" echo "ADDED policy-based routing per /sbin/ifup-local" >&2 echo $WARNING >&2 /usr/bin/logger -t ifup-local $WARNING fi +---- ----------------------------------------------------------- -3. Create /sbin/ifdown-local and chmod 755: - +. Create `/sbin/ifdown-local` and `chmod 755` ++ +---- #!/bin/bash # facility gateway, outbound on eth1 FACILITY_GW=172.16.0.1 FACILITY_GW="$(ip ro sho table main | grep default | cut -d\ -f3)" # cert-specific gateway for openvpn SERVER_GW="$(ip addr show tun0 | grep -oh 'peer\ [0-9.]\+' | cut -d\ -f2)" if [ $1 == tun0 ]; then ip rule delete to $FACILITY_GW table main ip rule delete to 172.16.0.0/16 table remote ip route del default via $SERVER_GW dev tun0 table remote echo "REMOVED policy-based routing per /sbin/ifdown-local" >&2 fi +----
jumanjiman/policy-based-routing
c01b70992d1aba01616272155fb2a2e8a589006b
better ascii art
diff --git a/frontend-same-as-backend/README b/frontend-same-as-backend/README index 20738b3..1896da5 100755 --- a/frontend-same-as-backend/README +++ b/frontend-same-as-backend/README @@ -1,25 +1,29 @@ scenario Ensure that all traffic coming in on INTERNAL interface is answered on INTERNAL interface. This is needed for facilities where the eth1 interface subnet conflicts with the backend subnets. 10.100.x.y/16 (frontend subnet) | | eth1 +-----+----+ | this | | machine | +-----+----+ | eth0 (INTERNAL) | 192.168.0.0/24 | +-----------+ | | +---+---+ +---+---+ | | | | +---+---+ +---+---+ | | 10.100.1.0/24 10.100.2.0/24 (backend subnets) + | | + +---+---+ +---+---+ + | | | | + +-------+ +-------+
jumanjiman/policy-based-routing
6829a422135a7f161521b9c56081cea44ed32a14
initial import
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b72f9be --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*~ +*.swp diff --git a/README.asciidoc b/README.asciidoc new file mode 100644 index 0000000..e17f860 --- /dev/null +++ b/README.asciidoc @@ -0,0 +1,9 @@ +== Policy-Based Routing in Linux == + +These examples use advanced routing techniques +to solve real-world routing challenges in Linux. +Each scenario is in a separate directory with a README. + +RHEL supports `rule-$dev` files in +`/etc/sysconfig/network-scripts`, but these examples +use `/sbin/ifup-local` to do various loops. diff --git a/frontend-same-as-backend/README b/frontend-same-as-backend/README new file mode 100755 index 0000000..20738b3 --- /dev/null +++ b/frontend-same-as-backend/README @@ -0,0 +1,25 @@ +scenario +Ensure that all traffic coming in on INTERNAL interface +is answered on INTERNAL interface. This is needed for +facilities where the eth1 interface subnet +conflicts with the backend subnets. + + 10.100.x.y/16 (frontend subnet) + | + | eth1 + +-----+----+ + | this | + | machine | + +-----+----+ + | eth0 (INTERNAL) + | + 192.168.0.0/24 + | + +-----------+ + | | + +---+---+ +---+---+ + | | | | + +---+---+ +---+---+ + | | + 10.100.1.0/24 10.100.2.0/24 (backend subnets) + diff --git a/frontend-same-as-backend/ifdown-local b/frontend-same-as-backend/ifdown-local new file mode 100755 index 0000000..1aa926e --- /dev/null +++ b/frontend-same-as-backend/ifdown-local @@ -0,0 +1,22 @@ +#!/bin/sh + +INTERNAL=eth0 + +# see ifup-local for explanation and ascii art + +if [ "$1" = $INTERNAL ]; then + # eth0 is $INTERNAL interface + + # Flush $INTERNAL routing table (see /etc/iproute2/rt_tables) + ip route flush table 200 + + # Remove policy rules + for x in $(seq 1 20); do + SUBNET="10.100.$x.0/24" + ip rule del from 192.168.0.254 to $SUBNET table 200 + done + + logger -t "/sbin/ifdown-local" \ + "Removed policy-based routing rules for $INTERNAL + +fi diff --git a/frontend-same-as-backend/ifup-local b/frontend-same-as-backend/ifup-local new file mode 100755 index 0000000..ffbcc2f --- /dev/null +++ b/frontend-same-as-backend/ifup-local @@ -0,0 +1,84 @@ +#!/bin/sh + +INTERNAL=eth0 + +if [ "$1" = $INTERNAL ]; then + # scenario + # Ensure that all traffic coming in on INTERNAL interface + # is answered on INTERNAL interface. This is needed for + # facilities where the eth1 interface subnet + # conflicts with the backend subnets. + # + # 10.100.x.y/16 (frontend subnet) + # | + # | eth1 + # +-----+----+ + # | this | + # | machine | + # +-----+----+ + # | eth0 (INTERNAL) + # | + # 192.168.0.0/24 + # | + # +-----------+ + # | | + # +---+---+ +---+---+ + # | | | | + # +---+---+ +---+---+ + # | | + # 10.100.1.0/24 10.100.2.0/24 (backend subnets) + # + + if ! $(grep -qs "200 INTERNAL" /etc/iproute2/rt_tables); then + # create a persistent routing table called INTERNAL + echo "updating /etc/iproute2/rt_tables" >&2 + echo "200 INTERNAL" >> /etc/iproute2/rt_tables + fi + + # Build a route to the gateway for each backend subnet + # and assign them to the INTERNAL table + for x in $(seq 1 20); do + SUBNET="10.100.$x.0/24" + ROUTER="192.168.0.$x" + ip route add $SUBNET via $ROUTER dev eth0 src 192.168.0.254 table 200 protocol static + + # Tell the kernel that + # outgoing traffic _from_ 192.168.0.254 to the backend subnet + # should use the INTERNAL routing table + # This allows the server to have the subnets accessible + # from both the front-end (eth1) and the backend (eth0) + RULE="from 192.168.0.254 to $SUBNET table 200" + ip rule show | grep -q "$RULE" + if [ $? -eq 0 ]; then + # rule was already there (but should not have been...see /sbin/ifdown-local) + { + echo "Rule was already present. This means you upped $INTERNAL twice " + echo "without bringing it down in between. Check the rule for correctness:" + echo " $RULE" + echo + echo "See /sbin/ifup-local and /sbin/ifdown-local" + } >&2 + else + ip rule add $RULE + fi + done + + { + # alert admin that policy-based routing is in place + echo "To see your backend routes, run:" + echo " ip route show table 200" + echo + echo "To see your rules, run:" + echo " ip rule show" + } >&2 + + logger -t "/sbin/ifup-local: " \ + "Added policy-based routing rules for INTERNAL" +fi + +# add a default route to INTERNAL table +DEFROUTE="$(ip route show | grep default)" +if ! [ "x$DEFROUTE" = "x" ]; then + ip route show table 200 | grep -q "$DEFROUTE" + [ $? -eq 0 ] || ip route add $DEFROUTE table 200 +fi diff --git a/same-subnet-eth0-eth1/README b/same-subnet-eth0-eth1/README new file mode 100644 index 0000000..a546335 --- /dev/null +++ b/same-subnet-eth0-eth1/README @@ -0,0 +1,26 @@ +This scenario assumes that 192.168.0.0/24 is on +both eth0 and eth1. + + + Internet + +-----+----+ + | router | + +-----+----+ + | 192.168.0.1/24 + | + 192.168.0.0/24 + | + | eth1=192.168.0.2/24 + +-----+----+ + | this | + | machine | + +-----+----+ + | eth0 (INTERNAL) = 192.168.0.254 + | + 192.168.0.0/24 + | + +-----------+ + | | + +---+---+ +---+---+ + | | | | + +-------+ +-------+ diff --git a/same-subnet-eth0-eth1/ifdown-local b/same-subnet-eth0-eth1/ifdown-local new file mode 100644 index 0000000..f8d2efc --- /dev/null +++ b/same-subnet-eth0-eth1/ifdown-local @@ -0,0 +1,6 @@ +#!/bin/bash + +/sbin/ip rule delete to 192.168.0.1 table 101 +for x in $(seq 3 20); do + /sbin/ip rule delete to 192.168.0.$x table 100 +done diff --git a/same-subnet-eth0-eth1/ifup-local b/same-subnet-eth0-eth1/ifup-local new file mode 100644 index 0000000..7bab360 --- /dev/null +++ b/same-subnet-eth0-eth1/ifup-local @@ -0,0 +1,13 @@ +#!/bin/bash + +# this should be saved as /sbin/ifup-local with mode 755 + +# add route for internal interface +/sbin/ip route add table 100 scope link dev eth0 +for x in $(seq 3 20); do + /sbin/ip rule add to 192.168.0.$x table 100 +done + +# add route for external interface +/sbin/ip route add table 101 scope link dev eth1 +/sbin/ip rule add to 192.168.0.1 table 101 diff --git a/tunnel-routing/README b/tunnel-routing/README new file mode 100644 index 0000000..3dacb80 --- /dev/null +++ b/tunnel-routing/README @@ -0,0 +1,86 @@ +scenario: +This machine runs a vpn client (such as openvpn) to +establish a connection to a remote network on 172.16.0.0/16, +but the Internet-facing interface on this machine +is on 172.16.0.0/x. Local workstations need +to route through this machine to reach tunnel network. + + 172.16.0.0/16 (tunnel network) + | + +-----+----+ + | vpn | + +-----+----+ + | REMOTE_OUTER=10.8.1.42 + +--------+ + | + | Internet + | +-----+----+ + | | router | + | +-----+----+ + | | + | 172.16.0.0/16 (frontend subnet) + | | + +-----+ | + tun0 | | eth1 + +--+--+----+ + | this | + | machine | + +-----+----+ + | eth0 (INTERNAL) + | + 192.168.0.0/24 + | + +-----------+ + | | + +---+---+ +---+---+ + | | | | local workstations + +-------+ +-------+ + + +To work around this, do something like: + +---------------------------------------------------------- +1. assign a name to routing table 36 + + echo -e '36\tremote' >> /etc/iproute2/rt_tables + +---------------------------------------------------------- +2. Create /sbin/ifup-local and chmod 755: + +#!/bin/bash + +# facility gateway, outbound on eth1 +FACILITY_GW=172.16.0.1 +FACILITY_GW="$(ip ro sho table main | grep default | cut -d\ -f3)" + +# cert-specific gateway for openvpn +SERVER_GW="$(ip addr show tun0 | grep -oh 'peer\ [0-9.]\+' | cut -d\ -f2)" + +if [ $1 == tun0 ]; then + ip route add default via $SERVER_GW dev tun0 table remote + ip rule add to $FACILITY_GW table main + ip rule add to 172.16.0.0/16 table remote + WARNING="Cluster $FACILITY_GW will be unavailable" + echo "ADDED policy-based routing per /sbin/ifup-local" >&2 + echo $WARNING >&2 + /usr/bin/logger -t ifup-local $WARNING +fi + +---------------------------------------------------------- +3. Create /sbin/ifdown-local and chmod 755: + +#!/bin/bash + +# facility gateway, outbound on eth1 +FACILITY_GW=172.16.0.1 +FACILITY_GW="$(ip ro sho table main | grep default | cut -d\ -f3)" + +# cert-specific gateway for openvpn +SERVER_GW="$(ip addr show tun0 | grep -oh 'peer\ [0-9.]\+' | cut -d\ -f2)" + +if [ $1 == tun0 ]; then + ip rule delete to $FACILITY_GW table main + ip rule delete to 172.16.0.0/16 table remote + ip route del default via $SERVER_GW dev tun0 table remote + echo "REMOVED policy-based routing per /sbin/ifdown-local" >&2 +fi diff --git a/tunnel-routing/ifdown-local b/tunnel-routing/ifdown-local new file mode 100755 index 0000000..0f26170 --- /dev/null +++ b/tunnel-routing/ifdown-local @@ -0,0 +1,11 @@ +#!/bin/bash + +# external IP of remote vpn device +REMOTE_OUTER=10.8.1.42 + +if [ $1 == tun0 ]; then + ip rule delete to 172.16.0.1 table main + ip rule delete to 172.16.0.0/16 table remote + ip route del default via $REMOTE_OUTER dev tun0 table remote + echo "REMOVED policy-based routing per /sbin/ifdown-local" >&2 +fi diff --git a/tunnel-routing/ifup-local b/tunnel-routing/ifup-local new file mode 100755 index 0000000..574ddd7 --- /dev/null +++ b/tunnel-routing/ifup-local @@ -0,0 +1,11 @@ +#!/bin/bash + +# the outer interface of remote tunnel endpoint +REMOTE_OUTER=10.8.1.42 + +if [ $1 == tun0 ]; then + ip route add default via $REMOTE_OUTER dev tun0 table remote + ip rule add to 172.16.0.1 table main + ip rule add to 172.16.0.0/16 table remote + echo "ADDED policy-based routing per /sbin/ifup-local" >&2 +fi diff --git a/tunnel-routing/rt_tables b/tunnel-routing/rt_tables new file mode 100644 index 0000000..cf3c39b --- /dev/null +++ b/tunnel-routing/rt_tables @@ -0,0 +1,12 @@ +# +# reserved values +# +255 local +254 main +253 default +0 unspec +# +# local +# +#1 inr.ruhep +99 clusters
jjpp/plamk
c3189963960995d5f72d665404dc14a9ec8892ec
more weird nuances
diff --git a/Makefile.hfst b/Makefile.hfst index 0e9151d..92f276c 100644 --- a/Makefile.hfst +++ b/Makefile.hfst @@ -1,175 +1,177 @@ XFST=hfst-xfst TWOLC=hfst-twolc ICONV=iconv # testimiseks ESTMORF=wine ~/estmorf/ESTMORF.EXE EKI_DATA=~/eki/data EKI_ANA=wine ~/eki/demo_ana.exe # latin1 to utf-8 TO_UTF8=$(ICONV) -f latin1 -t UTF-8 FROM_UTF8=$(ICONV) -f UTF-8 -t latin1 # estonians used modified latin1 where scaron & zcaron used to be # encoded as eth and thorn. ETHTHORN=sed -e 's/š/ð/g' -e 's/Š/Ð/g' -e 's/ž/þ/g' -e 's/Ž/Þ/g' INVERSE_ETHTHORN=sed -e 's/ð/š/g' -e 's/Ð/Š/g' -e 's/þ/ž/g' -e 's/Þ/Ž/g' GENERATED_LEX=stems.lexc generated_extra.lexc TESTFILE=1984_words_u.txt # vaikimisi ehitame vaid eesti keele morfoanalüsaatori FST all: eesti.fst # vahel on kasulik kõik genereeritud failid ära koristada clean: $(RM) eesti.fst lexicon.fst lex-av.fst rules.fst xfst.out estmorf.out rules-av.twolc \ rules-av.fst lexicon.lexc $(GENERATED_LEX) exceptions.lexc generated_overrides.lexc \ exceptions.fst full-compound.fst lihtsonad.fst liitsonamask.fst arvud.fst \ 1984_words_u_l1.txt 1984_words_u_l1.out eki.out liitsonamask.lexc \ estmorf_check.out reverse-eesti.fst reverse-lex-av.fst reverse-lihtsonad.fst \ liitsonafilter.lexc liitsonafilter.fst rules.hfst $(APERTIUM_CLEAN) ## peamine FST ehitamine #eesti.fst: lexicon.fst rules.fst exceptions.fst deriv_filter.txt xfst.script liitsonamask.lexc \ # liitsonafilter.lexc arvud.lexc # $(XFST) -f xfst.script %.fst: %.lexc hfst-lexc -f foma $< -o $@ # $(XFST) -e 'read lexc $<' -e 'set quit-on-fail OFF' -e 'eliminate flag LEXNAME' -e 'save $@' < /dev/null #%.fst: %.twolc # @printf "read-grammar $<\ncompile\nintersect\n\n\nsave-binary $@\nquit\n" | $(TWOLC) || \ ( $(TWOLC) -i $< -o $@ && $(XFST) -e 'load < $@' -e 'intersect' -e 'save $@' < /dev/null) %.hfst: %.twolc $(TWOLC) -f foma -i $< -o $@ --resolve #lex-av.fst: rules.fst lexicon.fst # $(XFST) -e 'read regex [@"rules.fst"].i .o. [@"lexicon.fst"]' -e 'save lex-av.fst' < /dev/null lex-av.fst: rules.hfst lexicon.fst - hfst-compose-intersect lexicon.fst rules.hfst -o $@ + hfst-invert -i lexicon.fst -o lexicon-i.fst + hfst-compose-intersect lexicon-i.fst rules.hfst -o lex-av-i.fst + hfst-invert -i lex-av-i.fst -o $@ #lihtsonad.fst: deriv_filter.txt exceptions.fst lex-av.fst rules.fst arvud.fst # $(XFST) -e 'read regex [ @re"deriv_filter.txt" .o. [[@"exceptions.fst"] .P. [@"lex-av.fst"]] .o. ~$$"#" .o. @"rules.fst" ] | @"arvud.fst"' -e 'save lihtsonad.fst' < /dev/null lihtsonad.fst: deriv_filter.txt exceptions.fst lex-av.fst rules.hfst arvud.fst $(XFST) -e 'read regex [ @re"deriv_filter.txt" .o. [[@"exceptions.fst"] .P. [@"lex-av.fst"]] .o. ~$$"#"]' -e 'save foo.fst' < /dev/null hfst-fst2fst -f foma -i foo.fst -o foo.hfst hfst-compose-intersect foo.hfst rules.hfst |\ hfst-disjunct arvud.fst |\ hfst-minimize -o $@ full-compound.fst: lihtsonad.fst # $(XFST) -e 'read regex ("-" "&") [ @"lihtsonad.fst" "&" ("-" "&") ]* @"lihtsonad.fst" ("&" "-")' -e 'save full-compound.fst' < /dev/null echo '("-" "&")' | hfst-regexp2fst -f foma -o hyphen-amper.hfst echo ' [ @"hyphen-amper.hfst" ] [ @"lihtsonad.fst" "&" @"hyphen-amper.hfst" ]* @"lihtsonad.fst" @"hyphen-amper.hfst"' | hfst-regexp2fst -f foma -o $@ eesti.fst: liitsonafilter.fst liitsonamask.fst full-compound.fst echo '@"liitsonafilter.fst" .o. @"liitsonamask.fst" .o. @"full-compound.fst" .o. [ "&" -> "" ]' | hfst-regexp2fst -f foma -o $@ # Heli variandis oli ülemine reeglitekiht vaid astmevahelduse jaoks, praktikas sellest ei piisanud? # rules-av.twolc on fail, kus on vaid rules.twolc algus kuni märgendini "!!!! EOF AV" rules-av.twolc: rules.twolc awk '/!!!! EOF AV/ { x = 1; } { if (!x) { print; } }' rules.twolc > rules-av.twolc # awk '/!!!! EOF AV/ { x = 1; } { if (!x) { print; } }' rules.twolc | sed -e 's/%+:0/%+:%+/' > rules-av.twolc # põhisõnastiku lexc-lähtetekst pannakse tükkidest kokku, tükkide järjekord on oluline lexicon.lexc: multichar.lexc main.lexc gi.lexc $(GENERATED_LEX) cat $^ > $@ # peamine tyvedesõnastik, genereeritakse peamiselt EKI tüvebaasist stems.lexc: tyvebaas.txt tyvebaas-lisa.txt eki2lex.pl cat tyvebaas.txt tyvebaas-lisa.txt | ./eki2lex.pl # eranditesõnastiku lexc-lähtetekst exceptions.lexc: multichar.lexc overrides.lexc generated_overrides.lexc gi.lexc cat $^ > $@ # erandifailid. "tõelised" erandid ja paralleelvormid, genereeritakse # pisut täiendatud EKI andmetest generated_overrides.lexc generated_extra.lexc: form.exc fcodes.ini exc2lex.pl cat form.exc | $(TO_UTF8) | $(INVERSE_ETHTHORN) | ./exc2lex.pl # liitsõna-regulaaravaldistega lexc-sõnastiku lähtetekst liitsonamask.lexc: multichar.lexc compound_definitions.lexc compound_rules.lexc cat $^ > $@ # liitsõna-erandite jms regulaaravaldis lexc-sõnastikuna liitsonafilter.lexc: multichar.lexc compound_definitions.lexc compound_filter.lexc cat $^ > $@ # # testimisega seotud kraam # # peamine testiviis. alternatiivsete sisenditega testimiseks # make TESTFILE=testifailinimi xfst.out xfst.out: eesti.fst $(TESTFILE) $(XFST) -e "load eesti.fst" -e "apply up < $(TESTFILE)" -q -pipe > xfst.out < /dev/null # võrdluseks estmorfi väljund # TESTFILE on ka siin kasutatav estmorf.out: $(TESTFILE) cat $^ | $(ETHTHORN) | $(FROM_UTF8) | $(ESTMORF) > $@ # "normeeritud" estmorfi väljund estmorf_check.out: estmorf.out cat $^ | fromdos | $(TO_UTF8) | $(INVERSE_ETHTHORN) | ./tolkija.pl > $@ # testfail EKI jaoks 1984_words_u_l1.txt: $(TESTFILE) cat $(TESTFILE) | $(ETHTHORN) | $(FROM_UTF8) | todos > $@ eki.out: 1984_words_u_l1.txt export EST_MORPHO_DATA=$(EKI_DATA); $(EKI_ANA) 1984_words_u_l1.txt /v3 /s+ /t- cat 1984_words_u_l1.out | ./eki_out2out.pl > eki.out # interaktiivne XFST -- ehitab valmis ja laeb vaikimisi ka kehtiva seisu FSTst xfsti: eesti.fst $(XFST) -e "load eesti.fst" tundmatud: xfst.out grep -FB1 ??? xfst.out | grep -vF ??? | grep -vFe -- | less test: estmorf.out xfst.out eki.out $(TESTFILE) grep -F '???' xfst.out | wc -l grep -F '###' estmorf.out | wc -l grep -F '###' eki.out | wc -l wc -l $(TESTFILE) testx: xfst.out grep -F '???' xfst.out | wc -l ###################################### apertium: apertium-fin-est.est-fin.LR.att.gz apertium-fin-est.est-fin.RL.att.gz punctuation.hfst: punctuation.lexc hfst-lexc -f foma $< -o $@ est.apertium.fst: eesti.fst punctuation.hfst hfst-union eesti.fst punctuation.hfst -o est.gen.fst hfst-invert est.gen.fst -o est.mor.fst hfst-substitute -F apertium.relabel est.mor.fst -o $@ apertium-fin-est.est-fin.LR.att: est.apertium.fst hfst-fst2txt est.apertium.fst -o $@ apertium-fin-est.est-fin.RL.att: est.apertium.fst hfst-invert est.apertium.fst | hfst-fst2txt -o $@ %.att.gz: %.att gzip -9 -f --verbose $< APERTIUM_CLEAN=apertium-fin-est.est-fin.LR.att.gz apertium-fin-est.est-fin.RL.att.gz est.apertium.fst \ punctuation.hfst est.gen.fst est.mor.fst
jjpp/plamk
3703581a1a89f4f6745e94d3c3787149c3562685
Minor fixes
diff --git a/Makefile.hfst b/Makefile.hfst index 469d2b9..0e9151d 100644 --- a/Makefile.hfst +++ b/Makefile.hfst @@ -1,175 +1,175 @@ XFST=hfst-xfst TWOLC=hfst-twolc ICONV=iconv # testimiseks ESTMORF=wine ~/estmorf/ESTMORF.EXE EKI_DATA=~/eki/data EKI_ANA=wine ~/eki/demo_ana.exe # latin1 to utf-8 TO_UTF8=$(ICONV) -f latin1 -t UTF-8 FROM_UTF8=$(ICONV) -f UTF-8 -t latin1 # estonians used modified latin1 where scaron & zcaron used to be # encoded as eth and thorn. ETHTHORN=sed -e 's/š/ð/g' -e 's/Š/Ð/g' -e 's/ž/þ/g' -e 's/Ž/Þ/g' INVERSE_ETHTHORN=sed -e 's/ð/š/g' -e 's/Ð/Š/g' -e 's/þ/ž/g' -e 's/Þ/Ž/g' GENERATED_LEX=stems.lexc generated_extra.lexc TESTFILE=1984_words_u.txt # vaikimisi ehitame vaid eesti keele morfoanalüsaatori FST all: eesti.fst # vahel on kasulik kõik genereeritud failid ära koristada clean: $(RM) eesti.fst lexicon.fst lex-av.fst rules.fst xfst.out estmorf.out rules-av.twolc \ rules-av.fst lexicon.lexc $(GENERATED_LEX) exceptions.lexc generated_overrides.lexc \ exceptions.fst full-compound.fst lihtsonad.fst liitsonamask.fst arvud.fst \ 1984_words_u_l1.txt 1984_words_u_l1.out eki.out liitsonamask.lexc \ estmorf_check.out reverse-eesti.fst reverse-lex-av.fst reverse-lihtsonad.fst \ - liitsonafilter.lexc liitsonafilter.fst rules.hfst + liitsonafilter.lexc liitsonafilter.fst rules.hfst $(APERTIUM_CLEAN) ## peamine FST ehitamine #eesti.fst: lexicon.fst rules.fst exceptions.fst deriv_filter.txt xfst.script liitsonamask.lexc \ # liitsonafilter.lexc arvud.lexc # $(XFST) -f xfst.script %.fst: %.lexc hfst-lexc -f foma $< -o $@ # $(XFST) -e 'read lexc $<' -e 'set quit-on-fail OFF' -e 'eliminate flag LEXNAME' -e 'save $@' < /dev/null #%.fst: %.twolc # @printf "read-grammar $<\ncompile\nintersect\n\n\nsave-binary $@\nquit\n" | $(TWOLC) || \ ( $(TWOLC) -i $< -o $@ && $(XFST) -e 'load < $@' -e 'intersect' -e 'save $@' < /dev/null) %.hfst: %.twolc $(TWOLC) -f foma -i $< -o $@ --resolve #lex-av.fst: rules.fst lexicon.fst # $(XFST) -e 'read regex [@"rules.fst"].i .o. [@"lexicon.fst"]' -e 'save lex-av.fst' < /dev/null lex-av.fst: rules.hfst lexicon.fst - hfst-compose-intersect lexicon.hfst rules.hfst -o $@ + hfst-compose-intersect lexicon.fst rules.hfst -o $@ #lihtsonad.fst: deriv_filter.txt exceptions.fst lex-av.fst rules.fst arvud.fst # $(XFST) -e 'read regex [ @re"deriv_filter.txt" .o. [[@"exceptions.fst"] .P. [@"lex-av.fst"]] .o. ~$$"#" .o. @"rules.fst" ] | @"arvud.fst"' -e 'save lihtsonad.fst' < /dev/null lihtsonad.fst: deriv_filter.txt exceptions.fst lex-av.fst rules.hfst arvud.fst $(XFST) -e 'read regex [ @re"deriv_filter.txt" .o. [[@"exceptions.fst"] .P. [@"lex-av.fst"]] .o. ~$$"#"]' -e 'save foo.fst' < /dev/null hfst-fst2fst -f foma -i foo.fst -o foo.hfst hfst-compose-intersect foo.hfst rules.hfst |\ hfst-disjunct arvud.fst |\ hfst-minimize -o $@ full-compound.fst: lihtsonad.fst # $(XFST) -e 'read regex ("-" "&") [ @"lihtsonad.fst" "&" ("-" "&") ]* @"lihtsonad.fst" ("&" "-")' -e 'save full-compound.fst' < /dev/null echo '("-" "&")' | hfst-regexp2fst -f foma -o hyphen-amper.hfst echo ' [ @"hyphen-amper.hfst" ] [ @"lihtsonad.fst" "&" @"hyphen-amper.hfst" ]* @"lihtsonad.fst" @"hyphen-amper.hfst"' | hfst-regexp2fst -f foma -o $@ eesti.fst: liitsonafilter.fst liitsonamask.fst full-compound.fst echo '@"liitsonafilter.fst" .o. @"liitsonamask.fst" .o. @"full-compound.fst" .o. [ "&" -> "" ]' | hfst-regexp2fst -f foma -o $@ # Heli variandis oli ülemine reeglitekiht vaid astmevahelduse jaoks, praktikas sellest ei piisanud? # rules-av.twolc on fail, kus on vaid rules.twolc algus kuni märgendini "!!!! EOF AV" rules-av.twolc: rules.twolc awk '/!!!! EOF AV/ { x = 1; } { if (!x) { print; } }' rules.twolc > rules-av.twolc # awk '/!!!! EOF AV/ { x = 1; } { if (!x) { print; } }' rules.twolc | sed -e 's/%+:0/%+:%+/' > rules-av.twolc # põhisõnastiku lexc-lähtetekst pannakse tükkidest kokku, tükkide järjekord on oluline lexicon.lexc: multichar.lexc main.lexc gi.lexc $(GENERATED_LEX) cat $^ > $@ # peamine tyvedesõnastik, genereeritakse peamiselt EKI tüvebaasist stems.lexc: tyvebaas.txt tyvebaas-lisa.txt eki2lex.pl cat tyvebaas.txt tyvebaas-lisa.txt | ./eki2lex.pl # eranditesõnastiku lexc-lähtetekst exceptions.lexc: multichar.lexc overrides.lexc generated_overrides.lexc gi.lexc cat $^ > $@ # erandifailid. "tõelised" erandid ja paralleelvormid, genereeritakse # pisut täiendatud EKI andmetest generated_overrides.lexc generated_extra.lexc: form.exc fcodes.ini exc2lex.pl cat form.exc | $(TO_UTF8) | $(INVERSE_ETHTHORN) | ./exc2lex.pl # liitsõna-regulaaravaldistega lexc-sõnastiku lähtetekst liitsonamask.lexc: multichar.lexc compound_definitions.lexc compound_rules.lexc cat $^ > $@ # liitsõna-erandite jms regulaaravaldis lexc-sõnastikuna liitsonafilter.lexc: multichar.lexc compound_definitions.lexc compound_filter.lexc cat $^ > $@ # # testimisega seotud kraam # # peamine testiviis. alternatiivsete sisenditega testimiseks # make TESTFILE=testifailinimi xfst.out xfst.out: eesti.fst $(TESTFILE) $(XFST) -e "load eesti.fst" -e "apply up < $(TESTFILE)" -q -pipe > xfst.out < /dev/null # võrdluseks estmorfi väljund # TESTFILE on ka siin kasutatav estmorf.out: $(TESTFILE) cat $^ | $(ETHTHORN) | $(FROM_UTF8) | $(ESTMORF) > $@ # "normeeritud" estmorfi väljund estmorf_check.out: estmorf.out cat $^ | fromdos | $(TO_UTF8) | $(INVERSE_ETHTHORN) | ./tolkija.pl > $@ # testfail EKI jaoks 1984_words_u_l1.txt: $(TESTFILE) cat $(TESTFILE) | $(ETHTHORN) | $(FROM_UTF8) | todos > $@ eki.out: 1984_words_u_l1.txt export EST_MORPHO_DATA=$(EKI_DATA); $(EKI_ANA) 1984_words_u_l1.txt /v3 /s+ /t- cat 1984_words_u_l1.out | ./eki_out2out.pl > eki.out # interaktiivne XFST -- ehitab valmis ja laeb vaikimisi ka kehtiva seisu FSTst xfsti: eesti.fst $(XFST) -e "load eesti.fst" tundmatud: xfst.out grep -FB1 ??? xfst.out | grep -vF ??? | grep -vFe -- | less test: estmorf.out xfst.out eki.out $(TESTFILE) grep -F '???' xfst.out | wc -l grep -F '###' estmorf.out | wc -l grep -F '###' eki.out | wc -l wc -l $(TESTFILE) testx: xfst.out grep -F '???' xfst.out | wc -l ###################################### apertium: apertium-fin-est.est-fin.LR.att.gz apertium-fin-est.est-fin.RL.att.gz punctuation.hfst: punctuation.lexc - hfst-lexc $< -o $@ + hfst-lexc -f foma $< -o $@ est.apertium.fst: eesti.fst punctuation.hfst hfst-union eesti.fst punctuation.hfst -o est.gen.fst hfst-invert est.gen.fst -o est.mor.fst hfst-substitute -F apertium.relabel est.mor.fst -o $@ apertium-fin-est.est-fin.LR.att: est.apertium.fst hfst-fst2txt est.apertium.fst -o $@ apertium-fin-est.est-fin.RL.att: est.apertium.fst hfst-invert est.apertium.fst | hfst-fst2txt -o $@ %.att.gz: %.att gzip -9 -f --verbose $< APERTIUM_CLEAN=apertium-fin-est.est-fin.LR.att.gz apertium-fin-est.est-fin.RL.att.gz est.apertium.fst \ punctuation.hfst est.gen.fst est.mor.fst