CombinedText
stringlengths
4
3.42M
# Copyright (C) 2007, 2008, 2009, 2010 The Collaborative Software Foundation # # This file is part of TriSano. # # TriSano is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # TriSano 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt. class HumanEvent < Event include Export::Cdc::HumanEvent extend NameAndBirthdateSearch validates_length_of :parent_guardian, :maximum => 255, :allow_blank => true validates_numericality_of :age_at_onset, :allow_nil => true, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 120, :only_integer => true, :message => :bad_range validates_date :event_onset_date before_validation :set_onset_date, :set_age_at_onset has_one :interested_party, :foreign_key => "event_id" has_many :labs, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy has_many :hospitalization_facilities, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy has_many :diagnostic_facilities, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy has_many :clinicians, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy belongs_to :participations_contact belongs_to :participations_encounter accepts_nested_attributes_for :interested_party accepts_nested_attributes_for :hospitalization_facilities, :allow_destroy => true, :reject_if => proc { |attrs| attrs["secondary_entity_id"].blank? && attrs["hospitals_participation_attributes"].all? { |k, v| v.blank? } } accepts_nested_attributes_for :clinicians, :allow_destroy => true, :reject_if => proc { |attrs| attrs.has_key?("person_entity_attributes") && attrs["person_entity_attributes"]["person_attributes"].all? { |k, v| if v == 'clinician' then true else v.blank? end } } accepts_nested_attributes_for :diagnostic_facilities, :allow_destroy => true, :reject_if => proc { |attrs| attrs.has_key?("place_entity_attributes") && attrs["place_entity_attributes"]["place_attributes"].all? { |k, v| v.blank? } } accepts_nested_attributes_for :labs, :allow_destroy => true, :reject_if => proc { |attrs| rewrite_attrs(attrs) } accepts_nested_attributes_for :participations_contact, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } } accepts_nested_attributes_for :participations_encounter, :reject_if => proc { |attrs| attrs.all? { |k, v| ((k == "user_id") || (k == "encounter_location_type")) ? true : v.blank? } } class << self def rewrite_attrs(attrs) entity_attrs = attrs["place_entity_attributes"] lab_attrs = entity_attrs["place_attributes"] return true if (lab_attrs.all? { |k, v| v.blank? } && attrs["lab_results_attributes"].all? { |k, v| v.all? { |k, v| v.blank? } }) # If there's a lab with the same name already in the database, use that instead. existing_labs = Place.labs_by_name(lab_attrs["name"]) unless existing_labs.empty? attrs["secondary_entity_id"] = existing_labs.first.entity_id attrs.delete("place_entity_attributes") else lab_attrs["place_type_ids"] = [Code.lab_place_type_id] end return false end def get_allowed_queues(query_queues) system_queues = EventQueue.queues_for_jurisdictions(User.current_user.jurisdiction_ids_for_privilege(:view_event)) queue_ids = system_queues.collect { |system_queue| query_queues.include?(system_queue.queue_name) ? system_queue.id : nil }.compact queue_names = system_queues.collect { |system_queue| query_queues.include?(system_queue.queue_name) ? system_queue.queue_name : nil }.compact return queue_ids, queue_names end def get_states_and_descriptions new.states.collect do |state| OpenStruct.new :workflow_state => state, :description => state_description(state) end end def state_description(state) I18n.translate(state, :scope => [:workflow]) end def find_all_for_filtered_view(options = {}) where_clause = "(events.type = 'MorbidityEvent' OR events.type = 'ContactEvent')" states = options[:states] || [] if states.empty? where_clause << " AND workflow_state != 'not_routed'" else where_clause << " AND workflow_state IN (#{ states.map { |s| sanitize_sql_for_conditions(["'%s'", s]).untaint }.join(',') })" end if options[:diseases] where_clause << " AND disease_id IN (#{ options[:diseases].map { |d| sanitize_sql_for_conditions(["'%s'", d]).untaint }.join(',') })" end if options[:investigators] where_clause << " AND investigator_id IN (#{ options[:investigators].map { |i| sanitize_sql_for_conditions(["'%s'", i]).untaint }.join(',') })" end if options[:queues] queue_ids, queue_names = get_allowed_queues(options[:queues]) if queue_ids.empty? raise(I18n.translate('no_queue_ids_returned')) else where_clause << " AND event_queue_id IN (#{ queue_ids.map { |q| sanitize_sql_for_conditions(["'%s'", q]).untaint }.join(',') })" end end if options[:do_not_show_deleted] where_clause << " AND events.deleted_at IS NULL" end order_direction = options[:order_direction].blank? ? 'ASC' : options[:order_direction] order_by_clause = case options[:order_by] when 'patient' "last_name #{order_direction}, first_name, disease_name, jurisdiction_short_name, workflow_state" when 'disease' "disease_name #{order_direction}, last_name, first_name, jurisdiction_short_name, workflow_state" when 'jurisdiction' "jurisdiction_short_name #{order_direction}, last_name, first_name, disease_name, workflow_state" when 'status' # Fortunately the event status code stored in the DB and the text the user sees mostly correspond to the same alphabetical ordering" "workflow_state #{order_direction}, last_name, first_name, disease_name, jurisdiction_short_name" when 'event_date' "events.created_at #{order_direction}, last_name, first_name, disease_name, jurisdiction_short_name, workflow_state" else "events.updated_at DESC" end users_view_jurisdictions = User.current_user.jurisdiction_ids_for_privilege(:view_event) users_view_jurisdictions << "NULL" if users_view_jurisdictions.empty? query_options = options.reject { |k, v| [:page, :order_by, :set_as_default_view].include?(k) } User.current_user.update_attribute('event_view_settings', query_options) if options[:set_as_default_view] == "1" users_view_jurisdictions_sanitized = [] users_view_jurisdictions.each do |j| users_view_jurisdictions_sanitized << sanitize_sql_for_conditions(["%d", j]).untaint end # Hard coding the query to wring out some speed. real_select = <<-SQL SELECT events.id AS id, events.event_onset_date AS event_onset_date, events.created_at AS created_at, events.type AS type, events.deleted_at AS deleted_at, events.workflow_state as workflow_state, events.investigator_id as investigator_id, events.event_queue_id as event_queue_id, entities.id AS entity_id, people.first_name AS first_name, people.last_name AS last_name, diseases.disease_name AS disease_name, jurisdiction_entities.id AS jurisdiction_entity_id, jurisdiction_places.short_name AS jurisdiction_short_name, sec_juris.secondary_jurisdiction_names AS secondary_jurisdictions, CASE WHEN users.given_name IS NOT NULL AND users.given_name != '' THEN users.given_name WHEN users.last_name IS NOT NULL AND users.last_name != '' THEN trim(BOTH ' ' FROM users.first_name || ' ' || users.last_name) WHEN users.user_name IS NOT NULL AND users.user_name != '' THEN users.user_name ELSE users.uid END AS investigator_name, event_queues.queue_name as queue_name FROM events INNER JOIN participations ON participations.event_id = events.id AND (participations.type = 'InterestedParty' ) INNER JOIN entities ON entities.id = participations.primary_entity_id AND (entities.entity_type = 'PersonEntity' ) INNER JOIN people ON people.entity_id = entities.id LEFT OUTER JOIN disease_events ON disease_events.event_id = events.id LEFT OUTER JOIN diseases ON disease_events.disease_id = diseases.id INNER JOIN participations AS jurisdictions ON jurisdictions.event_id = events.id AND (jurisdictions.type = 'Jurisdiction') AND (jurisdictions.secondary_entity_id IN (#{users_view_jurisdictions_sanitized.join(',')})) INNER JOIN entities AS jurisdiction_entities ON jurisdiction_entities.id = jurisdictions.secondary_entity_id AND (jurisdiction_entities.entity_type = 'PlaceEntity') INNER JOIN places AS jurisdiction_places ON jurisdiction_places.entity_id = jurisdiction_entities.id LEFT JOIN ( SELECT events.id AS event_id, ARRAY_ACCUM(places.short_name) AS secondary_jurisdiction_names FROM events LEFT JOIN participations p ON (p.event_id = events.id AND p.type = 'AssociatedJurisdiction') LEFT JOIN entities pe ON pe.id = p.secondary_entity_id LEFT JOIN places ON places.entity_id = pe.id GROUP BY events.id ) sec_juris ON (sec_juris.event_id = events.id) LEFT JOIN users ON users.id = events.investigator_id LEFT JOIN event_queues ON event_queues.id = events.event_queue_id SQL # The paginate plugin needs a total row count. Normally it would simply re-execute the main query wrapped in a count(*). # But in an effort to shave off some more time, we will provide a row count with this simplified version of the main # query. count_select = <<-SQL SELECT COUNT(*) FROM events INNER JOIN participations AS jurisdictions ON jurisdictions.event_id = events.id AND (jurisdictions.type = 'Jurisdiction') AND (jurisdictions.secondary_entity_id IN (#{users_view_jurisdictions.join(',')})) LEFT OUTER JOIN disease_events ON disease_events.event_id = events.id LEFT OUTER JOIN diseases ON disease_events.disease_id = diseases.id LEFT JOIN users ON users.id = events.investigator_id LEFT JOIN event_queues ON event_queues.id = events.event_queue_id SQL count_select << "WHERE (#{where_clause})\n" unless where_clause.blank? row_count = Event.count_by_sql(count_select) real_select << "WHERE (#{where_clause})\n" unless where_clause.blank? real_select << "ORDER BY #{order_by_clause}" find_options = { :page => options[:page], :total_entries => row_count } find_options[:per_page] = options[:per_page] if options[:per_page].to_i > 0 Event.paginate_by_sql(real_select, find_options) rescue Exception => ex logger.error ex raise ex end end def lab_results @results ||= ( results = [] labs.each do |lab| lab.lab_results.each do |lab_result| results << lab_result end end results ) end def definitive_lab_collection_date labs.collect{|l| l.lab_results.collect{|r| r.collection_date}}.flatten.compact.sort.first end def set_primary_entity_on_secondary_participations self.participations.each do |participation| if participation.primary_entity_id.nil? participation.update_attribute('primary_entity_id', self.interested_party.person_entity.id) end end end def party @party ||= self.safe_call_chain(:interested_party, :person_entity, :person) end def copy_from_person(person) self.suppress_validation(:first_reported_PH_date) self.build_jurisdiction self.build_interested_party self.jurisdiction.secondary_entity = (User.current_user.jurisdictions_for_privilege(:create_event).first || Place.unassigned_jurisdiction).entity self.interested_party.primary_entity_id = person.id self.interested_party.person_entity = person self.address = person.canonical_address end # Perform a shallow (event_coponents = nil) or deep (event_components != nil) copy of an event. # Can't simply do a single clone or a series of clones because there are some attributes we need # to leave behind, certain relationships that need to be severed, and we need to make a copy of # the address for longitudinal purposes. def copy_event(new_event, event_components) super(new_event, event_components) org_entity = self.interested_party.person_entity new_event.build_interested_party(:primary_entity_id => org_entity.id) entity_address = org_entity.addresses.find(:first, :conditions => ['event_id = ?', self.id], :order => 'created_at DESC') new_event.address = entity_address ? entity_address.clone : nil new_event.imported_from_id = self.imported_from_id new_event.parent_guardian = self.parent_guardian new_event.other_data_1 = self.other_data_1 new_event.other_data_2 = self.other_data_2 return unless event_components # Shallow, demographics only, copy # If event_components is not nil, then continue on with a deep copy if event_components.include?("clinical") self.hospitalization_facilities.each do |h| new_h = new_event.hospitalization_facilities.build(:secondary_entity_id => h.secondary_entity_id) unless h.hospitals_participation.nil? if attrs = h.hospitals_participation.attributes attrs.delete('participation_id') new_h.build_hospitals_participation(attrs) end end end self.interested_party.treatments.each do |t| attrs = t.attributes attrs.delete('participation_id') new_event.interested_party.treatments.build(attrs) end if rf = self.interested_party.risk_factor attrs = self.interested_party.risk_factor.attributes attrs.delete('participation_id') new_event.interested_party.build_risk_factor(attrs) end self.clinicians.each do |c| new_event.clinicians.build(:secondary_entity_id => c.secondary_entity_id) end self.diagnostic_facilities.each do |d| new_event.diagnostic_facilities.build(:secondary_entity_id => d.secondary_entity_id) end end if event_components.include?("lab") self.labs.each do |l| lab = new_event.labs.build(:secondary_entity_id => l.secondary_entity_id) l.lab_results.each do |lr| attrs = lr.attributes attrs.delete('participation_id') lab.lab_results.build(attrs) end end end end def update_from_params(event_params) =begin labs_attributes = event_params['labs_attributes'] if labs_attributes i = 0 loop do lab_attributes = labs_attributes[i.to_s] break unless lab_attributes place_entity_attributes = lab_attributes['place_entity_attributes'] place_attributes = place_entity_attributes['place_attributes'] new_lab_name = place_attributes['name'] old_place = Place.find place_attributes['id'] if new_lab_name != old_place.name and (new_place=Place.find_by_name(new_lab_name)) # This exists, just associate this PlaceEntity instead of # the old one. place_attributes['id'] = new_place.id place_entity_attributes['id'] = new_place.entity.id lab = Lab.find lab_attributes['id'] lab.secondary_entity_id = new_place.entity.id lab.save! end i += 1 end end =end self.attributes = event_params end def state_description I18n.t(state, :scope => [:workflow]) end # Debt: some stuff here gets written to the database, and some still # requires the event to be saved. def route_to_jurisdiction(jurisdiction, secondary_jurisdiction_ids=[], note="") return false unless valid? primary_changed = false jurisdiction_id = jurisdiction.to_i if jurisdiction.respond_to?('to_i') jurisdiction_id = jurisdiction.id if jurisdiction.is_a? Entity jurisdiction_id = jurisdiction.entity_id if jurisdiction.is_a? Place transaction do # Handle the primary jurisdiction # # Do nothing if the passed-in jurisdiction is the current jurisdiction unless jurisdiction_id == self.jurisdiction.secondary_entity_id proposed_jurisdiction = PlaceEntity.find(jurisdiction_id) # Will raise an exception if record not found raise(I18n.translate('new_jurisdiction_is_not_jurisdiction')) unless Place.jurisdictions.include?(proposed_jurisdiction.place) self.jurisdiction.update_attribute("secondary_entity_id", jurisdiction_id) self.add_note note primary_changed = true end # Handle secondary jurisdictions existing_secondary_jurisdiction_ids = associated_jurisdictions.collect { |participation| participation.secondary_entity_id } # if an existing secondary jurisdiction ID is not in the passed-in ids, delete (existing_secondary_jurisdiction_ids - secondary_jurisdiction_ids).each do |id_to_delete| associated_jurisdictions.delete(associated_jurisdictions.find_by_secondary_entity_id(id_to_delete)) end # if an passed-in ID is not in the existing secondary jurisdiction IDs, add (secondary_jurisdiction_ids - existing_secondary_jurisdiction_ids).each do |id_to_add| associated_jurisdictions.create(:secondary_entity_id => id_to_add) end if self.disease applicable_forms = Form.get_published_investigation_forms(self.disease_event.disease_id, self.jurisdiction.secondary_entity_id, self.class.name.underscore) self.add_forms(applicable_forms) end reload # Any existing references to this object won't see these changes without this end return primary_changed end # transitions that are allowed to be rendered by this user def allowed_transitions current_state.events.select do |event| priv_required = current_state.events(event).meta[:priv_required] next if priv_required.nil? j_id = primary_jurisdiction.entity_id User.current_user.is_entitled_to_in?(priv_required, j_id) end end def undo_workflow_side_effects attrs = { :investigation_started_date => nil, :investigation_completed_LHD_date => nil, :review_completed_by_state_date => nil } case self.state when :assigned_to_lhd attrs[:investigator_id] = nil attrs[:event_queue_id] = nil end self.update_attributes(attrs) end def add_labs_from_staged_message(staged_message) raise(ArgumentError, I18n.translate('not_a_valid_staged_message', :staged_message => staged_message.class)) unless staged_message.respond_to?('message_header') # All tests have a scale type. The scale type is well known and is part of the standard LOINC code data given in the SCALE_TYP # field. TriSano keeps the scale type in the loinc_codes table scale column. # # There are four scale types that we care about: ordinal (Ord: one of X), nominal (Nom: a string), quantitative (Qn: a number), # and ordinal or quantitative (OrdQn). # # An ordinal test result has values such as Positive or Reactive. E.g. the lab was positive for HIV # # A quantitative test result has a value such as 100 or .5, which when combined with the units field gives a meaningful result. # E.g, the lab showed a hemoglobin count of 13.0 Gm/Dl. # # A nominal test result has a string. In TriSano we are currently making the assumption that this is an organism name. # E.g the blood culture showed the influenza virus. # # An ordinal/quantiative test is either an ordinal string or a number # # These three principal (not including OrdQn) types of test results are, ideally, mapped to three different fields: # # Ord -> test_result_id # Qn -> result_value # Nom -> organism_id # # In the case or Ord and Nom, if the value can't be mapped because the provided value does not match TriSano values, # e.g., the ordinal value is "Affirmative" instead of "Positive", then the result is placed in the result_value field, # rather than not mapping it at all. This has the side effect of making an OrdQn the same as an Ord. # # In addition to organisms specified directly for nominal tests, ordinal and quantitative tests can have organisms too. # TriSano maintains a loinc code to organism relationship in the database # For ordinal tests, a single result has multiple synonyms, such as: "Positive", " Confirmed", " Detected", " Definitive" # So, first load the TriSano test_results, then bust out the slash-separated synonyms into hash keys whose value is the test_result ID. # I.e: { "Positive" => 1, "Confirmed" => 1, "Negative" => 2, ... } test_results = ExternalCode.find_all_by_code_name("test_result") result_map = {} test_results.each do |result| result.code_description.split('/').each do |component| result_map[component.gsub(/\s/, '').downcase] = result.id end end # Set the lab name lab_attributes = { "place_entity_attributes"=> { "place_attributes"=> { "name"=> staged_message.lab_name } }, "lab_results_attributes" => {} } # Create one lab result per OBX segment i = 0 diseases = Set.new # country per_message_comments = '' unless staged_message.patient.address_country.blank? per_message_comments = "#{I18n.translate :country}: #{staged_message.patient.address_country}" end pv1 = staged_message.pv1 orc = staged_message.common_order @orc_clinician = find_or_build_clinician(orc.clinician_last_name, orc.clinician_first_name, orc.clinician_phone_type, orc.clinician_telephone) unless orc.nil? or orc.clinician_last_name.blank? find_or_build_clinician(staged_message.pv1.attending_doctor[0], staged_message.pv1.attending_doctor[1]) unless pv1.nil? or pv1.attending_doctor.blank? find_or_build_clinician(staged_message.pv1.consulting_doctor[0], staged_message.pv1.consulting_doctor[1]) unless pv1.nil? or pv1.consulting_doctor.blank? staged_message.observation_requests.each do |obr| find_or_build_clinician(obr.clinician_last_name, obr.clinician_first_name, obr.clinician_phone_type, obr.clinician_telephone) unless obr.clinician_last_name.blank? per_request_comments = per_message_comments.clone unless obr.filler_order_number.blank? per_request_comments += ", " unless per_request_comments.blank? per_request_comments += "#{I18n.translate :accession_no}: #{obr.filler_order_number}" end unless obr.specimen_id.blank? per_request_comments += ", " unless per_request_comments.blank? per_request_comments += "#{I18n.translate :specimen_id}: #{obr.specimen_id}" end obr.tests.each do |obx| loinc_code = LoincCode.find_by_loinc_code obx.loinc_code @scale_type = nil @common_test_type = nil if loinc_code @scale_type = loinc_code.scale.the_code @common_test_type = loinc_code.common_test_type || CommonTestType.find_by_common_name(obx.loinc_common_test_type) else # No :loinc_code entry. # Look at other OBX fields for hints to the scale and common # test type. @scale_type = obx.loinc_scale if @scale_type.nil? self.add_note I18n.translate(:unknown_loinc_code, :loinc_code => obx.loinc_code) next end common_test_type_name = obx.loinc_common_test_type @common_test_type = CommonTestType.find_by_common_name(common_test_type_name) if common_test_type_name end if @common_test_type.nil? self.add_note I18n.translate(:loinc_code_known_but_not_linked, :loinc_code => obx.loinc_code) next end comments = per_request_comments.clone unless obx.abnormal_flags.blank? comments += ", " unless comments.blank? comments += "#{I18n.translate :abnormal_flags}: #{obx.abnormal_flags}" end result_hash = {} if @scale_type != "Nom" if loinc_code.organism result_hash["organism_id"] = loinc_code.organism.id else comments += ", " unless comments.blank? comments += "ELR Message: No organism mapped to LOINC code." end loinc_code.diseases.each { |disease| diseases << disease } end case @scale_type when "Ord", "OrdQn" obx_result = obx.result.gsub(/\s/, '').downcase if map_id = result_map[obx_result] result_hash["test_result_id"] = map_id else result_hash["result_value"] = obx.result end when "Qn" result_hash["result_value"] = obx.result when "Nom" # Try and find OBX-5 in the organism list, otherwise map to result_value # Eventually, we'll need to add more heuristics here for SNOMED etc. organism = Organism.first(:conditions => [ "organism_name ~* ?", '^'+obx.result+'$' ]) if organism.blank? result_hash["result_value"] = obx.result else result_hash["organism_id"] = organism.id organism.diseases.each { |disease| diseases << disease } end end begin lab_hash = { "test_type_id" => @common_test_type.id, "collection_date" => obr.collection_date, "lab_test_date" => obx.test_date, "reference_range" => obx.reference_range, "specimen_source_id" => obr.specimen_source.id, "staged_message_id" => staged_message.id, "units" => obx.units, "test_status_id" => obx.trisano_status_id, "loinc_code" => loinc_code, "comment" => comments }.merge!(result_hash) lab_attributes["lab_results_attributes"][i.to_s] = lab_hash rescue Exception => error raise StagedMessage::BadMessageFormat, error.message end i += 1 self.add_note(I18n.translate("system_notes.elr_with_test_type_assigned", :test_type => obx.test_type, :locale => I18n.default_locale)) end # Grab any diseases associated with this OBR loinc_code = LoincCode.find_by_loinc_code obr.test_performed loinc_code.diseases.each { |disease| diseases << disease } if loinc_code and diseases.blank? end unless i > 0 # All OBX invalid raise StagedMessage::UnknownLoincCode, I18n.translate(:all_obx_unprocessable) end self.labs_attributes = [ lab_attributes ] # Assign disease unless self.disease_event # Don't overwrite disease if already there. case diseases.size when 0 staged_message.note = "#{staged_message.note} #{I18n.translate('no_loinc_code_maps_to_disease', :locale => I18n.default_locale)} " when 1 disease_event = DiseaseEvent.new disease_event.disease = diseases.to_a.first self.build_disease_event(disease_event.attributes) staged_message.note = "#{staged_message.note} #{I18n.translate('event_disease_set_to', :disease_name => disease_event.disease.disease_name, :locale => I18n.default_locale)} " else staged_message.note = "#{staged_message.note} #{I18n.translate('loinc_code_maps_to_multiple_diseases', :locale => I18n.default_locale)}" + diseases.collect { |d| d.disease_name }.join('; ') + ". " end end unless staged_message.patient.primary_language.blank? or interested_party.nil? or interested_party.person_entity.person.primary_language_id staged_message.note ||= '' staged_message.note.sub! /\s+$/, '' staged_message.note += '. ' if staged_message.note.length > 0 staged_message.note += I18n.translate :unmapped_language_code, :lang_code => staged_message.patient.primary_language, :locale => I18n.default_locale end unless staged_message.patient.dead_flag.blank? or disease_event.nil? code = case staged_message.patient.dead_flag when 'Y' ExternalCode.yes when 'N' ExternalCode.no end self.disease_event.update_attribute :died_id, code.id end unless disease_event.nil? or staged_message.pv1.blank? or staged_message.pv1.hospitalized_id.nil? hospitalized_id = staged_message.pv1.hospitalized_id self.disease_event.update_attribute :hospitalized_id, hospitalized_id if hospitalized_id == ExternalCode.yes.id facility_name = staged_message.pv2.facility_name if staged_message.pv2 facility_name = staged_message.common_order.facility_name if facility_name.blank? and staged_message.common_order # assign the facility name, which requires finding or building a # place unless facility_name.blank? # do we already have this? place_entity = PlaceEntity.first :conditions => [ "places.name = ?", facility_name ], :joins => "INNER JOIN places ON places.entity_id = entities.id" # no? create it place_entity ||= PlaceEntity.new :place_attributes => { :name => facility_name, :short_name => facility_name } # make it a hospital place_code = Code.find_by_code_name_and_the_code('placetype', 'H') place_entity.place.place_types << place_code unless place_entity.place.place_types.include?(place_code) # associate it with this event self.hospitalization_facilities.build :place_entity => place_entity end end end self.parent_guardian = staged_message.next_of_kin.parent_guardian.slice(0,2).join(', ') if staged_message.next_of_kin end def possible_treatments(reload=false) if reload or @possible_treatments.nil? options = { :order => 'treatment_name' } if disease = disease_event.try(:disease) options[:joins] = 'LEFT JOIN disease_specific_treatments b ON b.treatment_id = treatments.id' options[:conditions] = [<<-SQL, disease.id, self.id] (active = true AND disease_id = ?) OR treatments.id IN ( SELECT treatment_id FROM participations_treatments a JOIN participations b ON b.id = a.participation_id AND b.event_id = ?) SQL else options[:conditions] = [<<-SQL, self.id] ("default" = true AND active = true) OR id IN ( SELECT treatment_id FROM participations_treatments a JOIN participations b ON b.id = a.participation_id AND b.event_id = ?) SQL end @possible_treatments = Treatment.all(options) end @possible_treatments end private def find_or_build_clinician(last_name, first_name, telephone_type=nil, telephone=nil) person_attributes = { :last_name => last_name , :first_name => first_name, :person_type => 'clinician' } person = Person.first :conditions => person_attributes if person person_entity_id = person.person_entity.id @clinician = clinicians.to_a.find do |c| c.secondary_entity_id == person_entity_id end @clinician ||= clinicians.build :secondary_entity_id => person_entity_id else @clinician = clinicians.to_a.find do |c| c.person_entity.person.last_name == last_name && c.person_entity.person.first_name == first_name end @clinician ||= clinicians.build :person_entity_attributes => { :person_attributes => person_attributes } end unless telephone_type.nil? or telephone.blank? or telephone.all? {|x|x.nil?} area_code, number, extension = telephone telephone_attributes = { :entity_location_type => telephone_type, :area_code => area_code, :phone_number => number, :extension => extension } @clinician.person_entity.telephones.to_a.find do |t| t.entity_location_type == telephone_type && t.area_code == area_code && t.phone_number == number && t.extension == extension end or @clinician.person_entity.telephones.build(telephone_attributes) end @clinician rescue end def set_age_at_onset birthdate = safe_call_chain(:interested_party, :person_entity, :person, :birth_date) self.age_info = AgeInfo.create_from_dates(birthdate, self.event_onset_date) end def set_onset_date self.event_onset_date = resolve_onset_date end def resolve_onset_date safe_call_chain(:disease_event, :disease_onset_date) || safe_call_chain(:disease_event, :date_diagnosed) || definitive_lab_collection_date || self.first_reported_PH_date || self.created_at.try(:to_date) || Date.today end def validate super county_code = self.address.try(:county).try(:the_code) if county_code == "OS" && (((self.lhd_case_status != ExternalCode.out_of_state) && (!self.lhd_case_status.nil?)) || ((self.state_case_status != ExternalCode.out_of_state) && (!self.state_case_status.nil?))) errors.add(:base, :invalid_case_status, :status => ExternalCode.out_of_state.code_description, :attr => I18n.t(:county).downcase, :value => self.address.county.code_description) end return if self.interested_party.nil? return unless bdate = self.interested_party.person_entity.try(:person).try(:birth_date) base_errors = {} self.hospitalization_facilities.each do |hf| if (date = hf.hospitals_participation.try(:admission_date).try(:to_date)) && (date < bdate) hf.hospitals_participation.errors.add(:admission_date, :cannot_precede_birth_date) base_errors['hospitals'] = [:precede_birth_date, {:thing => I18n.t(:hospitalization)}] end if (date = hf.hospitals_participation.try(:discharge_date).try(:to_date)) && (date < bdate) hf.hospitals_participation.errors.add(:discharge_date, :cannot_precede_birth_date) base_errors['hospitals'] = [:precede_birth_date, { :thing => I18n.t(:hospitalization) }] end end self.interested_party.treatments.each do |t| if (date = t.treatment_date.try(:to_date)) && (date < bdate) t.errors.add(:treatment_date, :cannot_precede_birth_date) base_errors['treatments'] = [:precede_birth_date, { :thing => I18n.t(:treatment) }] end if (date = t.stop_treatment_date.try(:to_date)) && (date < bdate) t.errors.add(:stop_treatment_date, :cannot_precede_birth_date) base_errors['treatments'] = [:precede_birth_date, { :thing => I18n.t(:treatment) }] end end risk_factor = self.interested_party.risk_factor if (date = risk_factor.try(:pregnancy_due_date).try(:to_date)) && (date < bdate) risk_factor.errors.add(:pregnancy_due_date, :cannot_precede_birth_date) base_errors['risk_factor'] = [:precede_birth_date, { :thing => I18n.t(:risk_factor) }] end if (date = self.disease_event.try(:disease_onset_date).try(:to_date)) && (date < bdate) self.disease_event.errors.add(:disease_onset_date, :cannot_precede_birth_date) base_errors['disease'] = [:precede_birth_date, { :thing => I18n.t(:disease) }] end if (date = self.disease_event.try(:date_diagnosed).try(:to_date)) && (date < bdate) self.disease_event.errors.add(:date_diagnosed, :cannot_precede_birth_date) base_errors['disease'] = [:precede_birth_date, { :thing => I18n.t(:disease) }] end self.labs.each do |l| l.lab_results.each do |lr| if (date = lr.collection_date.try(:to_date)) && (date < bdate) lr.errors.add(:collection_date, :cannot_precede_birth_date) base_errors['labs'] = [:precede_birth_date, { :thing => I18n.t(:lab_result) }] end if (date = lr.lab_test_date.try(:to_date)) && (date < bdate) lr.errors.add(:lab_test_date, :cannot_precede_birth_date) base_errors['labs'] = [:precede_birth_date, { :thing => I18n.t(:lab_result) }] end end end if (date = self.results_reported_to_clinician_date.try(:to_date)) && (date < bdate) self.errors.add(:results_reported_to_clinician_date, :cannot_precede_birth_date) end if (date = self.first_reported_PH_date.try(:to_date)) && (date < bdate) self.errors.add(:first_reported_PH_date, :cannot_precede_birth_date) end unless base_errors.empty? && self.errors.empty? base_errors.values.each { |msg| self.errors.add(:base, *msg) } end end end [Finished #8462191] Fix for duplicate treatments in drop downs. Existing tests continue to pass. No test changes b/c I couldn't dupe the issue in specs with factory-bootstrapped objects. # Copyright (C) 2007, 2008, 2009, 2010 The Collaborative Software Foundation # # This file is part of TriSano. # # TriSano is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # TriSano 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt. class HumanEvent < Event include Export::Cdc::HumanEvent extend NameAndBirthdateSearch validates_length_of :parent_guardian, :maximum => 255, :allow_blank => true validates_numericality_of :age_at_onset, :allow_nil => true, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 120, :only_integer => true, :message => :bad_range validates_date :event_onset_date before_validation :set_onset_date, :set_age_at_onset has_one :interested_party, :foreign_key => "event_id" has_many :labs, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy has_many :hospitalization_facilities, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy has_many :diagnostic_facilities, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy has_many :clinicians, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy belongs_to :participations_contact belongs_to :participations_encounter accepts_nested_attributes_for :interested_party accepts_nested_attributes_for :hospitalization_facilities, :allow_destroy => true, :reject_if => proc { |attrs| attrs["secondary_entity_id"].blank? && attrs["hospitals_participation_attributes"].all? { |k, v| v.blank? } } accepts_nested_attributes_for :clinicians, :allow_destroy => true, :reject_if => proc { |attrs| attrs.has_key?("person_entity_attributes") && attrs["person_entity_attributes"]["person_attributes"].all? { |k, v| if v == 'clinician' then true else v.blank? end } } accepts_nested_attributes_for :diagnostic_facilities, :allow_destroy => true, :reject_if => proc { |attrs| attrs.has_key?("place_entity_attributes") && attrs["place_entity_attributes"]["place_attributes"].all? { |k, v| v.blank? } } accepts_nested_attributes_for :labs, :allow_destroy => true, :reject_if => proc { |attrs| rewrite_attrs(attrs) } accepts_nested_attributes_for :participations_contact, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } } accepts_nested_attributes_for :participations_encounter, :reject_if => proc { |attrs| attrs.all? { |k, v| ((k == "user_id") || (k == "encounter_location_type")) ? true : v.blank? } } class << self def rewrite_attrs(attrs) entity_attrs = attrs["place_entity_attributes"] lab_attrs = entity_attrs["place_attributes"] return true if (lab_attrs.all? { |k, v| v.blank? } && attrs["lab_results_attributes"].all? { |k, v| v.all? { |k, v| v.blank? } }) # If there's a lab with the same name already in the database, use that instead. existing_labs = Place.labs_by_name(lab_attrs["name"]) unless existing_labs.empty? attrs["secondary_entity_id"] = existing_labs.first.entity_id attrs.delete("place_entity_attributes") else lab_attrs["place_type_ids"] = [Code.lab_place_type_id] end return false end def get_allowed_queues(query_queues) system_queues = EventQueue.queues_for_jurisdictions(User.current_user.jurisdiction_ids_for_privilege(:view_event)) queue_ids = system_queues.collect { |system_queue| query_queues.include?(system_queue.queue_name) ? system_queue.id : nil }.compact queue_names = system_queues.collect { |system_queue| query_queues.include?(system_queue.queue_name) ? system_queue.queue_name : nil }.compact return queue_ids, queue_names end def get_states_and_descriptions new.states.collect do |state| OpenStruct.new :workflow_state => state, :description => state_description(state) end end def state_description(state) I18n.translate(state, :scope => [:workflow]) end def find_all_for_filtered_view(options = {}) where_clause = "(events.type = 'MorbidityEvent' OR events.type = 'ContactEvent')" states = options[:states] || [] if states.empty? where_clause << " AND workflow_state != 'not_routed'" else where_clause << " AND workflow_state IN (#{ states.map { |s| sanitize_sql_for_conditions(["'%s'", s]).untaint }.join(',') })" end if options[:diseases] where_clause << " AND disease_id IN (#{ options[:diseases].map { |d| sanitize_sql_for_conditions(["'%s'", d]).untaint }.join(',') })" end if options[:investigators] where_clause << " AND investigator_id IN (#{ options[:investigators].map { |i| sanitize_sql_for_conditions(["'%s'", i]).untaint }.join(',') })" end if options[:queues] queue_ids, queue_names = get_allowed_queues(options[:queues]) if queue_ids.empty? raise(I18n.translate('no_queue_ids_returned')) else where_clause << " AND event_queue_id IN (#{ queue_ids.map { |q| sanitize_sql_for_conditions(["'%s'", q]).untaint }.join(',') })" end end if options[:do_not_show_deleted] where_clause << " AND events.deleted_at IS NULL" end order_direction = options[:order_direction].blank? ? 'ASC' : options[:order_direction] order_by_clause = case options[:order_by] when 'patient' "last_name #{order_direction}, first_name, disease_name, jurisdiction_short_name, workflow_state" when 'disease' "disease_name #{order_direction}, last_name, first_name, jurisdiction_short_name, workflow_state" when 'jurisdiction' "jurisdiction_short_name #{order_direction}, last_name, first_name, disease_name, workflow_state" when 'status' # Fortunately the event status code stored in the DB and the text the user sees mostly correspond to the same alphabetical ordering" "workflow_state #{order_direction}, last_name, first_name, disease_name, jurisdiction_short_name" when 'event_date' "events.created_at #{order_direction}, last_name, first_name, disease_name, jurisdiction_short_name, workflow_state" else "events.updated_at DESC" end users_view_jurisdictions = User.current_user.jurisdiction_ids_for_privilege(:view_event) users_view_jurisdictions << "NULL" if users_view_jurisdictions.empty? query_options = options.reject { |k, v| [:page, :order_by, :set_as_default_view].include?(k) } User.current_user.update_attribute('event_view_settings', query_options) if options[:set_as_default_view] == "1" users_view_jurisdictions_sanitized = [] users_view_jurisdictions.each do |j| users_view_jurisdictions_sanitized << sanitize_sql_for_conditions(["%d", j]).untaint end # Hard coding the query to wring out some speed. real_select = <<-SQL SELECT events.id AS id, events.event_onset_date AS event_onset_date, events.created_at AS created_at, events.type AS type, events.deleted_at AS deleted_at, events.workflow_state as workflow_state, events.investigator_id as investigator_id, events.event_queue_id as event_queue_id, entities.id AS entity_id, people.first_name AS first_name, people.last_name AS last_name, diseases.disease_name AS disease_name, jurisdiction_entities.id AS jurisdiction_entity_id, jurisdiction_places.short_name AS jurisdiction_short_name, sec_juris.secondary_jurisdiction_names AS secondary_jurisdictions, CASE WHEN users.given_name IS NOT NULL AND users.given_name != '' THEN users.given_name WHEN users.last_name IS NOT NULL AND users.last_name != '' THEN trim(BOTH ' ' FROM users.first_name || ' ' || users.last_name) WHEN users.user_name IS NOT NULL AND users.user_name != '' THEN users.user_name ELSE users.uid END AS investigator_name, event_queues.queue_name as queue_name FROM events INNER JOIN participations ON participations.event_id = events.id AND (participations.type = 'InterestedParty' ) INNER JOIN entities ON entities.id = participations.primary_entity_id AND (entities.entity_type = 'PersonEntity' ) INNER JOIN people ON people.entity_id = entities.id LEFT OUTER JOIN disease_events ON disease_events.event_id = events.id LEFT OUTER JOIN diseases ON disease_events.disease_id = diseases.id INNER JOIN participations AS jurisdictions ON jurisdictions.event_id = events.id AND (jurisdictions.type = 'Jurisdiction') AND (jurisdictions.secondary_entity_id IN (#{users_view_jurisdictions_sanitized.join(',')})) INNER JOIN entities AS jurisdiction_entities ON jurisdiction_entities.id = jurisdictions.secondary_entity_id AND (jurisdiction_entities.entity_type = 'PlaceEntity') INNER JOIN places AS jurisdiction_places ON jurisdiction_places.entity_id = jurisdiction_entities.id LEFT JOIN ( SELECT events.id AS event_id, ARRAY_ACCUM(places.short_name) AS secondary_jurisdiction_names FROM events LEFT JOIN participations p ON (p.event_id = events.id AND p.type = 'AssociatedJurisdiction') LEFT JOIN entities pe ON pe.id = p.secondary_entity_id LEFT JOIN places ON places.entity_id = pe.id GROUP BY events.id ) sec_juris ON (sec_juris.event_id = events.id) LEFT JOIN users ON users.id = events.investigator_id LEFT JOIN event_queues ON event_queues.id = events.event_queue_id SQL # The paginate plugin needs a total row count. Normally it would simply re-execute the main query wrapped in a count(*). # But in an effort to shave off some more time, we will provide a row count with this simplified version of the main # query. count_select = <<-SQL SELECT COUNT(*) FROM events INNER JOIN participations AS jurisdictions ON jurisdictions.event_id = events.id AND (jurisdictions.type = 'Jurisdiction') AND (jurisdictions.secondary_entity_id IN (#{users_view_jurisdictions.join(',')})) LEFT OUTER JOIN disease_events ON disease_events.event_id = events.id LEFT OUTER JOIN diseases ON disease_events.disease_id = diseases.id LEFT JOIN users ON users.id = events.investigator_id LEFT JOIN event_queues ON event_queues.id = events.event_queue_id SQL count_select << "WHERE (#{where_clause})\n" unless where_clause.blank? row_count = Event.count_by_sql(count_select) real_select << "WHERE (#{where_clause})\n" unless where_clause.blank? real_select << "ORDER BY #{order_by_clause}" find_options = { :page => options[:page], :total_entries => row_count } find_options[:per_page] = options[:per_page] if options[:per_page].to_i > 0 Event.paginate_by_sql(real_select, find_options) rescue Exception => ex logger.error ex raise ex end end def lab_results @results ||= ( results = [] labs.each do |lab| lab.lab_results.each do |lab_result| results << lab_result end end results ) end def definitive_lab_collection_date labs.collect{|l| l.lab_results.collect{|r| r.collection_date}}.flatten.compact.sort.first end def set_primary_entity_on_secondary_participations self.participations.each do |participation| if participation.primary_entity_id.nil? participation.update_attribute('primary_entity_id', self.interested_party.person_entity.id) end end end def party @party ||= self.safe_call_chain(:interested_party, :person_entity, :person) end def copy_from_person(person) self.suppress_validation(:first_reported_PH_date) self.build_jurisdiction self.build_interested_party self.jurisdiction.secondary_entity = (User.current_user.jurisdictions_for_privilege(:create_event).first || Place.unassigned_jurisdiction).entity self.interested_party.primary_entity_id = person.id self.interested_party.person_entity = person self.address = person.canonical_address end # Perform a shallow (event_coponents = nil) or deep (event_components != nil) copy of an event. # Can't simply do a single clone or a series of clones because there are some attributes we need # to leave behind, certain relationships that need to be severed, and we need to make a copy of # the address for longitudinal purposes. def copy_event(new_event, event_components) super(new_event, event_components) org_entity = self.interested_party.person_entity new_event.build_interested_party(:primary_entity_id => org_entity.id) entity_address = org_entity.addresses.find(:first, :conditions => ['event_id = ?', self.id], :order => 'created_at DESC') new_event.address = entity_address ? entity_address.clone : nil new_event.imported_from_id = self.imported_from_id new_event.parent_guardian = self.parent_guardian new_event.other_data_1 = self.other_data_1 new_event.other_data_2 = self.other_data_2 return unless event_components # Shallow, demographics only, copy # If event_components is not nil, then continue on with a deep copy if event_components.include?("clinical") self.hospitalization_facilities.each do |h| new_h = new_event.hospitalization_facilities.build(:secondary_entity_id => h.secondary_entity_id) unless h.hospitals_participation.nil? if attrs = h.hospitals_participation.attributes attrs.delete('participation_id') new_h.build_hospitals_participation(attrs) end end end self.interested_party.treatments.each do |t| attrs = t.attributes attrs.delete('participation_id') new_event.interested_party.treatments.build(attrs) end if rf = self.interested_party.risk_factor attrs = self.interested_party.risk_factor.attributes attrs.delete('participation_id') new_event.interested_party.build_risk_factor(attrs) end self.clinicians.each do |c| new_event.clinicians.build(:secondary_entity_id => c.secondary_entity_id) end self.diagnostic_facilities.each do |d| new_event.diagnostic_facilities.build(:secondary_entity_id => d.secondary_entity_id) end end if event_components.include?("lab") self.labs.each do |l| lab = new_event.labs.build(:secondary_entity_id => l.secondary_entity_id) l.lab_results.each do |lr| attrs = lr.attributes attrs.delete('participation_id') lab.lab_results.build(attrs) end end end end def update_from_params(event_params) =begin labs_attributes = event_params['labs_attributes'] if labs_attributes i = 0 loop do lab_attributes = labs_attributes[i.to_s] break unless lab_attributes place_entity_attributes = lab_attributes['place_entity_attributes'] place_attributes = place_entity_attributes['place_attributes'] new_lab_name = place_attributes['name'] old_place = Place.find place_attributes['id'] if new_lab_name != old_place.name and (new_place=Place.find_by_name(new_lab_name)) # This exists, just associate this PlaceEntity instead of # the old one. place_attributes['id'] = new_place.id place_entity_attributes['id'] = new_place.entity.id lab = Lab.find lab_attributes['id'] lab.secondary_entity_id = new_place.entity.id lab.save! end i += 1 end end =end self.attributes = event_params end def state_description I18n.t(state, :scope => [:workflow]) end # Debt: some stuff here gets written to the database, and some still # requires the event to be saved. def route_to_jurisdiction(jurisdiction, secondary_jurisdiction_ids=[], note="") return false unless valid? primary_changed = false jurisdiction_id = jurisdiction.to_i if jurisdiction.respond_to?('to_i') jurisdiction_id = jurisdiction.id if jurisdiction.is_a? Entity jurisdiction_id = jurisdiction.entity_id if jurisdiction.is_a? Place transaction do # Handle the primary jurisdiction # # Do nothing if the passed-in jurisdiction is the current jurisdiction unless jurisdiction_id == self.jurisdiction.secondary_entity_id proposed_jurisdiction = PlaceEntity.find(jurisdiction_id) # Will raise an exception if record not found raise(I18n.translate('new_jurisdiction_is_not_jurisdiction')) unless Place.jurisdictions.include?(proposed_jurisdiction.place) self.jurisdiction.update_attribute("secondary_entity_id", jurisdiction_id) self.add_note note primary_changed = true end # Handle secondary jurisdictions existing_secondary_jurisdiction_ids = associated_jurisdictions.collect { |participation| participation.secondary_entity_id } # if an existing secondary jurisdiction ID is not in the passed-in ids, delete (existing_secondary_jurisdiction_ids - secondary_jurisdiction_ids).each do |id_to_delete| associated_jurisdictions.delete(associated_jurisdictions.find_by_secondary_entity_id(id_to_delete)) end # if an passed-in ID is not in the existing secondary jurisdiction IDs, add (secondary_jurisdiction_ids - existing_secondary_jurisdiction_ids).each do |id_to_add| associated_jurisdictions.create(:secondary_entity_id => id_to_add) end if self.disease applicable_forms = Form.get_published_investigation_forms(self.disease_event.disease_id, self.jurisdiction.secondary_entity_id, self.class.name.underscore) self.add_forms(applicable_forms) end reload # Any existing references to this object won't see these changes without this end return primary_changed end # transitions that are allowed to be rendered by this user def allowed_transitions current_state.events.select do |event| priv_required = current_state.events(event).meta[:priv_required] next if priv_required.nil? j_id = primary_jurisdiction.entity_id User.current_user.is_entitled_to_in?(priv_required, j_id) end end def undo_workflow_side_effects attrs = { :investigation_started_date => nil, :investigation_completed_LHD_date => nil, :review_completed_by_state_date => nil } case self.state when :assigned_to_lhd attrs[:investigator_id] = nil attrs[:event_queue_id] = nil end self.update_attributes(attrs) end def add_labs_from_staged_message(staged_message) raise(ArgumentError, I18n.translate('not_a_valid_staged_message', :staged_message => staged_message.class)) unless staged_message.respond_to?('message_header') # All tests have a scale type. The scale type is well known and is part of the standard LOINC code data given in the SCALE_TYP # field. TriSano keeps the scale type in the loinc_codes table scale column. # # There are four scale types that we care about: ordinal (Ord: one of X), nominal (Nom: a string), quantitative (Qn: a number), # and ordinal or quantitative (OrdQn). # # An ordinal test result has values such as Positive or Reactive. E.g. the lab was positive for HIV # # A quantitative test result has a value such as 100 or .5, which when combined with the units field gives a meaningful result. # E.g, the lab showed a hemoglobin count of 13.0 Gm/Dl. # # A nominal test result has a string. In TriSano we are currently making the assumption that this is an organism name. # E.g the blood culture showed the influenza virus. # # An ordinal/quantiative test is either an ordinal string or a number # # These three principal (not including OrdQn) types of test results are, ideally, mapped to three different fields: # # Ord -> test_result_id # Qn -> result_value # Nom -> organism_id # # In the case or Ord and Nom, if the value can't be mapped because the provided value does not match TriSano values, # e.g., the ordinal value is "Affirmative" instead of "Positive", then the result is placed in the result_value field, # rather than not mapping it at all. This has the side effect of making an OrdQn the same as an Ord. # # In addition to organisms specified directly for nominal tests, ordinal and quantitative tests can have organisms too. # TriSano maintains a loinc code to organism relationship in the database # For ordinal tests, a single result has multiple synonyms, such as: "Positive", " Confirmed", " Detected", " Definitive" # So, first load the TriSano test_results, then bust out the slash-separated synonyms into hash keys whose value is the test_result ID. # I.e: { "Positive" => 1, "Confirmed" => 1, "Negative" => 2, ... } test_results = ExternalCode.find_all_by_code_name("test_result") result_map = {} test_results.each do |result| result.code_description.split('/').each do |component| result_map[component.gsub(/\s/, '').downcase] = result.id end end # Set the lab name lab_attributes = { "place_entity_attributes"=> { "place_attributes"=> { "name"=> staged_message.lab_name } }, "lab_results_attributes" => {} } # Create one lab result per OBX segment i = 0 diseases = Set.new # country per_message_comments = '' unless staged_message.patient.address_country.blank? per_message_comments = "#{I18n.translate :country}: #{staged_message.patient.address_country}" end pv1 = staged_message.pv1 orc = staged_message.common_order @orc_clinician = find_or_build_clinician(orc.clinician_last_name, orc.clinician_first_name, orc.clinician_phone_type, orc.clinician_telephone) unless orc.nil? or orc.clinician_last_name.blank? find_or_build_clinician(staged_message.pv1.attending_doctor[0], staged_message.pv1.attending_doctor[1]) unless pv1.nil? or pv1.attending_doctor.blank? find_or_build_clinician(staged_message.pv1.consulting_doctor[0], staged_message.pv1.consulting_doctor[1]) unless pv1.nil? or pv1.consulting_doctor.blank? staged_message.observation_requests.each do |obr| find_or_build_clinician(obr.clinician_last_name, obr.clinician_first_name, obr.clinician_phone_type, obr.clinician_telephone) unless obr.clinician_last_name.blank? per_request_comments = per_message_comments.clone unless obr.filler_order_number.blank? per_request_comments += ", " unless per_request_comments.blank? per_request_comments += "#{I18n.translate :accession_no}: #{obr.filler_order_number}" end unless obr.specimen_id.blank? per_request_comments += ", " unless per_request_comments.blank? per_request_comments += "#{I18n.translate :specimen_id}: #{obr.specimen_id}" end obr.tests.each do |obx| loinc_code = LoincCode.find_by_loinc_code obx.loinc_code @scale_type = nil @common_test_type = nil if loinc_code @scale_type = loinc_code.scale.the_code @common_test_type = loinc_code.common_test_type || CommonTestType.find_by_common_name(obx.loinc_common_test_type) else # No :loinc_code entry. # Look at other OBX fields for hints to the scale and common # test type. @scale_type = obx.loinc_scale if @scale_type.nil? self.add_note I18n.translate(:unknown_loinc_code, :loinc_code => obx.loinc_code) next end common_test_type_name = obx.loinc_common_test_type @common_test_type = CommonTestType.find_by_common_name(common_test_type_name) if common_test_type_name end if @common_test_type.nil? self.add_note I18n.translate(:loinc_code_known_but_not_linked, :loinc_code => obx.loinc_code) next end comments = per_request_comments.clone unless obx.abnormal_flags.blank? comments += ", " unless comments.blank? comments += "#{I18n.translate :abnormal_flags}: #{obx.abnormal_flags}" end result_hash = {} if @scale_type != "Nom" if loinc_code.organism result_hash["organism_id"] = loinc_code.organism.id else comments += ", " unless comments.blank? comments += "ELR Message: No organism mapped to LOINC code." end loinc_code.diseases.each { |disease| diseases << disease } end case @scale_type when "Ord", "OrdQn" obx_result = obx.result.gsub(/\s/, '').downcase if map_id = result_map[obx_result] result_hash["test_result_id"] = map_id else result_hash["result_value"] = obx.result end when "Qn" result_hash["result_value"] = obx.result when "Nom" # Try and find OBX-5 in the organism list, otherwise map to result_value # Eventually, we'll need to add more heuristics here for SNOMED etc. organism = Organism.first(:conditions => [ "organism_name ~* ?", '^'+obx.result+'$' ]) if organism.blank? result_hash["result_value"] = obx.result else result_hash["organism_id"] = organism.id organism.diseases.each { |disease| diseases << disease } end end begin lab_hash = { "test_type_id" => @common_test_type.id, "collection_date" => obr.collection_date, "lab_test_date" => obx.test_date, "reference_range" => obx.reference_range, "specimen_source_id" => obr.specimen_source.id, "staged_message_id" => staged_message.id, "units" => obx.units, "test_status_id" => obx.trisano_status_id, "loinc_code" => loinc_code, "comment" => comments }.merge!(result_hash) lab_attributes["lab_results_attributes"][i.to_s] = lab_hash rescue Exception => error raise StagedMessage::BadMessageFormat, error.message end i += 1 self.add_note(I18n.translate("system_notes.elr_with_test_type_assigned", :test_type => obx.test_type, :locale => I18n.default_locale)) end # Grab any diseases associated with this OBR loinc_code = LoincCode.find_by_loinc_code obr.test_performed loinc_code.diseases.each { |disease| diseases << disease } if loinc_code and diseases.blank? end unless i > 0 # All OBX invalid raise StagedMessage::UnknownLoincCode, I18n.translate(:all_obx_unprocessable) end self.labs_attributes = [ lab_attributes ] # Assign disease unless self.disease_event # Don't overwrite disease if already there. case diseases.size when 0 staged_message.note = "#{staged_message.note} #{I18n.translate('no_loinc_code_maps_to_disease', :locale => I18n.default_locale)} " when 1 disease_event = DiseaseEvent.new disease_event.disease = diseases.to_a.first self.build_disease_event(disease_event.attributes) staged_message.note = "#{staged_message.note} #{I18n.translate('event_disease_set_to', :disease_name => disease_event.disease.disease_name, :locale => I18n.default_locale)} " else staged_message.note = "#{staged_message.note} #{I18n.translate('loinc_code_maps_to_multiple_diseases', :locale => I18n.default_locale)}" + diseases.collect { |d| d.disease_name }.join('; ') + ". " end end unless staged_message.patient.primary_language.blank? or interested_party.nil? or interested_party.person_entity.person.primary_language_id staged_message.note ||= '' staged_message.note.sub! /\s+$/, '' staged_message.note += '. ' if staged_message.note.length > 0 staged_message.note += I18n.translate :unmapped_language_code, :lang_code => staged_message.patient.primary_language, :locale => I18n.default_locale end unless staged_message.patient.dead_flag.blank? or disease_event.nil? code = case staged_message.patient.dead_flag when 'Y' ExternalCode.yes when 'N' ExternalCode.no end self.disease_event.update_attribute :died_id, code.id end unless disease_event.nil? or staged_message.pv1.blank? or staged_message.pv1.hospitalized_id.nil? hospitalized_id = staged_message.pv1.hospitalized_id self.disease_event.update_attribute :hospitalized_id, hospitalized_id if hospitalized_id == ExternalCode.yes.id facility_name = staged_message.pv2.facility_name if staged_message.pv2 facility_name = staged_message.common_order.facility_name if facility_name.blank? and staged_message.common_order # assign the facility name, which requires finding or building a # place unless facility_name.blank? # do we already have this? place_entity = PlaceEntity.first :conditions => [ "places.name = ?", facility_name ], :joins => "INNER JOIN places ON places.entity_id = entities.id" # no? create it place_entity ||= PlaceEntity.new :place_attributes => { :name => facility_name, :short_name => facility_name } # make it a hospital place_code = Code.find_by_code_name_and_the_code('placetype', 'H') place_entity.place.place_types << place_code unless place_entity.place.place_types.include?(place_code) # associate it with this event self.hospitalization_facilities.build :place_entity => place_entity end end end self.parent_guardian = staged_message.next_of_kin.parent_guardian.slice(0,2).join(', ') if staged_message.next_of_kin end def possible_treatments(reload=false) if reload or @possible_treatments.nil? options = { :select => 'distinct treatments.*', :order => 'treatment_name' } if disease = disease_event.try(:disease) options[:joins] = 'LEFT JOIN disease_specific_treatments b ON b.treatment_id = treatments.id' options[:conditions] = [<<-SQL, disease.id, self.id] (active = true AND disease_id = ?) OR treatments.id IN ( SELECT treatment_id FROM participations_treatments a JOIN participations b ON b.id = a.participation_id AND b.event_id = ?) SQL else options[:conditions] = [<<-SQL, self.id] ("default" = true AND active = true) OR id IN ( SELECT treatment_id FROM participations_treatments a JOIN participations b ON b.id = a.participation_id AND b.event_id = ?) SQL end @possible_treatments = Treatment.all(options) end @possible_treatments end private def find_or_build_clinician(last_name, first_name, telephone_type=nil, telephone=nil) person_attributes = { :last_name => last_name , :first_name => first_name, :person_type => 'clinician' } person = Person.first :conditions => person_attributes if person person_entity_id = person.person_entity.id @clinician = clinicians.to_a.find do |c| c.secondary_entity_id == person_entity_id end @clinician ||= clinicians.build :secondary_entity_id => person_entity_id else @clinician = clinicians.to_a.find do |c| c.person_entity.person.last_name == last_name && c.person_entity.person.first_name == first_name end @clinician ||= clinicians.build :person_entity_attributes => { :person_attributes => person_attributes } end unless telephone_type.nil? or telephone.blank? or telephone.all? {|x|x.nil?} area_code, number, extension = telephone telephone_attributes = { :entity_location_type => telephone_type, :area_code => area_code, :phone_number => number, :extension => extension } @clinician.person_entity.telephones.to_a.find do |t| t.entity_location_type == telephone_type && t.area_code == area_code && t.phone_number == number && t.extension == extension end or @clinician.person_entity.telephones.build(telephone_attributes) end @clinician rescue end def set_age_at_onset birthdate = safe_call_chain(:interested_party, :person_entity, :person, :birth_date) self.age_info = AgeInfo.create_from_dates(birthdate, self.event_onset_date) end def set_onset_date self.event_onset_date = resolve_onset_date end def resolve_onset_date safe_call_chain(:disease_event, :disease_onset_date) || safe_call_chain(:disease_event, :date_diagnosed) || definitive_lab_collection_date || self.first_reported_PH_date || self.created_at.try(:to_date) || Date.today end def validate super county_code = self.address.try(:county).try(:the_code) if county_code == "OS" && (((self.lhd_case_status != ExternalCode.out_of_state) && (!self.lhd_case_status.nil?)) || ((self.state_case_status != ExternalCode.out_of_state) && (!self.state_case_status.nil?))) errors.add(:base, :invalid_case_status, :status => ExternalCode.out_of_state.code_description, :attr => I18n.t(:county).downcase, :value => self.address.county.code_description) end return if self.interested_party.nil? return unless bdate = self.interested_party.person_entity.try(:person).try(:birth_date) base_errors = {} self.hospitalization_facilities.each do |hf| if (date = hf.hospitals_participation.try(:admission_date).try(:to_date)) && (date < bdate) hf.hospitals_participation.errors.add(:admission_date, :cannot_precede_birth_date) base_errors['hospitals'] = [:precede_birth_date, {:thing => I18n.t(:hospitalization)}] end if (date = hf.hospitals_participation.try(:discharge_date).try(:to_date)) && (date < bdate) hf.hospitals_participation.errors.add(:discharge_date, :cannot_precede_birth_date) base_errors['hospitals'] = [:precede_birth_date, { :thing => I18n.t(:hospitalization) }] end end self.interested_party.treatments.each do |t| if (date = t.treatment_date.try(:to_date)) && (date < bdate) t.errors.add(:treatment_date, :cannot_precede_birth_date) base_errors['treatments'] = [:precede_birth_date, { :thing => I18n.t(:treatment) }] end if (date = t.stop_treatment_date.try(:to_date)) && (date < bdate) t.errors.add(:stop_treatment_date, :cannot_precede_birth_date) base_errors['treatments'] = [:precede_birth_date, { :thing => I18n.t(:treatment) }] end end risk_factor = self.interested_party.risk_factor if (date = risk_factor.try(:pregnancy_due_date).try(:to_date)) && (date < bdate) risk_factor.errors.add(:pregnancy_due_date, :cannot_precede_birth_date) base_errors['risk_factor'] = [:precede_birth_date, { :thing => I18n.t(:risk_factor) }] end if (date = self.disease_event.try(:disease_onset_date).try(:to_date)) && (date < bdate) self.disease_event.errors.add(:disease_onset_date, :cannot_precede_birth_date) base_errors['disease'] = [:precede_birth_date, { :thing => I18n.t(:disease) }] end if (date = self.disease_event.try(:date_diagnosed).try(:to_date)) && (date < bdate) self.disease_event.errors.add(:date_diagnosed, :cannot_precede_birth_date) base_errors['disease'] = [:precede_birth_date, { :thing => I18n.t(:disease) }] end self.labs.each do |l| l.lab_results.each do |lr| if (date = lr.collection_date.try(:to_date)) && (date < bdate) lr.errors.add(:collection_date, :cannot_precede_birth_date) base_errors['labs'] = [:precede_birth_date, { :thing => I18n.t(:lab_result) }] end if (date = lr.lab_test_date.try(:to_date)) && (date < bdate) lr.errors.add(:lab_test_date, :cannot_precede_birth_date) base_errors['labs'] = [:precede_birth_date, { :thing => I18n.t(:lab_result) }] end end end if (date = self.results_reported_to_clinician_date.try(:to_date)) && (date < bdate) self.errors.add(:results_reported_to_clinician_date, :cannot_precede_birth_date) end if (date = self.first_reported_PH_date.try(:to_date)) && (date < bdate) self.errors.add(:first_reported_PH_date, :cannot_precede_birth_date) end unless base_errors.empty? && self.errors.empty? base_errors.values.each { |msg| self.errors.add(:base, *msg) } end end end
# Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 The Collaborative Software Foundation # # This file is part of TriSano. # # TriSano is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # TriSano 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt. class HumanEvent < Event include Export::Cdc::HumanEvent extend NameAndBirthdateSearch validates_length_of :parent_guardian, :maximum => 255, :allow_blank => true validates_numericality_of :age_at_onset, :allow_nil => true, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 120, :only_integer => true, :message => :bad_range validates_date :event_onset_date before_validation :set_onset_date, :set_age_at_onset has_one :interested_party, :foreign_key => "event_id" has_many :labs, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy has_many :lab_results, :through => :labs has_many :hospitalization_facilities, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy has_many :hospitals_participations, :through => :hospitalization_facilities has_many :diagnostic_facilities, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy has_many :clinicians, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy belongs_to :participations_contact belongs_to :participations_encounter accepts_nested_attributes_for :interested_party accepts_nested_attributes_for :hospitalization_facilities, :allow_destroy => true, :reject_if => proc { |attrs| attrs["secondary_entity_id"].blank? && nested_attributes_blank?(attrs["hospitals_participation_attributes"]) } accepts_nested_attributes_for :clinicians, :allow_destroy => true, :reject_if => proc { |attrs| attrs.has_key?("person_entity_attributes") && attrs["person_entity_attributes"]["person_attributes"].all? { |k, v| if v == 'clinician' then true else v.blank? end } } accepts_nested_attributes_for :diagnostic_facilities, :allow_destroy => true, :reject_if => :place_and_canonical_address_blank? accepts_nested_attributes_for :labs, :allow_destroy => true, :reject_if => proc { |attrs| reject_or_rewrite_attrs(attrs) } accepts_nested_attributes_for :participations_contact, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } } accepts_nested_attributes_for :participations_encounter, :reject_if => proc { |attrs| attrs.all? { |k, v| ((k == "user_id") || (k == "encounter_location_type")) ? true : v.blank? } } after_save :associate_longitudinal_data class << self # Lab participations will either receive a place entity hash or a secondary_entity_id. # # Place entity hashes are received when the operation needs the flexibility to create # a new lab (place entity) in the system (automated staged messaging assignment). # # A secondary_entity_id will be received from drop-down select lists of labs in the UI. # # Both structures are inspected to determine nested-attribute rejection. If place # attributes are received, an attempt is made to reuse an existing entity to avoid # creating duplicates. def reject_or_rewrite_attrs(attrs) return true if (lab_place_attributes_blank?(attrs) && lab_result_attributes_blank?(attrs)) rewrite_attributes_to_reuse_place_entities(attrs) return false end def lab_place_attributes_blank?(attrs) if attrs["place_entity_attributes"] return attrs["place_entity_attributes"]["place_attributes"].all? { |k, v| v.blank? } else return attrs["secondary_entity_id"].blank? end end def lab_result_attributes_blank?(attrs) attrs["lab_results_attributes"].all? { |index, lab_result_attrs| nested_attributes_blank?(lab_result_attrs) } end def rewrite_attributes_to_reuse_place_entities(attrs) if attrs["place_entity_attributes"] place_attributes = attrs["place_entity_attributes"]["place_attributes"] existing_labs = Place.labs_by_name(place_attributes["name"]) unless existing_labs.empty? attrs["secondary_entity_id"] = existing_labs.first.entity_id attrs.delete("place_entity_attributes") else place_attributes["place_type_ids"] = [Code.lab_place_type_id] end end end def get_allowed_queues(queues, jurisdiction_ids) EventQueue.queues_for_jurisdictions(jurisdiction_ids).all(:conditions => {:id => queues}) end def get_states_and_descriptions new.states.collect do |state| OpenStruct.new :workflow_state => state, :description => state_description(state) end end def state_description(state) I18n.translate(state, :scope => [:workflow]) end def find_all_for_filtered_view(options) users_view_jurisdictions = options[:view_jurisdiction_ids] || [] return [] if users_view_jurisdictions.empty? where_clause = <<-SQL (NOT diseases.sensitive OR diseases.sensitive IS NULL OR jurisdictions.secondary_entity_id || secondary_jurisdiction_ids && ARRAY[#{(options[:access_sensitive_jurisdiction_ids] || []).join(',')}]::integer[]) SQL event_types = options[:event_types] || [] is_contact_search = event_types.include?('ContactEvent') is_contact_parent_search_only = false event_type_clause = "" if (is_contact_search && event_types.count == 1) # we are searching only for contact events whose parent events meet the search criteria is_contact_parent_search_only = true; event_type_clause << " AND (events.type = 'MorbidityEvent' OR events.type = 'AssessmentEvent')" elsif event_types.empty? event_type_clause << " AND (events.type = 'MorbidityEvent' OR events.type = 'ContactEvent' OR events.type = 'AssessmentEvent')" else event_types_clause = [] event_types.each { |event_type| event_types_clause << "events.type = '#{event_type}'" } event_type_clause << " AND (" event_type_clause << event_types_clause.join(" OR ") event_type_clause << ")" end states = options[:states] || [] if states.empty? where_clause << " AND workflow_state != 'not_routed'" else where_clause << " AND workflow_state IN (#{ states.map { |s| sanitize_sql_for_conditions(["'%s'", s]).untaint }.join(',') })" end if options[:diseases] where_clause << " AND disease_id IN (#{ options[:diseases].map { |d| sanitize_sql_for_conditions(["'%s'", d]).untaint }.join(',') })" end if options[:investigators] where_clause << " AND investigator_id IN (#{ options[:investigators].map { |i| sanitize_sql_for_conditions(["'%s'", i]).untaint }.join(',') })" end if options[:queues] queues = get_allowed_queues(options[:queues], users_view_jurisdictions) if queues.empty? raise(I18n.translate('no_queue_ids_returned')) else where_clause << " AND event_queue_id IN (#{ queues.map(&:id).join(',') })" end end if options[:do_not_show_deleted] where_clause << " AND events.deleted_at IS NULL" end order_direction = options[:order_direction].blank? ? 'ASC' : options[:order_direction] order_by_clause = case options[:order_by] when 'patient' "last_name #{order_direction}, first_name, disease_name, jurisdiction_short_name, workflow_state" when 'disease' "disease_name #{order_direction}, last_name, first_name, jurisdiction_short_name, workflow_state" when 'jurisdiction' "jurisdiction_short_name #{order_direction}, last_name, first_name, disease_name, workflow_state" when 'status' # Fortunately the event status code stored in the DB and the text the user sees mostly correspond to the same alphabetical ordering" "workflow_state #{order_direction}, last_name, first_name, disease_name, jurisdiction_short_name" when 'event_created' "events.created_at #{order_direction}, last_name, first_name, disease_name, jurisdiction_short_name, workflow_state" else "events.updated_at DESC" end users_view_jurisdictions_sanitized = users_view_jurisdictions.map do |j| sanitize_sql_for_conditions(["%d", j]).untaint end # Hard coding the query to wring out some speed. real_select = <<-SQL SELECT events.id AS id, events.event_onset_date AS event_onset_date, events.created_at AS created_at, events.type AS type, events.deleted_at AS deleted_at, events.workflow_state as workflow_state, events.investigator_id as investigator_id, events.event_queue_id as event_queue_id, entities.id AS entity_id, people.first_name AS first_name, people.last_name AS last_name, diseases.disease_name AS disease_name, jurisdiction_entities.id AS jurisdiction_entity_id, jurisdiction_places.short_name AS jurisdiction_short_name, sec_juris.secondary_jurisdiction_names AS secondary_jurisdictions, CASE WHEN users.given_name IS NOT NULL AND users.given_name != '' THEN users.given_name WHEN users.last_name IS NOT NULL AND users.last_name != '' THEN trim(BOTH ' ' FROM users.first_name || ' ' || users.last_name) WHEN users.user_name IS NOT NULL AND users.user_name != '' THEN users.user_name ELSE users.uid END AS investigator_name, event_queues.queue_name as queue_name, people.middle_name as middle_name FROM events INNER JOIN participations ON participations.event_id = events.id AND (participations.type = 'InterestedParty' ) INNER JOIN entities ON entities.id = participations.primary_entity_id AND (entities.entity_type = 'PersonEntity' ) INNER JOIN people ON people.entity_id = entities.id LEFT OUTER JOIN disease_events ON disease_events.event_id = events.id LEFT OUTER JOIN diseases ON disease_events.disease_id = diseases.id INNER JOIN participations AS jurisdictions ON jurisdictions.event_id = events.id AND (jurisdictions.type = 'Jurisdiction') AND (jurisdictions.secondary_entity_id IN (#{users_view_jurisdictions_sanitized.join(',')})) INNER JOIN entities AS jurisdiction_entities ON jurisdiction_entities.id = jurisdictions.secondary_entity_id AND (jurisdiction_entities.entity_type = 'PlaceEntity') INNER JOIN places AS jurisdiction_places ON jurisdiction_places.entity_id = jurisdiction_entities.id LEFT JOIN ( SELECT event_id, CASE WHEN secondary_jurisdiction_names_inner IS DISTINCT FROM ARRAY[NULL]::varchar[] THEN secondary_jurisdiction_names_inner ELSE ARRAY[]::varchar[] END AS secondary_jurisdiction_names, CASE WHEN secondary_jurisdiction_ids_inner IS DISTINCT FROM ARRAY[NULL]::integer[] THEN secondary_jurisdiction_ids_inner ELSE ARRAY[]::integer[] END AS secondary_jurisdiction_ids FROM ( SELECT events.id AS event_id, ARRAY_ACCUM(places.short_name) AS secondary_jurisdiction_names_inner, ARRAY_ACCUM(pe.id) AS secondary_jurisdiction_ids_inner FROM events LEFT JOIN participations p ON (p.event_id = events.id AND p.type = 'AssociatedJurisdiction') LEFT JOIN entities pe ON pe.id = p.secondary_entity_id LEFT JOIN places ON places.entity_id = pe.id GROUP BY events.id ) sec_juris_inner ) sec_juris ON (sec_juris.event_id = events.id) LEFT JOIN users ON users.id = events.investigator_id LEFT JOIN event_queues ON event_queues.id = events.event_queue_id SQL # The paginate plugin needs a total row count. Normally it would simply re-execute the main query wrapped in a count(*). # But in an effort to shave off some more time, we will provide a row count with this simplified version of the main # query. count_select = <<-SQL SELECT COUNT(*) FROM events INNER JOIN participations AS jurisdictions ON jurisdictions.event_id = events.id AND (jurisdictions.type = 'Jurisdiction') AND (jurisdictions.secondary_entity_id IN (#{users_view_jurisdictions.join(',')})) LEFT OUTER JOIN disease_events ON disease_events.event_id = events.id LEFT OUTER JOIN diseases ON disease_events.disease_id = diseases.id LEFT JOIN users ON users.id = events.investigator_id LEFT JOIN event_queues ON event_queues.id = events.event_queue_id LEFT JOIN ( SELECT event_id, CASE WHEN secondary_jurisdiction_ids_inner IS DISTINCT FROM ARRAY[NULL]::integer[] THEN secondary_jurisdiction_ids_inner ELSE ARRAY[]::integer[] END AS secondary_jurisdiction_ids FROM ( SELECT events.id AS event_id, ARRAY_ACCUM(p.secondary_entity_id) AS secondary_jurisdiction_ids_inner FROM events LEFT JOIN participations p ON (p.event_id = events.id AND p.type = 'AssociatedJurisdiction') GROUP BY events.id ) sec_juris_inner ) sec_juris ON (sec_juris.event_id = events.id) SQL real_select_temp = real_select.dup count_select_temp = count_select.dup where_clause_temp = where_clause + event_type_clause count_select << "WHERE (#{where_clause_temp})\n" unless where_clause_temp.blank? real_select << "WHERE (#{where_clause_temp})\n" unless where_clause_temp.blank? real_select << "ORDER BY #{order_by_clause}" if (is_contact_search) # change the select criteria to include contact events whose parents meet the search critera event_ids = Event.find_by_sql(real_select).map {|x| x.id} if (event_ids.count > 0) event_list = '' is_first = true event_ids.each do |id| if !is_first event_list += ',' end is_first = false event_list += id.to_s end #if we are searching only for contact events whose parents meet the search criteria contact_clause = "(events.type = 'ContactEvent' AND (events.parent_id IN (" + event_list + ")))" if (is_contact_parent_search_only) expanded_where_clause = "WHERE (#{contact_clause})\n" else # searching for parent events that meet the search critera and contact events whose parents meet the search criteria expanded_where_clause = "WHERE " + (where_clause_temp.blank? ? "#{contact_clause}" : "((#{where_clause_temp}) OR #{contact_clause})" ) end real_select_temp << expanded_where_clause real_select_temp << "ORDER BY #{order_by_clause}" real_select = real_select_temp count_select_temp << expanded_where_clause count_select = count_select_temp end end row_count = Event.count_by_sql(count_select) find_options = { :page => options[:page], :total_entries => row_count } find_options[:per_page] = options[:per_page] if options[:per_page].to_i > 0 Event.paginate_by_sql(real_select, find_options) rescue Exception => ex logger.error ex raise ex end end def definitive_lab_date labs.collect do |l| l.lab_results.collect do |r| r.collection_date || r.lab_test_date end end.flatten.compact.sort.first end def set_primary_entity_on_secondary_participations self.participations.each do |participation| if participation.primary_entity_id.nil? participation.update_attribute('primary_entity_id', self.interested_party.person_entity.id) end end end def party @party ||= self.safe_call_chain(:interested_party, :person_entity, :person) end def copy_from_person(person) self.suppress_validation(:first_reported_PH_date) self.build_jurisdiction self.build_interested_party self.jurisdiction.secondary_entity = (User.current_user.jurisdictions_for_privilege(:create_event).first || Place.unassigned_jurisdiction).entity self.interested_party.primary_entity_id = person.id self.interested_party.person_entity = person self.address = person.canonical_address end # Perform a shallow (event_coponents = nil) or deep (event_components != nil) copy of an event. # Can't simply do a single clone or a series of clones because there are some attributes we need # to leave behind, certain relationships that need to be severed, and we need to make a copy of # the address for longitudinal purposes. def copy_event(new_event, event_components) super(new_event, event_components) org_entity = self.interested_party.person_entity new_event.build_interested_party(:primary_entity_id => org_entity.id) entity_address = org_entity.addresses.find(:first, :conditions => ['event_id = ?', self.id], :order => 'created_at DESC') new_event.address = entity_address ? entity_address.clone : nil new_event.imported_from_id = self.imported_from_id new_event.parent_guardian = self.parent_guardian new_event.other_data_1 = self.other_data_1 new_event.other_data_2 = self.other_data_2 return unless event_components # Shallow, demographics only, copy # If event_components is not nil, then continue on with a deep copy if event_components.include?("clinical") self.hospitalization_facilities.each do |h| new_h = new_event.hospitalization_facilities.build(:secondary_entity_id => h.secondary_entity_id) unless h.hospitals_participation.nil? if attrs = h.hospitals_participation.attributes attrs.delete('participation_id') new_h.build_hospitals_participation(attrs) end end end self.interested_party.treatments.each do |t| attrs = t.attributes attrs.delete('participation_id') new_event.interested_party.treatments.build(attrs) end if rf = self.interested_party.risk_factor attrs = self.interested_party.risk_factor.attributes attrs.delete('participation_id') new_event.interested_party.build_risk_factor(attrs) end self.clinicians.each do |c| new_event.clinicians.build(:secondary_entity_id => c.secondary_entity_id) end self.diagnostic_facilities.each do |d| new_event.diagnostic_facilities.build(:secondary_entity_id => d.secondary_entity_id) end end if event_components.include?("lab") self.labs.each do |l| lab = new_event.labs.build(:secondary_entity_id => l.secondary_entity_id) l.lab_results.each do |lr| attrs = lr.attributes attrs.delete('participation_id') lab.lab_results.build(attrs) end end end end def update_from_params(event_params) if !self.try(:disease_event).nil? and event_params.has_key?('disease_event_attributes') event_params['disease_event_attributes']['id'] = self.disease_event.id end self.attributes = event_params end def state_description I18n.t(state, :scope => [:workflow]) end # Debt: some stuff here gets written to the database, and some still # requires the event to be saved. def route_to_jurisdiction(jurisdiction, secondary_jurisdiction_ids=[], note="") return false unless valid? primary_changed = false jurisdiction_id = jurisdiction.to_i if jurisdiction.respond_to?('to_i') jurisdiction_id = jurisdiction.id if jurisdiction.is_a? Entity jurisdiction_id = jurisdiction.entity_id if jurisdiction.is_a? Place transaction do # Handle the primary jurisdiction # # Do nothing if the passed-in jurisdiction is the current jurisdiction unless jurisdiction_id == self.jurisdiction.secondary_entity_id proposed_jurisdiction = PlaceEntity.jurisdictions.find(jurisdiction_id) raise(I18n.translate('new_jurisdiction_is_not_jurisdiction')) unless proposed_jurisdiction self.jurisdiction.update_attribute(:place_entity, proposed_jurisdiction) self.add_note note primary_changed = true end # Handle secondary jurisdictions existing_secondary_jurisdiction_ids = associated_jurisdictions.collect { |participation| participation.secondary_entity_id } # if an existing secondary jurisdiction ID is not in the passed-in ids, delete (existing_secondary_jurisdiction_ids - secondary_jurisdiction_ids).each do |id_to_delete| associated_jurisdictions.delete(associated_jurisdictions.find_by_secondary_entity_id(id_to_delete)) end # if an passed-in ID is not in the existing secondary jurisdiction IDs, add (secondary_jurisdiction_ids - existing_secondary_jurisdiction_ids).each do |id_to_add| associated_jurisdictions.create(:secondary_entity_id => id_to_add) end self.add_forms(self.available_forms) if self.can_receive_auto_assigned_forms? reload # Any existing references to this object won't see these changes without this end primary_changed end # transitions that are allowed to be rendered by this user def allowed_transitions current_state.events.select do |event| priv_required = current_state.events(event).meta[:priv_required] next if priv_required.nil? j_id = jurisdiction.secondary_entity_id User.current_user.is_entitled_to_in?(priv_required, j_id) end end def undo_workflow_side_effects attrs = { :investigation_started_date => nil, :investigation_completed_LHD_date => nil, :review_completed_by_state_date => nil } case self.state when :assigned_to_lhd attrs[:investigator_id] = nil attrs[:event_queue_id] = nil end self.update_attributes(attrs) end def add_labs_from_staged_message(staged_message) raise(ArgumentError, I18n.translate('not_a_valid_staged_message', :staged_message => staged_message.class)) unless staged_message.respond_to?('message_header') # All tests have a scale type. The scale type is well known and is part of the standard LOINC code data given in the SCALE_TYP # field. TriSano keeps the scale type in the loinc_codes table scale column. # # There are four scale types that we care about: ordinal (Ord: one of X), nominal (Nom: a string), quantitative (Qn: a number), # and ordinal or quantitative (OrdQn). # # An ordinal test result has values such as Positive or Reactive. E.g. the lab was positive for HIV # # A quantitative test result has a value such as 100 or .5, which when combined with the units field gives a meaningful result. # E.g, the lab showed a hemoglobin count of 13.0 Gm/Dl. # # A nominal test result has a string. In TriSano we are currently making the assumption that this is an organism name. # E.g the blood culture showed the influenza virus. # # An ordinal/quantiative test is either an ordinal string or a number # # These three principal (not including OrdQn) types of test results are, ideally, mapped to three different fields: # # Ord -> test_result_id # Qn -> result_value # Nom -> organism_id # # In the case or Ord and Nom, if the value can't be mapped because the provided value does not match TriSano values, # e.g., the ordinal value is "Affirmative" instead of "Positive", then the result is placed in the result_value field, # rather than not mapping it at all. This has the side effect of making an OrdQn the same as an Ord. # # In addition to organisms specified directly for nominal tests, ordinal and quantitative tests can have organisms too. # TriSano maintains a loinc code to organism relationship in the database # Set the lab name @lab_attributes = { "place_entity_attributes"=> { "place_attributes"=> { "name"=> staged_message.lab_name } }, "lab_results_attributes" => {} } # Create one lab result per OBX segment i = 0 @diseases = Set.new # country per_message_comments = '' unless staged_message.patient.address_country.blank? per_message_comments = "#{I18n.translate :country}: #{staged_message.patient.address_country}" end pv1 = staged_message.pv1 orc = staged_message.common_order find_or_build_clinician(orc.clinician_last_name, orc.clinician_first_name, orc.clinician_phone_type, orc.clinician_telephone) unless orc.nil? or orc.clinician_last_name.blank? find_or_build_clinician(staged_message.pv1.attending_doctor[0], staged_message.pv1.attending_doctor[1]) unless pv1.nil? or pv1.attending_doctor.blank? find_or_build_clinician(staged_message.pv1.consulting_doctor[0], staged_message.pv1.consulting_doctor[1]) unless pv1.nil? or pv1.consulting_doctor.blank? staged_message.observation_requests.each do |obr| find_or_build_clinician(obr.clinician_last_name, obr.clinician_first_name, obr.clinician_phone_type, obr.clinician_telephone) unless obr.clinician_last_name.blank? @per_request_comments = per_message_comments.clone unless obr.specimen_id.blank? @per_request_comments += ", " unless @per_request_comments.blank? @per_request_comments += "#{I18n.translate :specimen_id}: #{obr.specimen_id}" end unless obr.specimen_source_2_5_1.blank? and obr.specimen_source_2_3_1.blank? @per_request_comments += ", " unless @per_request_comments.blank? @per_request_comments += "#{I18n.translate :specimen_source}: #{obr.specimen_source_2_5_1 || obr.specimen_source_2_3_1}" end obr.tests.each do |obx| set_loinc_scale_and_test_type obx if @scale_type.nil? self.add_note I18n.translate(:unknown_loinc_code, :loinc_code => obx.loinc_code) next end if @common_test_type.nil? self.add_note I18n.translate(:loinc_code_known_but_not_linked, :loinc_code => obx.loinc_code) next end add_lab_results staged_message, obr, obx, i i += 1 self.add_note(I18n.translate("system_notes.elr_with_test_type_assigned", :test_type => obx.test_type, :locale => I18n.default_locale)) end # Grab any diseases associated with this OBR loinc_code = LoincCode.find_by_loinc_code obr.test_performed loinc_code.diseases.each { |disease| @diseases << disease } if loinc_code and @diseases.blank? end unless i > 0 # All OBX invalid raise StagedMessage::UnknownLoincCode, I18n.translate(:all_obx_unprocessable) end self.labs_attributes = [ @lab_attributes ] # Assign disease unless self.disease_event # Don't overwrite disease if already there. case @diseases.size when 0 staged_message.note = "#{staged_message.note} #{I18n.translate('no_loinc_code_maps_to_disease', :locale => I18n.default_locale)} " when 1 disease_event = DiseaseEvent.new disease_event.disease = @diseases.to_a.first self.build_disease_event(disease_event.attributes) staged_message.note = "#{staged_message.note} #{I18n.translate('event_disease_set_to', :disease_name => disease_event.disease.disease_name, :locale => I18n.default_locale)} " else staged_message.note = "#{staged_message.note} #{I18n.translate('loinc_code_maps_to_multiple_diseases', :locale => I18n.default_locale)}" + @diseases.collect { |d| d.disease_name }.join('; ') + ". " end end unless staged_message.patient.primary_language.blank? or interested_party.nil? or interested_party.person_entity.person.primary_language_id staged_message.note ||= '' staged_message.note.sub! /\s+$/, '' staged_message.note += '. ' if staged_message.note.length > 0 staged_message.note += I18n.translate :unmapped_language_code, :lang_code => staged_message.patient.primary_language, :locale => I18n.default_locale end unless staged_message.patient.dead_flag.blank? or disease_event.nil? code = case staged_message.patient.dead_flag when 'Y' ExternalCode.yes when 'N' ExternalCode.no end self.disease_event.died_id = code.id end if staged_message.common_order diagnostic_facility_name = staged_message.common_order.facility_name orc = staged_message.common_order unless diagnostic_facility_name.blank? place_entity = find_or_build_hospital(diagnostic_facility_name) place_entity.build_canonical_address(:street_number => orc.facility_address_street_no, :street_name => orc.facility_address_street, :city => orc.facility_address_city, :state_id => orc.facility_address_trisano_state_id, :postal_code => orc.facility_address_zip) unless orc.facility_address_empty? self.diagnostic_facilities.build :place_entity => place_entity end end unless disease_event.nil? or staged_message.pv1.blank? or staged_message.pv1.hospitalized_id.nil? hospitalized_id = staged_message.pv1.hospitalized_id self.disease_event.hospitalized_id = hospitalized_id if hospitalized_id == ExternalCode.yes.id facility_name = staged_message.pv2.facility_name if staged_message.pv2 facility_name = staged_message.common_order.facility_name if facility_name.blank? and staged_message.common_order unless facility_name.blank? place_entity = find_or_build_hospital(facility_name) self.hospitalization_facilities.build :place_entity => place_entity end end end self.parent_guardian = staged_message.next_of_kin.parent_guardian.slice(0,2).join(', ') if staged_message.next_of_kin end def find_or_build_hospital(place_name) # assign the facility name, which requires finding or building a # place # do we already have this? place_entity = PlaceEntity.find(:first, :conditions => [ "entities.deleted_at IS NULL AND LOWER(places.name) = ?", place_name.downcase ], :include => :place) # no? create it place_entity ||= PlaceEntity.new :place_attributes => { :name => place_name.titleize, :short_name => place_name.titleize } # make it a hospital place_code = Code.find_by_code_name_and_the_code('placetype', 'H') place_entity.place.place_types << place_code unless place_entity.place.place_types.include?(place_code) place_entity end def possible_treatments(reload=false) if reload or @possible_treatments.nil? options = { :select => 'distinct treatments.*', :order => 'treatment_name' } if disease = disease_event.try(:disease) options[:joins] = 'LEFT JOIN disease_specific_treatments b ON b.treatment_id = treatments.id' options[:conditions] = [<<-SQL, disease.id, self.id] (active = true AND disease_id = ?) OR treatments.id IN ( SELECT treatment_id FROM participations_treatments a JOIN participations b ON b.id = a.participation_id AND b.event_id = ?) SQL else options[:conditions] = [<<-SQL, self.id] ("default" = true AND active = true) OR id IN ( SELECT treatment_id FROM participations_treatments a JOIN participations b ON b.id = a.participation_id AND b.event_id = ?) SQL end @possible_treatments = Treatment.all(options) end @possible_treatments end private def add_lab_results(staged_message, obr, obx, i) comments = @per_request_comments.clone unless obx.abnormal_flags.blank? comments += ", " unless comments.blank? comments += "#{I18n.translate :abnormal_flags}: #{obx.abnormal_flags}" end comments += ", " unless comments.blank? comments += "Observation value: #{obx.obx_segment.observation_value}" result_hash = {} if @scale_type != "Nom" if @loinc_code.organism result_hash["organism_id"] = @loinc_code.organism.id else comments += ", " unless comments.blank? comments += "ELR Message: No organism mapped to LOINC code." end @loinc_code.diseases.each { |disease| @diseases << disease } end case @scale_type when "Ord", "OrdQn" obx_result = obx.result.gsub(/\s/, '').downcase if map_id = result_map[obx_result] result_hash["test_result_id"] = map_id else result_hash["result_value"] = obx.result end when "Qn" result_hash["result_value"] = obx.result when "Nom" # Try and find OBX-5 in the organism list, otherwise map to result_value # Eventually, we'll need to add more heuristics here for SNOMED etc. organism = Organism.first(:conditions => [ "organism_name ~* ?", '^'+obx.result+'$' ]) if organism.blank? result_hash["result_value"] = obx.result else result_hash["organism_id"] = organism.id organism.diseases.each { |disease| @diseases << disease } end end begin lab_hash = { "test_type_id" => @common_test_type.id, "collection_date" => obr.collection_date, "lab_test_date" => obx.test_date, "reference_range" => obx.reference_range, "specimen_source_id" => obr.specimen_source.id, "staged_message_id" => staged_message.id, "units" => obx.units, "test_status_id" => obx.trisano_status_id, "loinc_code" => @loinc_code, "comment" => comments }.merge!(result_hash) unless obr.filler_order_number.blank? lab_hash["accession_no"] = obr.filler_order_number end @lab_attributes["lab_results_attributes"][i.to_s] = lab_hash rescue Exception => error raise StagedMessage::BadMessageFormat, error.message end end def set_loinc_scale_and_test_type(obx) @loinc_code = LoincCode.find_by_loinc_code obx.loinc_code @scale_type = nil @common_test_type = nil if @loinc_code @scale_type = @loinc_code.scale.the_code @common_test_type = @loinc_code.common_test_type || CommonTestType.find_by_common_name(obx.loinc_common_test_type) else # No :loinc_code entry. # Look at other OBX fields for hints to the scale and common # test type. @scale_type = obx.loinc_scale common_test_type_name = obx.loinc_common_test_type @common_test_type = CommonTestType.find_by_common_name(common_test_type_name) if common_test_type_name end end def result_map self.class.result_map end class << self def result_map # For ordinal tests, a single result has multiple synonyms, such as: "Positive", " Confirmed", " Detected", " Definitive" # So, first load the TriSano test_results, then bust out the slash-separated synonyms into hash keys whose value is the test_result ID. # I.e: { "Positive" => 1, "Confirmed" => 1, "Negative" => 2, ... } unless @result_map test_results = ExternalCode.find_all_by_code_name("test_result") @result_map = {} test_results.each do |result| result.code_description.split('/').each do |component| @result_map[component.gsub(/\s/, '').downcase] = result.id end if result.code_description end end @result_map end end def find_or_build_clinician(last_name, first_name, telephone_type=nil, telephone=nil) person_attributes = { :last_name => last_name , :first_name => first_name, :person_type => 'clinician' } person = Person.first :conditions => person_attributes if person person_entity_id = person.person_entity.id @clinician = clinicians.to_a.find do |c| c.secondary_entity_id == person_entity_id end @clinician ||= clinicians.build :secondary_entity_id => person_entity_id else @clinician = clinicians.to_a.find do |c| c.person_entity.person.last_name == last_name && c.person_entity.person.first_name == first_name end @clinician ||= clinicians.build :person_entity_attributes => { :person_attributes => person_attributes } end unless telephone_type.nil? or telephone.blank? or telephone.all? {|x|x.nil?} area_code, number, extension = telephone telephone_attributes = { :entity_location_type => telephone_type, :area_code => area_code, :phone_number => number, :extension => extension } @clinician.person_entity.telephones.to_a.find do |t| t.entity_location_type == telephone_type && t.area_code == area_code && t.phone_number == number && t.extension == extension end or @clinician.person_entity.telephones.build(telephone_attributes) end @clinician rescue end def set_age_at_onset birthdate = safe_call_chain(:interested_party, :person_entity, :person, :birth_date) self.age_info = AgeInfo.create_from_dates(birthdate, self.event_onset_date) end def set_onset_date self.event_onset_date = resolve_onset_date end def resolve_onset_date safe_call_chain(:disease_event, :disease_onset_date) || safe_call_chain(:disease_event, :date_diagnosed) || definitive_lab_date || self.first_reported_PH_date || self.created_at.try(:to_date) || Date.today end def validate super county_jurisdiction = self.address.try(:county).try(:jurisdiction) if county_jurisdiction == Jurisdiction.out_of_state && (((self.lhd_case_status != ExternalCode.out_of_state) && (!self.lhd_case_status.nil?)) && ((self.state_case_status != ExternalCode.out_of_state) && (!self.state_case_status.nil?))) errors.add(:base, :invalid_case_status, :status => ExternalCode.out_of_state.code_description, :attr => I18n.t(:county).downcase, :value => self.address.county.code_description) end return if self.interested_party.nil? return unless bdate = self.interested_party.person_entity.try(:person).try(:birth_date) base_errors = {} self.hospitalization_facilities.each do |hf| if (date = hf.hospitals_participation.try(:admission_date).try(:to_date)) && (date < bdate) hf.hospitals_participation.errors.add(:admission_date, :cannot_precede_birth_date) base_errors['hospitals'] = [:precede_birth_date, {:thing => I18n.t(:hospitalization)}] end if (date = hf.hospitals_participation.try(:discharge_date).try(:to_date)) && (date < bdate) hf.hospitals_participation.errors.add(:discharge_date, :cannot_precede_birth_date) base_errors['hospitals'] = [:precede_birth_date, { :thing => I18n.t(:hospitalization) }] end end self.interested_party.treatments.each do |t| if (date = t.treatment_date.try(:to_date)) && (date < bdate) t.errors.add(:treatment_date, :cannot_precede_birth_date) base_errors['treatments'] = [:precede_birth_date, { :thing => I18n.t(:treatment) }] end if (date = t.stop_treatment_date.try(:to_date)) && (date < bdate) t.errors.add(:stop_treatment_date, :cannot_precede_birth_date) base_errors['treatments'] = [:precede_birth_date, { :thing => I18n.t(:treatment) }] end end risk_factor = self.interested_party.risk_factor if (date = risk_factor.try(:pregnancy_due_date).try(:to_date)) && (date < bdate) risk_factor.errors.add(:pregnancy_due_date, :cannot_precede_birth_date) base_errors['risk_factor'] = [:precede_birth_date, { :thing => I18n.t(:risk_factor) }] end if (date = self.disease_event.try(:disease_onset_date).try(:to_date)) && (date < bdate) self.disease_event.errors.add(:disease_onset_date, :cannot_precede_birth_date) base_errors['disease'] = [:precede_birth_date, { :thing => I18n.t(:disease) }] end if (date = self.disease_event.try(:date_diagnosed).try(:to_date)) && (date < bdate) self.disease_event.errors.add(:date_diagnosed, :cannot_precede_birth_date) base_errors['disease'] = [:precede_birth_date, { :thing => I18n.t(:disease) }] end self.labs.each do |l| l.lab_results.each do |lr| if (date = lr.collection_date.try(:to_date)) && (date < bdate) lr.errors.add(:collection_date, :cannot_precede_birth_date) base_errors['labs'] = [:precede_birth_date, { :thing => I18n.t(:lab_result) }] end if (date = lr.lab_test_date.try(:to_date)) && (date < bdate) lr.errors.add(:lab_test_date, :cannot_precede_birth_date) base_errors['labs'] = [:precede_birth_date, { :thing => I18n.t(:lab_result) }] end end end if (date = self.results_reported_to_clinician_date.try(:to_date)) && (date < bdate) self.errors.add(:results_reported_to_clinician_date, :cannot_precede_birth_date) end if (date = self.first_reported_PH_date.try(:to_date)) && (date < bdate) self.errors.add(:first_reported_PH_date, :cannot_precede_birth_date) end unless base_errors.empty? && self.errors.empty? base_errors.values.each { |msg| self.errors.add(:base, *msg) } end end def associate_longitudinal_data if address address.update_attributes(:entity_id => interested_party.primary_entity_id) end end end fix bug with cache not being cleared for event save # Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 The Collaborative Software Foundation # # This file is part of TriSano. # # TriSano is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # TriSano 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt. class HumanEvent < Event include Export::Cdc::HumanEvent extend NameAndBirthdateSearch validates_length_of :parent_guardian, :maximum => 255, :allow_blank => true validates_numericality_of :age_at_onset, :allow_nil => true, :greater_than_or_equal_to => 0, :less_than_or_equal_to => 120, :only_integer => true, :message => :bad_range validates_date :event_onset_date before_validation :set_onset_date, :set_age_at_onset has_one :interested_party, :foreign_key => "event_id" has_many :labs, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy has_many :lab_results, :through => :labs has_many :hospitalization_facilities, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy has_many :hospitals_participations, :through => :hospitalization_facilities has_many :diagnostic_facilities, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy has_many :clinicians, :foreign_key => "event_id", :order => 'created_at ASC', :dependent => :destroy belongs_to :participations_contact belongs_to :participations_encounter accepts_nested_attributes_for :interested_party accepts_nested_attributes_for :hospitalization_facilities, :allow_destroy => true, :reject_if => proc { |attrs| attrs["secondary_entity_id"].blank? && nested_attributes_blank?(attrs["hospitals_participation_attributes"]) } accepts_nested_attributes_for :clinicians, :allow_destroy => true, :reject_if => proc { |attrs| attrs.has_key?("person_entity_attributes") && attrs["person_entity_attributes"]["person_attributes"].all? { |k, v| if v == 'clinician' then true else v.blank? end } } accepts_nested_attributes_for :diagnostic_facilities, :allow_destroy => true, :reject_if => :place_and_canonical_address_blank? accepts_nested_attributes_for :labs, :allow_destroy => true, :reject_if => proc { |attrs| reject_or_rewrite_attrs(attrs) } accepts_nested_attributes_for :participations_contact, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } } accepts_nested_attributes_for :participations_encounter, :reject_if => proc { |attrs| attrs.all? { |k, v| ((k == "user_id") || (k == "encounter_location_type")) ? true : v.blank? } } after_save :associate_longitudinal_data, :purge_event_from_cache class << self # Lab participations will either receive a place entity hash or a secondary_entity_id. # # Place entity hashes are received when the operation needs the flexibility to create # a new lab (place entity) in the system (automated staged messaging assignment). # # A secondary_entity_id will be received from drop-down select lists of labs in the UI. # # Both structures are inspected to determine nested-attribute rejection. If place # attributes are received, an attempt is made to reuse an existing entity to avoid # creating duplicates. def reject_or_rewrite_attrs(attrs) return true if (lab_place_attributes_blank?(attrs) && lab_result_attributes_blank?(attrs)) rewrite_attributes_to_reuse_place_entities(attrs) return false end def lab_place_attributes_blank?(attrs) if attrs["place_entity_attributes"] return attrs["place_entity_attributes"]["place_attributes"].all? { |k, v| v.blank? } else return attrs["secondary_entity_id"].blank? end end def lab_result_attributes_blank?(attrs) attrs["lab_results_attributes"].all? { |index, lab_result_attrs| nested_attributes_blank?(lab_result_attrs) } end def rewrite_attributes_to_reuse_place_entities(attrs) if attrs["place_entity_attributes"] place_attributes = attrs["place_entity_attributes"]["place_attributes"] existing_labs = Place.labs_by_name(place_attributes["name"]) unless existing_labs.empty? attrs["secondary_entity_id"] = existing_labs.first.entity_id attrs.delete("place_entity_attributes") else place_attributes["place_type_ids"] = [Code.lab_place_type_id] end end end def get_allowed_queues(queues, jurisdiction_ids) EventQueue.queues_for_jurisdictions(jurisdiction_ids).all(:conditions => {:id => queues}) end def get_states_and_descriptions new.states.collect do |state| OpenStruct.new :workflow_state => state, :description => state_description(state) end end def state_description(state) I18n.translate(state, :scope => [:workflow]) end def find_all_for_filtered_view(options) users_view_jurisdictions = options[:view_jurisdiction_ids] || [] return [] if users_view_jurisdictions.empty? where_clause = <<-SQL (NOT diseases.sensitive OR diseases.sensitive IS NULL OR jurisdictions.secondary_entity_id || secondary_jurisdiction_ids && ARRAY[#{(options[:access_sensitive_jurisdiction_ids] || []).join(',')}]::integer[]) SQL event_types = options[:event_types] || [] is_contact_search = event_types.include?('ContactEvent') is_contact_parent_search_only = false event_type_clause = "" if (is_contact_search && event_types.count == 1) # we are searching only for contact events whose parent events meet the search criteria is_contact_parent_search_only = true; event_type_clause << " AND (events.type = 'MorbidityEvent' OR events.type = 'AssessmentEvent')" elsif event_types.empty? event_type_clause << " AND (events.type = 'MorbidityEvent' OR events.type = 'ContactEvent' OR events.type = 'AssessmentEvent')" else event_types_clause = [] event_types.each { |event_type| event_types_clause << "events.type = '#{event_type}'" } event_type_clause << " AND (" event_type_clause << event_types_clause.join(" OR ") event_type_clause << ")" end states = options[:states] || [] if states.empty? where_clause << " AND workflow_state != 'not_routed'" else where_clause << " AND workflow_state IN (#{ states.map { |s| sanitize_sql_for_conditions(["'%s'", s]).untaint }.join(',') })" end if options[:diseases] where_clause << " AND disease_id IN (#{ options[:diseases].map { |d| sanitize_sql_for_conditions(["'%s'", d]).untaint }.join(',') })" end if options[:investigators] where_clause << " AND investigator_id IN (#{ options[:investigators].map { |i| sanitize_sql_for_conditions(["'%s'", i]).untaint }.join(',') })" end if options[:queues] queues = get_allowed_queues(options[:queues], users_view_jurisdictions) if queues.empty? raise(I18n.translate('no_queue_ids_returned')) else where_clause << " AND event_queue_id IN (#{ queues.map(&:id).join(',') })" end end if options[:do_not_show_deleted] where_clause << " AND events.deleted_at IS NULL" end order_direction = options[:order_direction].blank? ? 'ASC' : options[:order_direction] order_by_clause = case options[:order_by] when 'patient' "last_name #{order_direction}, first_name, disease_name, jurisdiction_short_name, workflow_state" when 'disease' "disease_name #{order_direction}, last_name, first_name, jurisdiction_short_name, workflow_state" when 'jurisdiction' "jurisdiction_short_name #{order_direction}, last_name, first_name, disease_name, workflow_state" when 'status' # Fortunately the event status code stored in the DB and the text the user sees mostly correspond to the same alphabetical ordering" "workflow_state #{order_direction}, last_name, first_name, disease_name, jurisdiction_short_name" when 'event_created' "events.created_at #{order_direction}, last_name, first_name, disease_name, jurisdiction_short_name, workflow_state" else "events.updated_at DESC" end users_view_jurisdictions_sanitized = users_view_jurisdictions.map do |j| sanitize_sql_for_conditions(["%d", j]).untaint end # Hard coding the query to wring out some speed. real_select = <<-SQL SELECT events.id AS id, events.event_onset_date AS event_onset_date, events.created_at AS created_at, events.type AS type, events.deleted_at AS deleted_at, events.workflow_state as workflow_state, events.investigator_id as investigator_id, events.event_queue_id as event_queue_id, entities.id AS entity_id, people.first_name AS first_name, people.last_name AS last_name, diseases.disease_name AS disease_name, jurisdiction_entities.id AS jurisdiction_entity_id, jurisdiction_places.short_name AS jurisdiction_short_name, sec_juris.secondary_jurisdiction_names AS secondary_jurisdictions, CASE WHEN users.given_name IS NOT NULL AND users.given_name != '' THEN users.given_name WHEN users.last_name IS NOT NULL AND users.last_name != '' THEN trim(BOTH ' ' FROM users.first_name || ' ' || users.last_name) WHEN users.user_name IS NOT NULL AND users.user_name != '' THEN users.user_name ELSE users.uid END AS investigator_name, event_queues.queue_name as queue_name, people.middle_name as middle_name FROM events INNER JOIN participations ON participations.event_id = events.id AND (participations.type = 'InterestedParty' ) INNER JOIN entities ON entities.id = participations.primary_entity_id AND (entities.entity_type = 'PersonEntity' ) INNER JOIN people ON people.entity_id = entities.id LEFT OUTER JOIN disease_events ON disease_events.event_id = events.id LEFT OUTER JOIN diseases ON disease_events.disease_id = diseases.id INNER JOIN participations AS jurisdictions ON jurisdictions.event_id = events.id AND (jurisdictions.type = 'Jurisdiction') AND (jurisdictions.secondary_entity_id IN (#{users_view_jurisdictions_sanitized.join(',')})) INNER JOIN entities AS jurisdiction_entities ON jurisdiction_entities.id = jurisdictions.secondary_entity_id AND (jurisdiction_entities.entity_type = 'PlaceEntity') INNER JOIN places AS jurisdiction_places ON jurisdiction_places.entity_id = jurisdiction_entities.id LEFT JOIN ( SELECT event_id, CASE WHEN secondary_jurisdiction_names_inner IS DISTINCT FROM ARRAY[NULL]::varchar[] THEN secondary_jurisdiction_names_inner ELSE ARRAY[]::varchar[] END AS secondary_jurisdiction_names, CASE WHEN secondary_jurisdiction_ids_inner IS DISTINCT FROM ARRAY[NULL]::integer[] THEN secondary_jurisdiction_ids_inner ELSE ARRAY[]::integer[] END AS secondary_jurisdiction_ids FROM ( SELECT events.id AS event_id, ARRAY_ACCUM(places.short_name) AS secondary_jurisdiction_names_inner, ARRAY_ACCUM(pe.id) AS secondary_jurisdiction_ids_inner FROM events LEFT JOIN participations p ON (p.event_id = events.id AND p.type = 'AssociatedJurisdiction') LEFT JOIN entities pe ON pe.id = p.secondary_entity_id LEFT JOIN places ON places.entity_id = pe.id GROUP BY events.id ) sec_juris_inner ) sec_juris ON (sec_juris.event_id = events.id) LEFT JOIN users ON users.id = events.investigator_id LEFT JOIN event_queues ON event_queues.id = events.event_queue_id SQL # The paginate plugin needs a total row count. Normally it would simply re-execute the main query wrapped in a count(*). # But in an effort to shave off some more time, we will provide a row count with this simplified version of the main # query. count_select = <<-SQL SELECT COUNT(*) FROM events INNER JOIN participations AS jurisdictions ON jurisdictions.event_id = events.id AND (jurisdictions.type = 'Jurisdiction') AND (jurisdictions.secondary_entity_id IN (#{users_view_jurisdictions.join(',')})) LEFT OUTER JOIN disease_events ON disease_events.event_id = events.id LEFT OUTER JOIN diseases ON disease_events.disease_id = diseases.id LEFT JOIN users ON users.id = events.investigator_id LEFT JOIN event_queues ON event_queues.id = events.event_queue_id LEFT JOIN ( SELECT event_id, CASE WHEN secondary_jurisdiction_ids_inner IS DISTINCT FROM ARRAY[NULL]::integer[] THEN secondary_jurisdiction_ids_inner ELSE ARRAY[]::integer[] END AS secondary_jurisdiction_ids FROM ( SELECT events.id AS event_id, ARRAY_ACCUM(p.secondary_entity_id) AS secondary_jurisdiction_ids_inner FROM events LEFT JOIN participations p ON (p.event_id = events.id AND p.type = 'AssociatedJurisdiction') GROUP BY events.id ) sec_juris_inner ) sec_juris ON (sec_juris.event_id = events.id) SQL real_select_temp = real_select.dup count_select_temp = count_select.dup where_clause_temp = where_clause + event_type_clause count_select << "WHERE (#{where_clause_temp})\n" unless where_clause_temp.blank? real_select << "WHERE (#{where_clause_temp})\n" unless where_clause_temp.blank? real_select << "ORDER BY #{order_by_clause}" if (is_contact_search) # change the select criteria to include contact events whose parents meet the search critera event_ids = Event.find_by_sql(real_select).map {|x| x.id} if (event_ids.count > 0) event_list = '' is_first = true event_ids.each do |id| if !is_first event_list += ',' end is_first = false event_list += id.to_s end #if we are searching only for contact events whose parents meet the search criteria contact_clause = "(events.type = 'ContactEvent' AND (events.parent_id IN (" + event_list + ")))" if (is_contact_parent_search_only) expanded_where_clause = "WHERE (#{contact_clause})\n" else # searching for parent events that meet the search critera and contact events whose parents meet the search criteria expanded_where_clause = "WHERE " + (where_clause_temp.blank? ? "#{contact_clause}" : "((#{where_clause_temp}) OR #{contact_clause})" ) end real_select_temp << expanded_where_clause real_select_temp << "ORDER BY #{order_by_clause}" real_select = real_select_temp count_select_temp << expanded_where_clause count_select = count_select_temp end end row_count = Event.count_by_sql(count_select) find_options = { :page => options[:page], :total_entries => row_count } find_options[:per_page] = options[:per_page] if options[:per_page].to_i > 0 Event.paginate_by_sql(real_select, find_options) rescue Exception => ex logger.error ex raise ex end end def definitive_lab_date labs.collect do |l| l.lab_results.collect do |r| r.collection_date || r.lab_test_date end end.flatten.compact.sort.first end def set_primary_entity_on_secondary_participations self.participations.each do |participation| if participation.primary_entity_id.nil? participation.update_attribute('primary_entity_id', self.interested_party.person_entity.id) end end end def party @party ||= self.safe_call_chain(:interested_party, :person_entity, :person) end def copy_from_person(person) self.suppress_validation(:first_reported_PH_date) self.build_jurisdiction self.build_interested_party self.jurisdiction.secondary_entity = (User.current_user.jurisdictions_for_privilege(:create_event).first || Place.unassigned_jurisdiction).entity self.interested_party.primary_entity_id = person.id self.interested_party.person_entity = person self.address = person.canonical_address end # Perform a shallow (event_coponents = nil) or deep (event_components != nil) copy of an event. # Can't simply do a single clone or a series of clones because there are some attributes we need # to leave behind, certain relationships that need to be severed, and we need to make a copy of # the address for longitudinal purposes. def copy_event(new_event, event_components) super(new_event, event_components) org_entity = self.interested_party.person_entity new_event.build_interested_party(:primary_entity_id => org_entity.id) entity_address = org_entity.addresses.find(:first, :conditions => ['event_id = ?', self.id], :order => 'created_at DESC') new_event.address = entity_address ? entity_address.clone : nil new_event.imported_from_id = self.imported_from_id new_event.parent_guardian = self.parent_guardian new_event.other_data_1 = self.other_data_1 new_event.other_data_2 = self.other_data_2 return unless event_components # Shallow, demographics only, copy # If event_components is not nil, then continue on with a deep copy if event_components.include?("clinical") self.hospitalization_facilities.each do |h| new_h = new_event.hospitalization_facilities.build(:secondary_entity_id => h.secondary_entity_id) unless h.hospitals_participation.nil? if attrs = h.hospitals_participation.attributes attrs.delete('participation_id') new_h.build_hospitals_participation(attrs) end end end self.interested_party.treatments.each do |t| attrs = t.attributes attrs.delete('participation_id') new_event.interested_party.treatments.build(attrs) end if rf = self.interested_party.risk_factor attrs = self.interested_party.risk_factor.attributes attrs.delete('participation_id') new_event.interested_party.build_risk_factor(attrs) end self.clinicians.each do |c| new_event.clinicians.build(:secondary_entity_id => c.secondary_entity_id) end self.diagnostic_facilities.each do |d| new_event.diagnostic_facilities.build(:secondary_entity_id => d.secondary_entity_id) end end if event_components.include?("lab") self.labs.each do |l| lab = new_event.labs.build(:secondary_entity_id => l.secondary_entity_id) l.lab_results.each do |lr| attrs = lr.attributes attrs.delete('participation_id') lab.lab_results.build(attrs) end end end end def update_from_params(event_params) if !self.try(:disease_event).nil? and event_params.has_key?('disease_event_attributes') event_params['disease_event_attributes']['id'] = self.disease_event.id end self.attributes = event_params end def state_description I18n.t(state, :scope => [:workflow]) end # Debt: some stuff here gets written to the database, and some still # requires the event to be saved. def route_to_jurisdiction(jurisdiction, secondary_jurisdiction_ids=[], note="") return false unless valid? primary_changed = false jurisdiction_id = jurisdiction.to_i if jurisdiction.respond_to?('to_i') jurisdiction_id = jurisdiction.id if jurisdiction.is_a? Entity jurisdiction_id = jurisdiction.entity_id if jurisdiction.is_a? Place transaction do # Handle the primary jurisdiction # # Do nothing if the passed-in jurisdiction is the current jurisdiction unless jurisdiction_id == self.jurisdiction.secondary_entity_id proposed_jurisdiction = PlaceEntity.jurisdictions.find(jurisdiction_id) raise(I18n.translate('new_jurisdiction_is_not_jurisdiction')) unless proposed_jurisdiction self.jurisdiction.update_attribute(:place_entity, proposed_jurisdiction) self.add_note note primary_changed = true end # Handle secondary jurisdictions existing_secondary_jurisdiction_ids = associated_jurisdictions.collect { |participation| participation.secondary_entity_id } # if an existing secondary jurisdiction ID is not in the passed-in ids, delete (existing_secondary_jurisdiction_ids - secondary_jurisdiction_ids).each do |id_to_delete| associated_jurisdictions.delete(associated_jurisdictions.find_by_secondary_entity_id(id_to_delete)) end # if an passed-in ID is not in the existing secondary jurisdiction IDs, add (secondary_jurisdiction_ids - existing_secondary_jurisdiction_ids).each do |id_to_add| associated_jurisdictions.create(:secondary_entity_id => id_to_add) end self.add_forms(self.available_forms) if self.can_receive_auto_assigned_forms? reload # Any existing references to this object won't see these changes without this end primary_changed end # transitions that are allowed to be rendered by this user def allowed_transitions current_state.events.select do |event| priv_required = current_state.events(event).meta[:priv_required] next if priv_required.nil? j_id = jurisdiction.secondary_entity_id User.current_user.is_entitled_to_in?(priv_required, j_id) end end def undo_workflow_side_effects attrs = { :investigation_started_date => nil, :investigation_completed_LHD_date => nil, :review_completed_by_state_date => nil } case self.state when :assigned_to_lhd attrs[:investigator_id] = nil attrs[:event_queue_id] = nil end self.update_attributes(attrs) end def add_labs_from_staged_message(staged_message) raise(ArgumentError, I18n.translate('not_a_valid_staged_message', :staged_message => staged_message.class)) unless staged_message.respond_to?('message_header') # All tests have a scale type. The scale type is well known and is part of the standard LOINC code data given in the SCALE_TYP # field. TriSano keeps the scale type in the loinc_codes table scale column. # # There are four scale types that we care about: ordinal (Ord: one of X), nominal (Nom: a string), quantitative (Qn: a number), # and ordinal or quantitative (OrdQn). # # An ordinal test result has values such as Positive or Reactive. E.g. the lab was positive for HIV # # A quantitative test result has a value such as 100 or .5, which when combined with the units field gives a meaningful result. # E.g, the lab showed a hemoglobin count of 13.0 Gm/Dl. # # A nominal test result has a string. In TriSano we are currently making the assumption that this is an organism name. # E.g the blood culture showed the influenza virus. # # An ordinal/quantiative test is either an ordinal string or a number # # These three principal (not including OrdQn) types of test results are, ideally, mapped to three different fields: # # Ord -> test_result_id # Qn -> result_value # Nom -> organism_id # # In the case or Ord and Nom, if the value can't be mapped because the provided value does not match TriSano values, # e.g., the ordinal value is "Affirmative" instead of "Positive", then the result is placed in the result_value field, # rather than not mapping it at all. This has the side effect of making an OrdQn the same as an Ord. # # In addition to organisms specified directly for nominal tests, ordinal and quantitative tests can have organisms too. # TriSano maintains a loinc code to organism relationship in the database # Set the lab name @lab_attributes = { "place_entity_attributes"=> { "place_attributes"=> { "name"=> staged_message.lab_name } }, "lab_results_attributes" => {} } # Create one lab result per OBX segment i = 0 @diseases = Set.new # country per_message_comments = '' unless staged_message.patient.address_country.blank? per_message_comments = "#{I18n.translate :country}: #{staged_message.patient.address_country}" end pv1 = staged_message.pv1 orc = staged_message.common_order find_or_build_clinician(orc.clinician_last_name, orc.clinician_first_name, orc.clinician_phone_type, orc.clinician_telephone) unless orc.nil? or orc.clinician_last_name.blank? find_or_build_clinician(staged_message.pv1.attending_doctor[0], staged_message.pv1.attending_doctor[1]) unless pv1.nil? or pv1.attending_doctor.blank? find_or_build_clinician(staged_message.pv1.consulting_doctor[0], staged_message.pv1.consulting_doctor[1]) unless pv1.nil? or pv1.consulting_doctor.blank? staged_message.observation_requests.each do |obr| find_or_build_clinician(obr.clinician_last_name, obr.clinician_first_name, obr.clinician_phone_type, obr.clinician_telephone) unless obr.clinician_last_name.blank? @per_request_comments = per_message_comments.clone unless obr.specimen_id.blank? @per_request_comments += ", " unless @per_request_comments.blank? @per_request_comments += "#{I18n.translate :specimen_id}: #{obr.specimen_id}" end unless obr.specimen_source_2_5_1.blank? and obr.specimen_source_2_3_1.blank? @per_request_comments += ", " unless @per_request_comments.blank? @per_request_comments += "#{I18n.translate :specimen_source}: #{obr.specimen_source_2_5_1 || obr.specimen_source_2_3_1}" end obr.tests.each do |obx| set_loinc_scale_and_test_type obx if @scale_type.nil? self.add_note I18n.translate(:unknown_loinc_code, :loinc_code => obx.loinc_code) next end if @common_test_type.nil? self.add_note I18n.translate(:loinc_code_known_but_not_linked, :loinc_code => obx.loinc_code) next end add_lab_results staged_message, obr, obx, i i += 1 self.add_note(I18n.translate("system_notes.elr_with_test_type_assigned", :test_type => obx.test_type, :locale => I18n.default_locale)) end # Grab any diseases associated with this OBR loinc_code = LoincCode.find_by_loinc_code obr.test_performed loinc_code.diseases.each { |disease| @diseases << disease } if loinc_code and @diseases.blank? end unless i > 0 # All OBX invalid raise StagedMessage::UnknownLoincCode, I18n.translate(:all_obx_unprocessable) end self.labs_attributes = [ @lab_attributes ] # Assign disease unless self.disease_event # Don't overwrite disease if already there. case @diseases.size when 0 staged_message.note = "#{staged_message.note} #{I18n.translate('no_loinc_code_maps_to_disease', :locale => I18n.default_locale)} " when 1 disease_event = DiseaseEvent.new disease_event.disease = @diseases.to_a.first self.build_disease_event(disease_event.attributes) staged_message.note = "#{staged_message.note} #{I18n.translate('event_disease_set_to', :disease_name => disease_event.disease.disease_name, :locale => I18n.default_locale)} " else staged_message.note = "#{staged_message.note} #{I18n.translate('loinc_code_maps_to_multiple_diseases', :locale => I18n.default_locale)}" + @diseases.collect { |d| d.disease_name }.join('; ') + ". " end end unless staged_message.patient.primary_language.blank? or interested_party.nil? or interested_party.person_entity.person.primary_language_id staged_message.note ||= '' staged_message.note.sub! /\s+$/, '' staged_message.note += '. ' if staged_message.note.length > 0 staged_message.note += I18n.translate :unmapped_language_code, :lang_code => staged_message.patient.primary_language, :locale => I18n.default_locale end unless staged_message.patient.dead_flag.blank? or disease_event.nil? code = case staged_message.patient.dead_flag when 'Y' ExternalCode.yes when 'N' ExternalCode.no end self.disease_event.died_id = code.id end if staged_message.common_order diagnostic_facility_name = staged_message.common_order.facility_name orc = staged_message.common_order unless diagnostic_facility_name.blank? place_entity = find_or_build_hospital(diagnostic_facility_name) place_entity.build_canonical_address(:street_number => orc.facility_address_street_no, :street_name => orc.facility_address_street, :city => orc.facility_address_city, :state_id => orc.facility_address_trisano_state_id, :postal_code => orc.facility_address_zip) unless orc.facility_address_empty? self.diagnostic_facilities.build :place_entity => place_entity end end unless disease_event.nil? or staged_message.pv1.blank? or staged_message.pv1.hospitalized_id.nil? hospitalized_id = staged_message.pv1.hospitalized_id self.disease_event.hospitalized_id = hospitalized_id if hospitalized_id == ExternalCode.yes.id facility_name = staged_message.pv2.facility_name if staged_message.pv2 facility_name = staged_message.common_order.facility_name if facility_name.blank? and staged_message.common_order unless facility_name.blank? place_entity = find_or_build_hospital(facility_name) self.hospitalization_facilities.build :place_entity => place_entity end end end self.parent_guardian = staged_message.next_of_kin.parent_guardian.slice(0,2).join(', ') if staged_message.next_of_kin end def find_or_build_hospital(place_name) # assign the facility name, which requires finding or building a # place # do we already have this? place_entity = PlaceEntity.find(:first, :conditions => [ "entities.deleted_at IS NULL AND LOWER(places.name) = ?", place_name.downcase ], :include => :place) # no? create it place_entity ||= PlaceEntity.new :place_attributes => { :name => place_name.titleize, :short_name => place_name.titleize } # make it a hospital place_code = Code.find_by_code_name_and_the_code('placetype', 'H') place_entity.place.place_types << place_code unless place_entity.place.place_types.include?(place_code) place_entity end def possible_treatments(reload=false) if reload or @possible_treatments.nil? options = { :select => 'distinct treatments.*', :order => 'treatment_name' } if disease = disease_event.try(:disease) options[:joins] = 'LEFT JOIN disease_specific_treatments b ON b.treatment_id = treatments.id' options[:conditions] = [<<-SQL, disease.id, self.id] (active = true AND disease_id = ?) OR treatments.id IN ( SELECT treatment_id FROM participations_treatments a JOIN participations b ON b.id = a.participation_id AND b.event_id = ?) SQL else options[:conditions] = [<<-SQL, self.id] ("default" = true AND active = true) OR id IN ( SELECT treatment_id FROM participations_treatments a JOIN participations b ON b.id = a.participation_id AND b.event_id = ?) SQL end @possible_treatments = Treatment.all(options) end @possible_treatments end private def add_lab_results(staged_message, obr, obx, i) comments = @per_request_comments.clone unless obx.abnormal_flags.blank? comments += ", " unless comments.blank? comments += "#{I18n.translate :abnormal_flags}: #{obx.abnormal_flags}" end comments += ", " unless comments.blank? comments += "Observation value: #{obx.obx_segment.observation_value}" result_hash = {} if @scale_type != "Nom" if @loinc_code.organism result_hash["organism_id"] = @loinc_code.organism.id else comments += ", " unless comments.blank? comments += "ELR Message: No organism mapped to LOINC code." end @loinc_code.diseases.each { |disease| @diseases << disease } end case @scale_type when "Ord", "OrdQn" obx_result = obx.result.gsub(/\s/, '').downcase if map_id = result_map[obx_result] result_hash["test_result_id"] = map_id else result_hash["result_value"] = obx.result end when "Qn" result_hash["result_value"] = obx.result when "Nom" # Try and find OBX-5 in the organism list, otherwise map to result_value # Eventually, we'll need to add more heuristics here for SNOMED etc. organism = Organism.first(:conditions => [ "organism_name ~* ?", '^'+obx.result+'$' ]) if organism.blank? result_hash["result_value"] = obx.result else result_hash["organism_id"] = organism.id organism.diseases.each { |disease| @diseases << disease } end end begin lab_hash = { "test_type_id" => @common_test_type.id, "collection_date" => obr.collection_date, "lab_test_date" => obx.test_date, "reference_range" => obx.reference_range, "specimen_source_id" => obr.specimen_source.id, "staged_message_id" => staged_message.id, "units" => obx.units, "test_status_id" => obx.trisano_status_id, "loinc_code" => @loinc_code, "comment" => comments }.merge!(result_hash) unless obr.filler_order_number.blank? lab_hash["accession_no"] = obr.filler_order_number end @lab_attributes["lab_results_attributes"][i.to_s] = lab_hash rescue Exception => error raise StagedMessage::BadMessageFormat, error.message end end def set_loinc_scale_and_test_type(obx) @loinc_code = LoincCode.find_by_loinc_code obx.loinc_code @scale_type = nil @common_test_type = nil if @loinc_code @scale_type = @loinc_code.scale.the_code @common_test_type = @loinc_code.common_test_type || CommonTestType.find_by_common_name(obx.loinc_common_test_type) else # No :loinc_code entry. # Look at other OBX fields for hints to the scale and common # test type. @scale_type = obx.loinc_scale common_test_type_name = obx.loinc_common_test_type @common_test_type = CommonTestType.find_by_common_name(common_test_type_name) if common_test_type_name end end def result_map self.class.result_map end class << self def result_map # For ordinal tests, a single result has multiple synonyms, such as: "Positive", " Confirmed", " Detected", " Definitive" # So, first load the TriSano test_results, then bust out the slash-separated synonyms into hash keys whose value is the test_result ID. # I.e: { "Positive" => 1, "Confirmed" => 1, "Negative" => 2, ... } unless @result_map test_results = ExternalCode.find_all_by_code_name("test_result") @result_map = {} test_results.each do |result| result.code_description.split('/').each do |component| @result_map[component.gsub(/\s/, '').downcase] = result.id end if result.code_description end end @result_map end end def find_or_build_clinician(last_name, first_name, telephone_type=nil, telephone=nil) person_attributes = { :last_name => last_name , :first_name => first_name, :person_type => 'clinician' } person = Person.first :conditions => person_attributes if person person_entity_id = person.person_entity.id @clinician = clinicians.to_a.find do |c| c.secondary_entity_id == person_entity_id end @clinician ||= clinicians.build :secondary_entity_id => person_entity_id else @clinician = clinicians.to_a.find do |c| c.person_entity.person.last_name == last_name && c.person_entity.person.first_name == first_name end @clinician ||= clinicians.build :person_entity_attributes => { :person_attributes => person_attributes } end unless telephone_type.nil? or telephone.blank? or telephone.all? {|x|x.nil?} area_code, number, extension = telephone telephone_attributes = { :entity_location_type => telephone_type, :area_code => area_code, :phone_number => number, :extension => extension } @clinician.person_entity.telephones.to_a.find do |t| t.entity_location_type == telephone_type && t.area_code == area_code && t.phone_number == number && t.extension == extension end or @clinician.person_entity.telephones.build(telephone_attributes) end @clinician rescue end def set_age_at_onset birthdate = safe_call_chain(:interested_party, :person_entity, :person, :birth_date) self.age_info = AgeInfo.create_from_dates(birthdate, self.event_onset_date) end def set_onset_date self.event_onset_date = resolve_onset_date end def resolve_onset_date safe_call_chain(:disease_event, :disease_onset_date) || safe_call_chain(:disease_event, :date_diagnosed) || definitive_lab_date || self.first_reported_PH_date || self.created_at.try(:to_date) || Date.today end def validate super county_jurisdiction = self.address.try(:county).try(:jurisdiction) if county_jurisdiction == Jurisdiction.out_of_state && (((self.lhd_case_status != ExternalCode.out_of_state) && (!self.lhd_case_status.nil?)) && ((self.state_case_status != ExternalCode.out_of_state) && (!self.state_case_status.nil?))) errors.add(:base, :invalid_case_status, :status => ExternalCode.out_of_state.code_description, :attr => I18n.t(:county).downcase, :value => self.address.county.code_description) end return if self.interested_party.nil? return unless bdate = self.interested_party.person_entity.try(:person).try(:birth_date) base_errors = {} self.hospitalization_facilities.each do |hf| if (date = hf.hospitals_participation.try(:admission_date).try(:to_date)) && (date < bdate) hf.hospitals_participation.errors.add(:admission_date, :cannot_precede_birth_date) base_errors['hospitals'] = [:precede_birth_date, {:thing => I18n.t(:hospitalization)}] end if (date = hf.hospitals_participation.try(:discharge_date).try(:to_date)) && (date < bdate) hf.hospitals_participation.errors.add(:discharge_date, :cannot_precede_birth_date) base_errors['hospitals'] = [:precede_birth_date, { :thing => I18n.t(:hospitalization) }] end end self.interested_party.treatments.each do |t| if (date = t.treatment_date.try(:to_date)) && (date < bdate) t.errors.add(:treatment_date, :cannot_precede_birth_date) base_errors['treatments'] = [:precede_birth_date, { :thing => I18n.t(:treatment) }] end if (date = t.stop_treatment_date.try(:to_date)) && (date < bdate) t.errors.add(:stop_treatment_date, :cannot_precede_birth_date) base_errors['treatments'] = [:precede_birth_date, { :thing => I18n.t(:treatment) }] end end risk_factor = self.interested_party.risk_factor if (date = risk_factor.try(:pregnancy_due_date).try(:to_date)) && (date < bdate) risk_factor.errors.add(:pregnancy_due_date, :cannot_precede_birth_date) base_errors['risk_factor'] = [:precede_birth_date, { :thing => I18n.t(:risk_factor) }] end if (date = self.disease_event.try(:disease_onset_date).try(:to_date)) && (date < bdate) self.disease_event.errors.add(:disease_onset_date, :cannot_precede_birth_date) base_errors['disease'] = [:precede_birth_date, { :thing => I18n.t(:disease) }] end if (date = self.disease_event.try(:date_diagnosed).try(:to_date)) && (date < bdate) self.disease_event.errors.add(:date_diagnosed, :cannot_precede_birth_date) base_errors['disease'] = [:precede_birth_date, { :thing => I18n.t(:disease) }] end self.labs.each do |l| l.lab_results.each do |lr| if (date = lr.collection_date.try(:to_date)) && (date < bdate) lr.errors.add(:collection_date, :cannot_precede_birth_date) base_errors['labs'] = [:precede_birth_date, { :thing => I18n.t(:lab_result) }] end if (date = lr.lab_test_date.try(:to_date)) && (date < bdate) lr.errors.add(:lab_test_date, :cannot_precede_birth_date) base_errors['labs'] = [:precede_birth_date, { :thing => I18n.t(:lab_result) }] end end end if (date = self.results_reported_to_clinician_date.try(:to_date)) && (date < bdate) self.errors.add(:results_reported_to_clinician_date, :cannot_precede_birth_date) end if (date = self.first_reported_PH_date.try(:to_date)) && (date < bdate) self.errors.add(:first_reported_PH_date, :cannot_precede_birth_date) end unless base_errors.empty? && self.errors.empty? base_errors.values.each { |msg| self.errors.add(:base, *msg) } end end def associate_longitudinal_data if address address.update_attributes(:entity_id => interested_party.primary_entity_id) end end def purge_event_from_cache redis.delete_matched("views/events/#{self.id}/*") end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "redis-store-rails2-compat" spec.version = '1.1.4' spec.authors = ["Kimmo Lehto"] spec.email = ["kimmo.lehto@gmail.com"] spec.description = %q{Bring back the rails2 compatibility from redis-store 1.0.0.1 to 1.1.x} spec.summary = %q{Bring back the rails2 compatibility from redis-store 1.0.0.1 to 1.1.x} spec.homepage = "https://github.com/kke/redis-store-rails2-compat" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_runtime_dependency "redis-store", "<2.0" spec.add_runtime_dependency "active_support", "<3.0" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" end active_support is actually activesupport # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "redis-store-rails2-compat" spec.version = '1.1.4' spec.authors = ["Kimmo Lehto"] spec.email = ["kimmo.lehto@gmail.com"] spec.description = %q{Bring back the rails2 compatibility from redis-store 1.0.0.1 to 1.1.x} spec.summary = %q{Bring back the rails2 compatibility from redis-store 1.0.0.1 to 1.1.x} spec.homepage = "https://github.com/kke/redis-store-rails2-compat" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_runtime_dependency "redis-store", "<2.0" spec.add_runtime_dependency "activesupport", "<3.0" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" end
Merb::Generators::ModelGenerator.template :model_activerecord, :orm => :activerecord do source(File.dirname(__FILE__), "templates/model/app/models/%file_name%.rb") destination("app/models", base_path, "#{file_name}.rb") end added invocations for migration generator Merb::Generators::ModelGenerator.template :model_activerecord, :orm => :activerecord do source(File.dirname(__FILE__), "templates/model/app/models/%file_name%.rb") destination("app/models", base_path, "#{file_name}.rb") end Merb::Generators::ModelGenerator.invoke :migration, :orm => :activerecord do |generator| generator.new(destination_root, options.merge(:model => true), file_name, attributes) end
module Asciidoctor module Diagram VERSION = "2.0.3" end end Bump asciidoctor-diagram to 2.0.4.next1 module Asciidoctor module Diagram VERSION = "2.0.4.next1" end end
# frozen_string_literal: true require_relative 'spine_item_processor' require_relative 'font_icon_map' module Asciidoctor module Epub3 # Public: The main converter for the epub3 backend that handles packaging the # EPUB3 or KF8 publication file. class Converter include ::Asciidoctor::Converter include ::Asciidoctor::Logging include ::Asciidoctor::Writer register_for 'epub3' def initialize backend, opts super basebackend 'html' outfilesuffix '.epub' # dummy outfilesuffix since it may be .mobi htmlsyntax 'xml' @validate = false @extract = false @kindlegen_path = nil @epubcheck_path = nil end def convert node, name = nil if (name ||= node.node_name) == 'document' @validate = node.attr? 'ebook-validate' @extract = node.attr? 'ebook-extract' @compress = node.attr 'ebook-compress' @kindlegen_path = node.attr 'ebook-kindlegen-path' @epubcheck_path = node.attr 'ebook-epubcheck-path' spine_items = node.references[:spine_items] if spine_items.nil? logger.error %(#{::File.basename node.document.attr('docfile')}: failed to find spine items, produced file will be invalid) spine_items = [] end Packager.new node, spine_items, node.attributes['ebook-format'].to_sym # converting an element from the spine document, such as an inline node in the doctitle elsif name.start_with? 'inline_' (@content_converter ||= ::Asciidoctor::Converter::Factory.default.create 'epub3-xhtml5').convert node, name else raise ::ArgumentError, %(Encountered unexpected node in epub3 package converter: #{name}) end end # FIXME: we have to package in write because we don't have access to target before this point def write packager, target packager.package validate: @validate, extract: @extract, compress: @compress, kindlegen_path: @kindlegen_path, epubcheck_path: @epubcheck_path, target: target nil end end # Public: The converter for the epub3 backend that converts the individual # content documents in an EPUB3 publication. class ContentConverter include ::Asciidoctor::Converter include ::Asciidoctor::Logging register_for 'epub3-xhtml5' LF = ?\n NoBreakSpace = '&#xa0;' ThinNoBreakSpace = '&#x202f;' RightAngleQuote = '&#x203a;' CalloutStartNum = %(\u2460) CharEntityRx = /&#(\d{2,6});/ XmlElementRx = /<\/?.+?>/ TrailingPunctRx = /[[:punct:]]$/ FromHtmlSpecialCharsMap = { '&lt;' => '<', '&gt;' => '>', '&amp;' => '&', } FromHtmlSpecialCharsRx = /(?:#{FromHtmlSpecialCharsMap.keys * '|'})/ ToHtmlSpecialCharsMap = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', } ToHtmlSpecialCharsRx = /[#{ToHtmlSpecialCharsMap.keys.join}]/ def initialize backend, opts super basebackend 'html' outfilesuffix '.xhtml' htmlsyntax 'xml' @xrefs_seen = ::Set.new @icon_names = [] end def convert node, name = nil if respond_to? name ||= node.node_name send name, node else logger.warn %(conversion missing in epub3 backend for #{name}) end end def document node docid = node.id pubtype = node.attr 'publication-type', 'book' if (doctitle = node.doctitle partition: true, use_fallback: true).subtitle? title = %(#{doctitle.main} ) subtitle = doctitle.subtitle else # HACK: until we get proper handling of title-only in CSS title = '' subtitle = doctitle.combined end doctitle_sanitized = (node.doctitle sanitize: true, use_fallback: true).to_s subtitle_formatted = subtitle.split.map {|w| %(<b>#{w}</b>) } * ' ' if pubtype == 'book' byline = '' else author = node.attr 'author' username = node.attr 'username', 'default' imagesdir = (node.references[:spine].attr 'imagesdir', '.').chomp '/' imagesdir = imagesdir == '.' ? '' : %(#{imagesdir}/) byline = %(<p class="byline"><img src="#{imagesdir}avatars/#{username}.jpg"/> <b class="author">#{author}</b></p>#{LF}) end mark_last_paragraph node unless pubtype == 'book' content = node.content # NOTE must run after content is resolved # TODO perhaps create dynamic CSS file? if @icon_names.empty? icon_css_head = '' else icon_defs = @icon_names.map {|name| %(.i-#{name}::before { content: "#{FontIconMap[name.tr('-', '_').to_sym]}"; }) } * LF icon_css_head = %(<style> #{icon_defs} </style> ) end # NOTE kindlegen seems to mangle the <header> element, so we wrap its content in a div lines = [%(<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" xml:lang="#{lang = node.attr 'lang', 'en'}" lang="#{lang}"> <head> <meta charset="UTF-8"/> <title>#{doctitle_sanitized}</title> <link rel="stylesheet" type="text/css" href="styles/epub3.css"/> <link rel="stylesheet" type="text/css" href="styles/epub3-css3-only.css" media="(min-device-width: 0px)"/> #{icon_css_head}<script type="text/javascript"><![CDATA[ document.addEventListener('DOMContentLoaded', function(event, reader) { if (!(reader = navigator.epubReadingSystem)) { if (navigator.userAgent.indexOf(' calibre/') >= 0) reader = { name: 'calibre-desktop' }; else if (window.parent == window || !(reader = window.parent.navigator.epubReadingSystem)) return; } document.body.setAttribute('class', reader.name.toLowerCase().replace(/ /g, '-')); }); ]]></script> </head> <body> <section class="chapter" title="#{doctitle_sanitized.gsub '"', '&quot;'}" epub:type="chapter" id="#{docid}"> <header> <div class="chapter-header"> #{byline}<h1 class="chapter-title">#{title}#{subtitle ? %(<small class="subtitle">#{subtitle_formatted}</small>) : ''}</h1> </div> </header> #{content})] if node.footnotes? # NOTE kindlegen seems to mangle the <footer> element, so we wrap its content in a div lines << '<footer> <div class="chapter-footer"> <div class="footnotes">' node.footnotes.each do |footnote| lines << %(<aside id="note-#{footnote.index}" epub:type="footnote"> <p><sup class="noteref"><a href="#noteref-#{footnote.index}">#{footnote.index}</a></sup> #{footnote.text}</p> </aside>) end lines << '</div> </div> </footer>' end lines << '</section> </body> </html>' lines * LF end # NOTE embedded is used for AsciiDoc table cell content def embedded node node.content end def section node hlevel = node.level + 1 epub_type_attr = node.special ? %( epub:type="#{node.sectname}") : '' div_classes = [%(sect#{node.level}), node.role].compact title = node.title title_sanitized = xml_sanitize title if node.document.header? || node.level != 1 || node != node.document.first_section %(<section class="#{div_classes * ' '}" title="#{title_sanitized}"#{epub_type_attr}> <h#{hlevel} id="#{node.id}">#{title}</h#{hlevel}>#{(content = node.content).empty? ? '' : %( #{content})} </section>) else # document has no level-0 heading and this heading serves as the document title node.content end end # TODO: support use of quote block as abstract def preamble node if (first_block = node.blocks[0]) && first_block.style == 'abstract' abstract first_block # REVIEW: should we treat the preamble as an abstract in general? elsif first_block && node.blocks.size == 1 abstract first_block else node.content end end def open node id_attr = node.id ? %( id="#{node.id}") : nil class_attr = node.role ? %( class="#{node.role}") : nil if id_attr || class_attr %(<div#{id_attr}#{class_attr}> #{convert_content node} </div>) else convert_content node end end def abstract node %(<div class="abstract" epub:type="preamble"> #{convert_content node} </div>) end def paragraph node role = node.role # stack-head is the alternative to the default, inline-head (where inline means "run-in") head_stop = node.attr 'head-stop', (role && (node.has_role? 'stack-head') ? nil : '.') head = node.title? ? %(<strong class="head">#{title = node.title}#{head_stop && title !~ TrailingPunctRx ? head_stop : ''}</strong> ) : '' if role node.set_option 'hardbreaks' if node.has_role? 'signature' %(<p class="#{role}">#{head}#{node.content}</p>) else %(<p>#{head}#{node.content}</p>) end end def pass node content = node.content if content == '<?hard-pagebreak?>' '<hr epub:type="pagebreak" class="pagebreak"/>' else content end end def admonition node id_attr = node.id ? %( id="#{node.id}") : '' if node.title? title = node.title title_sanitized = xml_sanitize title title_attr = %( title="#{node.caption}: #{title_sanitized}") title_el = %(<h2>#{title}</h2> ) else title_attr = %( title="#{node.caption}") title_el = '' end type = node.attr 'name' epub_type = case type when 'tip' 'help' when 'note' 'note' when 'important', 'warning', 'caution' 'warning' end %(<aside#{id_attr} class="admonition #{type}"#{title_attr} epub:type="#{epub_type}"> #{title_el}<div class="content"> #{convert_content node} </div> </aside>) end def example node id_attr = node.id ? %( id="#{node.id}") : '' title_div = node.title? ? %(<div class="example-title">#{node.title}</div> ) : '' %(<div#{id_attr} class="example"> #{title_div}<div class="example-content"> #{convert_content node} </div> </div>) end def floating_title node tag_name = %(h#{node.level + 1}) id_attribute = node.id ? %( id="#{node.id}") : '' %(<#{tag_name}#{id_attribute} class="#{['discrete', node.role].compact * ' '}">#{node.title}</#{tag_name}>) end def listing node figure_classes = ['listing'] figure_classes << 'coalesce' if node.option? 'unbreakable' pre_classes = node.style == 'source' ? ['source', %(language-#{node.attr 'language'})] : ['screen'] title_div = node.title? ? %(<figcaption>#{node.captioned_title}</figcaption> ) : '' # patches conums to fix extra or missing leading space # TODO remove patch once upgrading to Asciidoctor 1.5.6 %(<figure class="#{figure_classes * ' '}"> #{title_div}<pre class="#{pre_classes * ' '}"><code>#{(node.content || '').gsub(/(?<! )<i class="conum"| +<i class="conum"/, ' <i class="conum"')}</code></pre> </figure>) end # QUESTION should we wrap the <pre> in either <div> or <figure>? def literal node %(<pre class="screen">#{node.content}</pre>) end def page_break _node '<hr epub:type="pagebreak" class="pagebreak"/>' end def thematic_break _node '<hr class="thematicbreak"/>' end def quote node id_attr = %( id="#{node.id}") if node.id class_attr = (role = node.role) ? %( class="blockquote #{role}") : ' class="blockquote"' footer_content = [] if (attribution = node.attr 'attribution') footer_content << attribution end if (citetitle = node.attr 'citetitle') citetitle_sanitized = xml_sanitize citetitle footer_content << %(<cite title="#{citetitle_sanitized}">#{citetitle}</cite>) end footer_content << %(<span class="context">#{node.title}</span>) if node.title? footer_tag = footer_content.empty? ? '' : %( <footer>~ #{footer_content * ' '}</footer>) content = (convert_content node).strip %(<div#{id_attr}#{class_attr}> <blockquote> #{content}#{footer_tag} </blockquote> </div>) end def verse node id_attr = %( id="#{node.id}") if node.id class_attr = (role = node.role) ? %( class="verse #{role}") : ' class="verse"' footer_content = [] if (attribution = node.attr 'attribution') footer_content << attribution end if (citetitle = node.attr 'citetitle') citetitle_sanitized = xml_sanitize citetitle footer_content << %(<cite title="#{citetitle_sanitized}">#{citetitle}</cite>) end footer_tag = !footer_content.empty? ? %( <span class="attribution">~ #{footer_content * ', '}</span>) : '' %(<div#{id_attr}#{class_attr}> <pre>#{node.content}#{footer_tag}</pre> </div>) end def sidebar node classes = ['sidebar'] if node.title? classes << 'titled' title = node.title title_sanitized = xml_sanitize title title_attr = %( title="#{title_sanitized}") title_el = %(<h2>#{title}</h2> ) else title_attr = title_el = '' end %(<aside class="#{classes * ' '}"#{title_attr} epub:type="sidebar"> #{title_el}<div class="content"> #{convert_content node} </div> </aside>) end def table node lines = [%(<div class="table">)] lines << %(<div class="content">) table_id_attr = node.id ? %( id="#{node.id}") : '' frame_class = { 'all' => 'table-framed', 'topbot' => 'table-framed-topbot', 'sides' => 'table-framed-sides', 'none' => '', } grid_class = { 'all' => 'table-grid', 'rows' => 'table-grid-rows', 'cols' => 'table-grid-cols', 'none' => '', } table_classes = %W[table #{frame_class[node.attr 'frame'] || frame_class['topbot']} #{grid_class[node.attr 'grid'] || grid_class['rows']}] if (role = node.role) table_classes << role end table_class_attr = %( class="#{table_classes * ' '}") table_styles = [] table_styles << %(width: #{node.attr 'tablepcwidth'}%) unless (node.option? 'autowidth') && !(node.attr? 'width', nil, false) table_style_attr = !table_styles.empty? ? %( style="#{table_styles * '; '}") : '' lines << %(<table#{table_id_attr}#{table_class_attr}#{table_style_attr}>) lines << %(<caption>#{node.captioned_title}</caption>) if node.title? if (node.attr 'rowcount') > 0 lines << '<colgroup>' #if node.option? 'autowidth' tag = %(<col/>) node.columns.size.times do lines << tag end #else # node.columns.each do |col| # lines << %(<col style="width: #{col.attr 'colpcwidth'}%"/>) # end #end lines << '</colgroup>' [:head, :foot, :body].reject {|tsec| node.rows[tsec].empty? }.each do |tsec| lines << %(<t#{tsec}>) node.rows[tsec].each do |row| lines << '<tr>' row.each do |cell| if tsec == :head cell_content = cell.text else case cell.style when :asciidoc cell_content = %(<div class="embed">#{cell.content}</div>) when :verse cell_content = %(<div class="verse">#{cell.text}</div>) when :literal cell_content = %(<div class="literal"><pre>#{cell.text}</pre></div>) else cell_content = '' cell.content.each do |text| cell_content = %(#{cell_content}<p>#{text}</p>) end end end cell_tag_name = tsec == :head || cell.style == :header ? 'th' : 'td' cell_classes = [] if (halign = cell.attr 'halign') && halign != 'left' cell_classes << 'halign-left' end if (halign = cell.attr 'valign') && halign != 'top' cell_classes << 'valign-top' end cell_class_attr = !cell_classes.empty? ? %( class="#{cell_classes * ' '}") : '' cell_colspan_attr = cell.colspan ? %( colspan="#{cell.colspan}") : '' cell_rowspan_attr = cell.rowspan ? %( rowspan="#{cell.rowspan}") : '' cell_style_attr = (node.document.attr? 'cellbgcolor') ? %( style="background-color: #{node.document.attr 'cellbgcolor'}") : '' lines << %(<#{cell_tag_name}#{cell_class_attr}#{cell_colspan_attr}#{cell_rowspan_attr}#{cell_style_attr}>#{cell_content}</#{cell_tag_name}>) end lines << '</tr>' end lines << %(</t#{tsec}>) end end lines << '</table> </div> </div>' lines * LF end def colist node lines = ['<div class="callout-list"> <ol>'] num = CalloutStartNum node.items.each_with_index do |item, i| lines << %(<li><i class="conum" data-value="#{i + 1}">#{num}</i> #{item.text}</li>) num = num.next end lines << '</ol> </div>' end # TODO: add complex class if list has nested blocks def dlist node lines = [] case (style = node.style) when 'itemized', 'ordered' list_tag_name = style == 'itemized' ? 'ul' : 'ol' role = node.role subject_stop = node.attr 'subject-stop', (role && (node.has_role? 'stack') ? nil : ':') # QUESTION should we just use itemized-list and ordered-list as the class here? or just list? div_classes = [%(#{style}-list), role].compact list_class_attr = (node.option? 'brief') ? ' class="brief"' : '' lines << %(<div class="#{div_classes * ' '}"> <#{list_tag_name}#{list_class_attr}#{list_tag_name == 'ol' && (node.option? 'reversed') ? ' reversed="reversed"' : ''}>) node.items.each do |subjects, dd| # consists of one term (a subject) and supporting content subject = [*subjects].first.text subject_plain = xml_sanitize subject, :plain subject_element = %(<strong class="subject">#{subject}#{subject_stop && subject_plain !~ TrailingPunctRx ? subject_stop : ''}</strong>) lines << '<li>' if dd # NOTE: must wrap remaining text in a span to help webkit justify the text properly lines << %(<span class="principal">#{subject_element}#{dd.text? ? %( <span class="supporting">#{dd.text}</span>) : ''}</span>) lines << dd.content if dd.blocks? else lines << %(<span class="principal">#{subject_element}</span>) end lines << '</li>' end lines << %(</#{list_tag_name}> </div>) else lines << '<div class="description-list"> <dl>' node.items.each do |terms, dd| [*terms].each do |dt| lines << %(<dt> <span class="term">#{dt.text}</span> </dt>) end next unless dd lines << '<dd>' if dd.blocks? lines << %(<span class="principal">#{dd.text}</span>) if dd.text? lines << dd.content else lines << %(<span class="principal">#{dd.text}</span>) end lines << '</dd>' end lines << '</dl> </div>' end lines * LF end def olist node complex = false div_classes = ['ordered-list', node.style, node.role].compact ol_classes = [node.style, ((node.option? 'brief') ? 'brief' : nil)].compact ol_class_attr = ol_classes.empty? ? '' : %( class="#{ol_classes * ' '}") ol_start_attr = (node.attr? 'start') ? %( start="#{node.attr 'start'}") : '' id_attribute = node.id ? %( id="#{node.id}") : '' lines = [%(<div#{id_attribute} class="#{div_classes * ' '}">)] lines << %(<h3 class="list-heading">#{node.title}</h3>) if node.title? lines << %(<ol#{ol_class_attr}#{ol_start_attr}#{(node.option? 'reversed') ? ' reversed="reversed"' : ''}>) node.items.each do |item| lines << %(<li> <span class="principal">#{item.text}</span>) if item.blocks? lines << item.content complex = true unless item.blocks.size == 1 && ::Asciidoctor::List === item.blocks[0] end lines << '</li>' end if complex div_classes << 'complex' lines[0] = %(<div class="#{div_classes * ' '}">) end lines << '</ol> </div>' lines * LF end def ulist node complex = false div_classes = ['itemized-list', node.style, node.role].compact ul_classes = [node.style, ((node.option? 'brief') ? 'brief' : nil)].compact ul_class_attr = ul_classes.empty? ? '' : %( class="#{ul_classes * ' '}") id_attribute = node.id ? %( id="#{node.id}") : '' lines = [%(<div#{id_attribute} class="#{div_classes * ' '}">)] lines << %(<h3 class="list-heading">#{node.title}</h3>) if node.title? lines << %(<ul#{ul_class_attr}>) node.items.each do |item| lines << %(<li> <span class="principal">#{item.text}</span>) if item.blocks? lines << item.content complex = true unless item.blocks.size == 1 && ::Asciidoctor::List === item.blocks[0] end lines << '</li>' end if complex div_classes << 'complex' lines[0] = %(<div class="#{div_classes * ' '}">) end lines << '</ul> </div>' lines * LF end def image node target = node.attr 'target' type = (::File.extname target)[1..-1] id_attr = node.id ? %( id="#{node.id}") : '' img_attrs = [%(alt="#{node.attr 'alt'}")] case type when 'svg' img_attrs << %(style="width: #{node.attr 'scaledwidth', '100%'}") # TODO: make this a convenience method on document epub_properties = (node.document.attributes['epub-properties'] ||= []) epub_properties << 'svg' unless epub_properties.include? 'svg' else img_attrs << %(style="width: #{node.attr 'scaledwidth'}") if node.attr? 'scaledwidth' end =begin # NOTE to set actual width and height, use CSS width and height if type == 'svg' if node.attr? 'scaledwidth' img_attrs << %(width="#{node.attr 'scaledwidth'}") # Kindle #elsif node.attr? 'scaledheight' # img_attrs << %(width="#{node.attr 'scaledheight'}" height="#{node.attr 'scaledheight'}") # ePub3 elsif node.attr? 'scaledheight' img_attrs << %(height="#{node.attr 'scaledheight'}" style="max-height: #{node.attr 'scaledheight'} !important") else # Aldiko doesn't not scale width to 100% by default img_attrs << %(width="100%") end end =end %(<figure#{id_attr} class="image#{prepend_space node.role}"> <div class="content"> <img src="#{node.image_uri node.attr('target')}" #{img_attrs * ' '}/> </div>#{node.title? ? %( <figcaption>#{node.captioned_title}</figcaption>) : ''} </figure>) end def inline_anchor node target = node.target case node.type when :xref # TODO: would be helpful to know what type the target is (e.g., bibref) doc, refid, text, path = node.document, ((node.attr 'refid') || target), node.text, (node.attr 'path') # NOTE if path is non-nil, we have an inter-document xref # QUESTION should we drop the id attribute for an inter-document xref? if path # ex. chapter-id#section-id if node.attr 'fragment' refdoc_id, refdoc_refid = refid.split '#', 2 if refdoc_id == refdoc_refid target = target[0...(target.index '#')] id_attr = %( id="xref--#{refdoc_id}") else id_attr = %( id="xref--#{refdoc_id}--#{refdoc_refid}") end # ex. chapter-id# else refdoc_id = refdoc_refid = refid # inflate key to spine item root (e.g., transform chapter-id to chapter-id#chapter-id) refid = %(#{refid}##{refid}) id_attr = %( id="xref--#{refdoc_id}") end id_attr = '' unless @xrefs_seen.add? refid refdoc = doc.references[:spine_items].find {|it| refdoc_id == (it.id || (it.attr 'docname')) } if refdoc if (refs = refdoc.references[:refs]) && ::Asciidoctor::AbstractNode === (ref = refs[refdoc_refid]) text ||= ::Asciidoctor::Document === ref ? ((ref.attr 'docreftext') || ref.doctitle) : ref.xreftext((@xrefstyle ||= (doc.attr 'xrefstyle'))) elsif (xreftext = refdoc.references[:ids][refdoc_refid]) text ||= xreftext else logger.warn %(#{::File.basename doc.attr('docfile')}: invalid reference to unknown anchor in #{refdoc_id} chapter: #{refdoc_refid}) end else logger.warn %(#{::File.basename doc.attr('docfile')}: invalid reference to anchor in unknown chapter: #{refdoc_id}) end else id_attr = (@xrefs_seen.add? refid) ? %( id="xref-#{refid}") : '' if (refs = doc.references[:refs]) if ::Asciidoctor::AbstractNode === (ref = refs[refid]) xreftext = text || ref.xreftext((@xrefstyle ||= (doc.attr 'xrefstyle'))) end else xreftext = doc.references[:ids][refid] end if xreftext text ||= xreftext else # FIXME: we get false negatives for reference to bibref when using Asciidoctor < 1.5.6 logger.warn %(#{::File.basename doc.attr('docfile')}: invalid reference to unknown local anchor (or valid bibref): #{refid}) end end %(<a#{id_attr} href="#{target}" class="xref">#{text || "[#{refid}]"}</a>) when :ref %(<a id="#{target}"></a>) when :link %(<a href="#{target}" class="link">#{node.text}</a>) when :bibref if @xrefs_seen.include? target %(<a id="#{target}" href="#xref-#{target}">[#{target}]</a>) else %(<a id="#{target}"></a>[#{target}]) end end end def inline_break node %(#{node.text}<br/>) end def inline_button node %(<b class="button">[<span class="label">#{node.text}</span>]</b>) end def inline_callout node num = CalloutStartNum int_num = node.text.to_i (int_num - 1).times { num = num.next } %(<i class="conum" data-value="#{int_num}">#{num}</i>) end def inline_footnote node if (index = node.attr 'index') %(<sup class="noteref">[<a id="noteref-#{index}" href="#note-#{index}" epub:type="noteref">#{index}</a>]</sup>) elsif node.type == :xref %(<mark class="noteref" title="Unresolved note reference">#{node.text}</mark>) end end def inline_image node if node.type == 'icon' @icon_names << (icon_name = node.target) i_classes = ['icon', %(i-#{icon_name})] i_classes << %(icon-#{node.attr 'size'}) if node.attr? 'size' i_classes << %(icon-flip-#{(node.attr 'flip')[0]}) if node.attr? 'flip' i_classes << %(icon-rotate-#{node.attr 'rotate'}) if node.attr? 'rotate' i_classes << node.role if node.role? %(<i class="#{i_classes * ' '}"></i>) else target = node.image_uri node.target img_attrs = [%(alt="#{node.attr 'alt'}"), %(class="inline#{node.role? ? " #{node.role}" : ''}")] if target.end_with? '.svg' img_attrs << %(style="width: #{node.attr 'scaledwidth', '100%'}") # TODO: make this a convenience method on document epub_properties = (node.document.attributes['epub-properties'] ||= []) epub_properties << 'svg' unless epub_properties.include? 'svg' elsif node.attr? 'scaledwidth' img_attrs << %(style="width: #{node.attr 'scaledwidth'}") end %(<img src="#{target}" #{img_attrs * ' '}/>) end end def inline_indexterm node node.type == :visible ? node.text : '' end def inline_kbd node if (keys = node.attr 'keys').size == 1 %(<kbd>#{keys[0]}</kbd>) else key_combo = keys.map {|key| %(<kbd>#{key}</kbd>) }.join '+' %(<span class="keyseq">#{key_combo}</span>) end end def inline_menu node menu = node.attr 'menu' # NOTE we swap right angle quote with chevron right from FontAwesome using CSS caret = %(#{NoBreakSpace}<span class="caret">#{RightAngleQuote}</span> ) if !(submenus = node.attr 'submenus').empty? submenu_path = submenus.map {|submenu| %(<span class="submenu">#{submenu}</span>#{caret}) }.join.chop %(<span class="menuseq"><span class="menu">#{menu}</span>#{caret}#{submenu_path} <span class="menuitem">#{node.attr 'menuitem'}</span></span>) elsif (menuitem = node.attr 'menuitem') %(<span class="menuseq"><span class="menu">#{menu}</span>#{caret}<span class="menuitem">#{menuitem}</span></span>) else %(<span class="menu">#{menu}</span>) end end def inline_quoted node case node.type when :strong %(<strong>#{node.text}</strong>) when :emphasis %(<em>#{node.text}</em>) when :monospaced %(<code class="literal">#{node.text}</code>) when :double #%(&#x201c;#{node.text}&#x201d;) %(“#{node.text}”) when :single #%(&#x2018;#{node.text}&#x2019;) %(‘#{node.text}’) when :superscript %(<sup>#{node.text}</sup>) when :subscript %(<sub>#{node.text}</sub>) else node.text end end def convert_content node node.content_model == :simple ? %(<p>#{node.content}</p>) : node.content end # FIXME: merge into with xml_sanitize helper def xml_sanitize value, target = :attribute sanitized = (value.include? '<') ? value.gsub(XmlElementRx, '').strip.tr_s(' ', ' ') : value if target == :plain && (sanitized.include? ';') sanitized = sanitized.gsub(CharEntityRx) { [$1.to_i].pack 'U*' } if sanitized.include? '&#' sanitized = sanitized.gsub FromHtmlSpecialCharsRx, FromHtmlSpecialCharsMap elsif target == :attribute sanitized = sanitized.gsub '"', '&quot;' if sanitized.include? '"' end sanitized end # TODO: make check for last content paragraph a feature of Asciidoctor def mark_last_paragraph root return unless (last_block = root.blocks[-1]) last_block = last_block.blocks[-1] while last_block.context == :section && last_block.blocks? if last_block.context == :paragraph last_block.attributes['role'] = last_block.role? ? %(#{last_block.role} last) : 'last' end nil end # Prepend a space to the value if it's non-nil, otherwise return empty string. def prepend_space value value ? %( #{value}) : '' end end class DocumentIdGenerator ReservedIds = %w(cover nav ncx) CharRefRx = /&(?:([a-zA-Z][a-zA-Z]+\d{0,2})|#(\d\d\d{0,4})|#x([\da-fA-F][\da-fA-F][\da-fA-F]{0,3}));/ if defined? __dir__ InvalidIdCharsRx = /[^\p{Word}]+/ LeadingDigitRx = /^\p{Nd}/ else InvalidIdCharsRx = /[^[:word:]]+/ LeadingDigitRx = /^[[:digit:]]/ end class << self def generate_id doc, pre = nil, sep = nil synthetic = false unless (id = doc.id) # NOTE we assume pre is a valid ID prefix and that pre and sep only contain valid ID chars pre ||= '_' sep = sep ? sep.chr : '_' if doc.header? id = doc.doctitle sanitize: true id = id.gsub CharRefRx do $1 ? ($1 == 'amp' ? 'and' : sep) : ((d = $2 ? $2.to_i : $3.hex) == 8217 ? '' : ([d].pack 'U*')) end if id.include? '&' id = id.downcase.gsub InvalidIdCharsRx, sep if id.empty? id, synthetic = nil, true else unless sep.empty? if (id = id.tr_s sep, sep).end_with? sep if id == sep id, synthetic = nil, true else id = (id.start_with? sep) ? id[1..-2] : id.chop end elsif id.start_with? sep id = id[1..-1] end end unless synthetic if pre.empty? id = %(_#{id}) if LeadingDigitRx =~ id elsif !(id.start_with? pre) id = %(#{pre}#{id}) end end end elsif (first_section = doc.first_section) id = first_section.id else synthetic = true end id = %(#{pre}document#{sep}#{doc.object_id}) if synthetic end logger.error %(chapter uses a reserved ID: #{id}) if !synthetic && (ReservedIds.include? id) id end end end require_relative 'packager' Extensions.register do if (document = @document).backend == 'epub3' document.attributes['spine'] = '' document.set_attribute 'listing-caption', 'Listing' # pygments.rb hangs on JRuby for Windows, see https://github.com/asciidoctor/asciidoctor-epub3/issues/253 if !(::RUBY_ENGINE == 'jruby' && Gem.win_platform?) && (Gem.try_activate 'pygments.rb') if document.set_attribute 'source-highlighter', 'pygments' document.set_attribute 'pygments-css', 'style' document.set_attribute 'pygments-style', 'bw' end end case (ebook_format = document.attributes['ebook-format']) when 'epub3', 'kf8' # all good when 'mobi' ebook_format = document.attributes['ebook-format'] = 'kf8' else # QUESTION should we display a warning? ebook_format = document.attributes['ebook-format'] = 'epub3' end document.attributes[%(ebook-format-#{ebook_format})] = '' # Only fire SpineItemProcessor for top-level include directives include_processor SpineItemProcessor.new(document) treeprocessor do process do |doc| doc.id = DocumentIdGenerator.generate_id doc, (doc.attr 'idprefix'), (doc.attr 'idseparator') nil end end end end end end resolves #279 prefix node convert methods with convert_ (PR #280) # frozen_string_literal: true require_relative 'spine_item_processor' require_relative 'font_icon_map' module Asciidoctor module Epub3 # Public: The main converter for the epub3 backend that handles packaging the # EPUB3 or KF8 publication file. class Converter include ::Asciidoctor::Converter include ::Asciidoctor::Logging include ::Asciidoctor::Writer register_for 'epub3' def initialize backend, opts super basebackend 'html' outfilesuffix '.epub' # dummy outfilesuffix since it may be .mobi htmlsyntax 'xml' @validate = false @extract = false @kindlegen_path = nil @epubcheck_path = nil end def convert node, name = nil if (name ||= node.node_name) == 'document' @validate = node.attr? 'ebook-validate' @extract = node.attr? 'ebook-extract' @compress = node.attr 'ebook-compress' @kindlegen_path = node.attr 'ebook-kindlegen-path' @epubcheck_path = node.attr 'ebook-epubcheck-path' spine_items = node.references[:spine_items] if spine_items.nil? logger.error %(#{::File.basename node.document.attr('docfile')}: failed to find spine items, produced file will be invalid) spine_items = [] end Packager.new node, spine_items, node.attributes['ebook-format'].to_sym # converting an element from the spine document, such as an inline node in the doctitle elsif name.start_with? 'inline_' (@content_converter ||= ::Asciidoctor::Converter::Factory.default.create 'epub3-xhtml5').convert node, name else raise ::ArgumentError, %(Encountered unexpected node in epub3 package converter: #{name}) end end # FIXME: we have to package in write because we don't have access to target before this point def write packager, target packager.package validate: @validate, extract: @extract, compress: @compress, kindlegen_path: @kindlegen_path, epubcheck_path: @epubcheck_path, target: target nil end end # Public: The converter for the epub3 backend that converts the individual # content documents in an EPUB3 publication. class ContentConverter include ::Asciidoctor::Converter include ::Asciidoctor::Logging register_for 'epub3-xhtml5' LF = ?\n NoBreakSpace = '&#xa0;' ThinNoBreakSpace = '&#x202f;' RightAngleQuote = '&#x203a;' CalloutStartNum = %(\u2460) CharEntityRx = /&#(\d{2,6});/ XmlElementRx = /<\/?.+?>/ TrailingPunctRx = /[[:punct:]]$/ FromHtmlSpecialCharsMap = { '&lt;' => '<', '&gt;' => '>', '&amp;' => '&', } FromHtmlSpecialCharsRx = /(?:#{FromHtmlSpecialCharsMap.keys * '|'})/ ToHtmlSpecialCharsMap = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', } ToHtmlSpecialCharsRx = /[#{ToHtmlSpecialCharsMap.keys.join}]/ def initialize backend, opts super basebackend 'html' outfilesuffix '.xhtml' htmlsyntax 'xml' @xrefs_seen = ::Set.new @icon_names = [] end def convert node, name = nil, _opts = {} method_name = %(convert_#{name ||= node.node_name}) if respond_to? method_name send method_name, node else logger.warn %(conversion missing in backend #{@backend} for #{name}) end end def convert_document node docid = node.id pubtype = node.attr 'publication-type', 'book' if (doctitle = node.doctitle partition: true, use_fallback: true).subtitle? title = %(#{doctitle.main} ) subtitle = doctitle.subtitle else # HACK: until we get proper handling of title-only in CSS title = '' subtitle = doctitle.combined end doctitle_sanitized = (node.doctitle sanitize: true, use_fallback: true).to_s subtitle_formatted = subtitle.split.map {|w| %(<b>#{w}</b>) } * ' ' if pubtype == 'book' byline = '' else author = node.attr 'author' username = node.attr 'username', 'default' imagesdir = (node.references[:spine].attr 'imagesdir', '.').chomp '/' imagesdir = imagesdir == '.' ? '' : %(#{imagesdir}/) byline = %(<p class="byline"><img src="#{imagesdir}avatars/#{username}.jpg"/> <b class="author">#{author}</b></p>#{LF}) end mark_last_paragraph node unless pubtype == 'book' content = node.content # NOTE must run after content is resolved # TODO perhaps create dynamic CSS file? if @icon_names.empty? icon_css_head = '' else icon_defs = @icon_names.map {|name| %(.i-#{name}::before { content: "#{FontIconMap[name.tr('-', '_').to_sym]}"; }) } * LF icon_css_head = %(<style> #{icon_defs} </style> ) end # NOTE kindlegen seems to mangle the <header> element, so we wrap its content in a div lines = [%(<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" xml:lang="#{lang = node.attr 'lang', 'en'}" lang="#{lang}"> <head> <meta charset="UTF-8"/> <title>#{doctitle_sanitized}</title> <link rel="stylesheet" type="text/css" href="styles/epub3.css"/> <link rel="stylesheet" type="text/css" href="styles/epub3-css3-only.css" media="(min-device-width: 0px)"/> #{icon_css_head}<script type="text/javascript"><![CDATA[ document.addEventListener('DOMContentLoaded', function(event, reader) { if (!(reader = navigator.epubReadingSystem)) { if (navigator.userAgent.indexOf(' calibre/') >= 0) reader = { name: 'calibre-desktop' }; else if (window.parent == window || !(reader = window.parent.navigator.epubReadingSystem)) return; } document.body.setAttribute('class', reader.name.toLowerCase().replace(/ /g, '-')); }); ]]></script> </head> <body> <section class="chapter" title="#{doctitle_sanitized.gsub '"', '&quot;'}" epub:type="chapter" id="#{docid}"> <header> <div class="chapter-header"> #{byline}<h1 class="chapter-title">#{title}#{subtitle ? %(<small class="subtitle">#{subtitle_formatted}</small>) : ''}</h1> </div> </header> #{content})] if node.footnotes? # NOTE kindlegen seems to mangle the <footer> element, so we wrap its content in a div lines << '<footer> <div class="chapter-footer"> <div class="footnotes">' node.footnotes.each do |footnote| lines << %(<aside id="note-#{footnote.index}" epub:type="footnote"> <p><sup class="noteref"><a href="#noteref-#{footnote.index}">#{footnote.index}</a></sup> #{footnote.text}</p> </aside>) end lines << '</div> </div> </footer>' end lines << '</section> </body> </html>' lines * LF end # NOTE embedded is used for AsciiDoc table cell content def convert_embedded node node.content end def convert_section node hlevel = node.level + 1 epub_type_attr = node.special ? %( epub:type="#{node.sectname}") : '' div_classes = [%(sect#{node.level}), node.role].compact title = node.title title_sanitized = xml_sanitize title if node.document.header? || node.level != 1 || node != node.document.first_section %(<section class="#{div_classes * ' '}" title="#{title_sanitized}"#{epub_type_attr}> <h#{hlevel} id="#{node.id}">#{title}</h#{hlevel}>#{(content = node.content).empty? ? '' : %( #{content})} </section>) else # document has no level-0 heading and this heading serves as the document title node.content end end # TODO: support use of quote block as abstract def convert_preamble node if (first_block = node.blocks[0]) && first_block.style == 'abstract' convert_abstract first_block # REVIEW: should we treat the preamble as an abstract in general? elsif first_block && node.blocks.size == 1 convert_abstract first_block else node.content end end def convert_open node id_attr = node.id ? %( id="#{node.id}") : nil class_attr = node.role ? %( class="#{node.role}") : nil if id_attr || class_attr %(<div#{id_attr}#{class_attr}> #{output_content node} </div>) else output_content node end end def convert_abstract node %(<div class="abstract" epub:type="preamble"> #{output_content node} </div>) end def convert_paragraph node role = node.role # stack-head is the alternative to the default, inline-head (where inline means "run-in") head_stop = node.attr 'head-stop', (role && (node.has_role? 'stack-head') ? nil : '.') head = node.title? ? %(<strong class="head">#{title = node.title}#{head_stop && title !~ TrailingPunctRx ? head_stop : ''}</strong> ) : '' if role node.set_option 'hardbreaks' if node.has_role? 'signature' %(<p class="#{role}">#{head}#{node.content}</p>) else %(<p>#{head}#{node.content}</p>) end end def convert_pass node content = node.content if content == '<?hard-pagebreak?>' '<hr epub:type="pagebreak" class="pagebreak"/>' else content end end def convert_admonition node id_attr = node.id ? %( id="#{node.id}") : '' if node.title? title = node.title title_sanitized = xml_sanitize title title_attr = %( title="#{node.caption}: #{title_sanitized}") title_el = %(<h2>#{title}</h2> ) else title_attr = %( title="#{node.caption}") title_el = '' end type = node.attr 'name' epub_type = case type when 'tip' 'help' when 'note' 'note' when 'important', 'warning', 'caution' 'warning' end %(<aside#{id_attr} class="admonition #{type}"#{title_attr} epub:type="#{epub_type}"> #{title_el}<div class="content"> #{output_content node} </div> </aside>) end def convert_example node id_attr = node.id ? %( id="#{node.id}") : '' title_div = node.title? ? %(<div class="example-title">#{node.title}</div> ) : '' %(<div#{id_attr} class="example"> #{title_div}<div class="example-content"> #{output_content node} </div> </div>) end def convert_floating_title node tag_name = %(h#{node.level + 1}) id_attribute = node.id ? %( id="#{node.id}") : '' %(<#{tag_name}#{id_attribute} class="#{['discrete', node.role].compact * ' '}">#{node.title}</#{tag_name}>) end def convert_listing node figure_classes = ['listing'] figure_classes << 'coalesce' if node.option? 'unbreakable' pre_classes = node.style == 'source' ? ['source', %(language-#{node.attr 'language'})] : ['screen'] title_div = node.title? ? %(<figcaption>#{node.captioned_title}</figcaption> ) : '' # patches conums to fix extra or missing leading space # TODO remove patch once upgrading to Asciidoctor 1.5.6 %(<figure class="#{figure_classes * ' '}"> #{title_div}<pre class="#{pre_classes * ' '}"><code>#{(node.content || '').gsub(/(?<! )<i class="conum"| +<i class="conum"/, ' <i class="conum"')}</code></pre> </figure>) end # QUESTION should we wrap the <pre> in either <div> or <figure>? def convert_literal node %(<pre class="screen">#{node.content}</pre>) end def convert_page_break _node '<hr epub:type="pagebreak" class="pagebreak"/>' end def convert_thematic_break _node '<hr class="thematicbreak"/>' end def convert_quote node id_attr = %( id="#{node.id}") if node.id class_attr = (role = node.role) ? %( class="blockquote #{role}") : ' class="blockquote"' footer_content = [] if (attribution = node.attr 'attribution') footer_content << attribution end if (citetitle = node.attr 'citetitle') citetitle_sanitized = xml_sanitize citetitle footer_content << %(<cite title="#{citetitle_sanitized}">#{citetitle}</cite>) end footer_content << %(<span class="context">#{node.title}</span>) if node.title? footer_tag = footer_content.empty? ? '' : %( <footer>~ #{footer_content * ' '}</footer>) content = (output_content node).strip %(<div#{id_attr}#{class_attr}> <blockquote> #{content}#{footer_tag} </blockquote> </div>) end def convert_verse node id_attr = %( id="#{node.id}") if node.id class_attr = (role = node.role) ? %( class="verse #{role}") : ' class="verse"' footer_content = [] if (attribution = node.attr 'attribution') footer_content << attribution end if (citetitle = node.attr 'citetitle') citetitle_sanitized = xml_sanitize citetitle footer_content << %(<cite title="#{citetitle_sanitized}">#{citetitle}</cite>) end footer_tag = !footer_content.empty? ? %( <span class="attribution">~ #{footer_content * ', '}</span>) : '' %(<div#{id_attr}#{class_attr}> <pre>#{node.content}#{footer_tag}</pre> </div>) end def convert_sidebar node classes = ['sidebar'] if node.title? classes << 'titled' title = node.title title_sanitized = xml_sanitize title title_attr = %( title="#{title_sanitized}") title_el = %(<h2>#{title}</h2> ) else title_attr = title_el = '' end %(<aside class="#{classes * ' '}"#{title_attr} epub:type="sidebar"> #{title_el}<div class="content"> #{output_content node} </div> </aside>) end def convert_table node lines = [%(<div class="table">)] lines << %(<div class="content">) table_id_attr = node.id ? %( id="#{node.id}") : '' frame_class = { 'all' => 'table-framed', 'topbot' => 'table-framed-topbot', 'sides' => 'table-framed-sides', 'none' => '', } grid_class = { 'all' => 'table-grid', 'rows' => 'table-grid-rows', 'cols' => 'table-grid-cols', 'none' => '', } table_classes = %W[table #{frame_class[node.attr 'frame'] || frame_class['topbot']} #{grid_class[node.attr 'grid'] || grid_class['rows']}] if (role = node.role) table_classes << role end table_class_attr = %( class="#{table_classes * ' '}") table_styles = [] table_styles << %(width: #{node.attr 'tablepcwidth'}%) unless (node.option? 'autowidth') && !(node.attr? 'width', nil, false) table_style_attr = !table_styles.empty? ? %( style="#{table_styles * '; '}") : '' lines << %(<table#{table_id_attr}#{table_class_attr}#{table_style_attr}>) lines << %(<caption>#{node.captioned_title}</caption>) if node.title? if (node.attr 'rowcount') > 0 lines << '<colgroup>' #if node.option? 'autowidth' tag = %(<col/>) node.columns.size.times do lines << tag end #else # node.columns.each do |col| # lines << %(<col style="width: #{col.attr 'colpcwidth'}%"/>) # end #end lines << '</colgroup>' [:head, :foot, :body].reject {|tsec| node.rows[tsec].empty? }.each do |tsec| lines << %(<t#{tsec}>) node.rows[tsec].each do |row| lines << '<tr>' row.each do |cell| if tsec == :head cell_content = cell.text else case cell.style when :asciidoc cell_content = %(<div class="embed">#{cell.content}</div>) when :verse cell_content = %(<div class="verse">#{cell.text}</div>) when :literal cell_content = %(<div class="literal"><pre>#{cell.text}</pre></div>) else cell_content = '' cell.content.each do |text| cell_content = %(#{cell_content}<p>#{text}</p>) end end end cell_tag_name = tsec == :head || cell.style == :header ? 'th' : 'td' cell_classes = [] if (halign = cell.attr 'halign') && halign != 'left' cell_classes << 'halign-left' end if (halign = cell.attr 'valign') && halign != 'top' cell_classes << 'valign-top' end cell_class_attr = !cell_classes.empty? ? %( class="#{cell_classes * ' '}") : '' cell_colspan_attr = cell.colspan ? %( colspan="#{cell.colspan}") : '' cell_rowspan_attr = cell.rowspan ? %( rowspan="#{cell.rowspan}") : '' cell_style_attr = (node.document.attr? 'cellbgcolor') ? %( style="background-color: #{node.document.attr 'cellbgcolor'}") : '' lines << %(<#{cell_tag_name}#{cell_class_attr}#{cell_colspan_attr}#{cell_rowspan_attr}#{cell_style_attr}>#{cell_content}</#{cell_tag_name}>) end lines << '</tr>' end lines << %(</t#{tsec}>) end end lines << '</table> </div> </div>' lines * LF end def convert_colist node lines = ['<div class="callout-list"> <ol>'] num = CalloutStartNum node.items.each_with_index do |item, i| lines << %(<li><i class="conum" data-value="#{i + 1}">#{num}</i> #{item.text}</li>) num = num.next end lines << '</ol> </div>' end # TODO: add complex class if list has nested blocks def convert_dlist node lines = [] case (style = node.style) when 'itemized', 'ordered' list_tag_name = style == 'itemized' ? 'ul' : 'ol' role = node.role subject_stop = node.attr 'subject-stop', (role && (node.has_role? 'stack') ? nil : ':') # QUESTION should we just use itemized-list and ordered-list as the class here? or just list? div_classes = [%(#{style}-list), role].compact list_class_attr = (node.option? 'brief') ? ' class="brief"' : '' lines << %(<div class="#{div_classes * ' '}"> <#{list_tag_name}#{list_class_attr}#{list_tag_name == 'ol' && (node.option? 'reversed') ? ' reversed="reversed"' : ''}>) node.items.each do |subjects, dd| # consists of one term (a subject) and supporting content subject = [*subjects].first.text subject_plain = xml_sanitize subject, :plain subject_element = %(<strong class="subject">#{subject}#{subject_stop && subject_plain !~ TrailingPunctRx ? subject_stop : ''}</strong>) lines << '<li>' if dd # NOTE: must wrap remaining text in a span to help webkit justify the text properly lines << %(<span class="principal">#{subject_element}#{dd.text? ? %( <span class="supporting">#{dd.text}</span>) : ''}</span>) lines << dd.content if dd.blocks? else lines << %(<span class="principal">#{subject_element}</span>) end lines << '</li>' end lines << %(</#{list_tag_name}> </div>) else lines << '<div class="description-list"> <dl>' node.items.each do |terms, dd| [*terms].each do |dt| lines << %(<dt> <span class="term">#{dt.text}</span> </dt>) end next unless dd lines << '<dd>' if dd.blocks? lines << %(<span class="principal">#{dd.text}</span>) if dd.text? lines << dd.content else lines << %(<span class="principal">#{dd.text}</span>) end lines << '</dd>' end lines << '</dl> </div>' end lines * LF end def convert_olist node complex = false div_classes = ['ordered-list', node.style, node.role].compact ol_classes = [node.style, ((node.option? 'brief') ? 'brief' : nil)].compact ol_class_attr = ol_classes.empty? ? '' : %( class="#{ol_classes * ' '}") ol_start_attr = (node.attr? 'start') ? %( start="#{node.attr 'start'}") : '' id_attribute = node.id ? %( id="#{node.id}") : '' lines = [%(<div#{id_attribute} class="#{div_classes * ' '}">)] lines << %(<h3 class="list-heading">#{node.title}</h3>) if node.title? lines << %(<ol#{ol_class_attr}#{ol_start_attr}#{(node.option? 'reversed') ? ' reversed="reversed"' : ''}>) node.items.each do |item| lines << %(<li> <span class="principal">#{item.text}</span>) if item.blocks? lines << item.content complex = true unless item.blocks.size == 1 && ::Asciidoctor::List === item.blocks[0] end lines << '</li>' end if complex div_classes << 'complex' lines[0] = %(<div class="#{div_classes * ' '}">) end lines << '</ol> </div>' lines * LF end def convert_ulist node complex = false div_classes = ['itemized-list', node.style, node.role].compact ul_classes = [node.style, ((node.option? 'brief') ? 'brief' : nil)].compact ul_class_attr = ul_classes.empty? ? '' : %( class="#{ul_classes * ' '}") id_attribute = node.id ? %( id="#{node.id}") : '' lines = [%(<div#{id_attribute} class="#{div_classes * ' '}">)] lines << %(<h3 class="list-heading">#{node.title}</h3>) if node.title? lines << %(<ul#{ul_class_attr}>) node.items.each do |item| lines << %(<li> <span class="principal">#{item.text}</span>) if item.blocks? lines << item.content complex = true unless item.blocks.size == 1 && ::Asciidoctor::List === item.blocks[0] end lines << '</li>' end if complex div_classes << 'complex' lines[0] = %(<div class="#{div_classes * ' '}">) end lines << '</ul> </div>' lines * LF end def convert_image node target = node.attr 'target' type = (::File.extname target)[1..-1] id_attr = node.id ? %( id="#{node.id}") : '' img_attrs = [%(alt="#{node.attr 'alt'}")] case type when 'svg' img_attrs << %(style="width: #{node.attr 'scaledwidth', '100%'}") # TODO: make this a convenience method on document epub_properties = (node.document.attributes['epub-properties'] ||= []) epub_properties << 'svg' unless epub_properties.include? 'svg' else img_attrs << %(style="width: #{node.attr 'scaledwidth'}") if node.attr? 'scaledwidth' end =begin # NOTE to set actual width and height, use CSS width and height if type == 'svg' if node.attr? 'scaledwidth' img_attrs << %(width="#{node.attr 'scaledwidth'}") # Kindle #elsif node.attr? 'scaledheight' # img_attrs << %(width="#{node.attr 'scaledheight'}" height="#{node.attr 'scaledheight'}") # ePub3 elsif node.attr? 'scaledheight' img_attrs << %(height="#{node.attr 'scaledheight'}" style="max-height: #{node.attr 'scaledheight'} !important") else # Aldiko doesn't not scale width to 100% by default img_attrs << %(width="100%") end end =end %(<figure#{id_attr} class="image#{prepend_space node.role}"> <div class="content"> <img src="#{node.image_uri node.attr('target')}" #{img_attrs * ' '}/> </div>#{node.title? ? %( <figcaption>#{node.captioned_title}</figcaption>) : ''} </figure>) end def convert_inline_anchor node target = node.target case node.type when :xref # TODO: would be helpful to know what type the target is (e.g., bibref) doc, refid, text, path = node.document, ((node.attr 'refid') || target), node.text, (node.attr 'path') # NOTE if path is non-nil, we have an inter-document xref # QUESTION should we drop the id attribute for an inter-document xref? if path # ex. chapter-id#section-id if node.attr 'fragment' refdoc_id, refdoc_refid = refid.split '#', 2 if refdoc_id == refdoc_refid target = target[0...(target.index '#')] id_attr = %( id="xref--#{refdoc_id}") else id_attr = %( id="xref--#{refdoc_id}--#{refdoc_refid}") end # ex. chapter-id# else refdoc_id = refdoc_refid = refid # inflate key to spine item root (e.g., transform chapter-id to chapter-id#chapter-id) refid = %(#{refid}##{refid}) id_attr = %( id="xref--#{refdoc_id}") end id_attr = '' unless @xrefs_seen.add? refid refdoc = doc.references[:spine_items].find {|it| refdoc_id == (it.id || (it.attr 'docname')) } if refdoc if (refs = refdoc.references[:refs]) && ::Asciidoctor::AbstractNode === (ref = refs[refdoc_refid]) text ||= ::Asciidoctor::Document === ref ? ((ref.attr 'docreftext') || ref.doctitle) : ref.xreftext((@xrefstyle ||= (doc.attr 'xrefstyle'))) elsif (xreftext = refdoc.references[:ids][refdoc_refid]) text ||= xreftext else logger.warn %(#{::File.basename doc.attr('docfile')}: invalid reference to unknown anchor in #{refdoc_id} chapter: #{refdoc_refid}) end else logger.warn %(#{::File.basename doc.attr('docfile')}: invalid reference to anchor in unknown chapter: #{refdoc_id}) end else id_attr = (@xrefs_seen.add? refid) ? %( id="xref-#{refid}") : '' if (refs = doc.references[:refs]) if ::Asciidoctor::AbstractNode === (ref = refs[refid]) xreftext = text || ref.xreftext((@xrefstyle ||= (doc.attr 'xrefstyle'))) end else xreftext = doc.references[:ids][refid] end if xreftext text ||= xreftext else # FIXME: we get false negatives for reference to bibref when using Asciidoctor < 1.5.6 logger.warn %(#{::File.basename doc.attr('docfile')}: invalid reference to unknown local anchor (or valid bibref): #{refid}) end end %(<a#{id_attr} href="#{target}" class="xref">#{text || "[#{refid}]"}</a>) when :ref %(<a id="#{target}"></a>) when :link %(<a href="#{target}" class="link">#{node.text}</a>) when :bibref if @xrefs_seen.include? target %(<a id="#{target}" href="#xref-#{target}">[#{target}]</a>) else %(<a id="#{target}"></a>[#{target}]) end end end def convert_inline_break node %(#{node.text}<br/>) end def convert_inline_button node %(<b class="button">[<span class="label">#{node.text}</span>]</b>) end def convert_inline_callout node num = CalloutStartNum int_num = node.text.to_i (int_num - 1).times { num = num.next } %(<i class="conum" data-value="#{int_num}">#{num}</i>) end def convert_inline_footnote node if (index = node.attr 'index') %(<sup class="noteref">[<a id="noteref-#{index}" href="#note-#{index}" epub:type="noteref">#{index}</a>]</sup>) elsif node.type == :xref %(<mark class="noteref" title="Unresolved note reference">#{node.text}</mark>) end end def convert_inline_image node if node.type == 'icon' @icon_names << (icon_name = node.target) i_classes = ['icon', %(i-#{icon_name})] i_classes << %(icon-#{node.attr 'size'}) if node.attr? 'size' i_classes << %(icon-flip-#{(node.attr 'flip')[0]}) if node.attr? 'flip' i_classes << %(icon-rotate-#{node.attr 'rotate'}) if node.attr? 'rotate' i_classes << node.role if node.role? %(<i class="#{i_classes * ' '}"></i>) else target = node.image_uri node.target img_attrs = [%(alt="#{node.attr 'alt'}"), %(class="inline#{node.role? ? " #{node.role}" : ''}")] if target.end_with? '.svg' img_attrs << %(style="width: #{node.attr 'scaledwidth', '100%'}") # TODO: make this a convenience method on document epub_properties = (node.document.attributes['epub-properties'] ||= []) epub_properties << 'svg' unless epub_properties.include? 'svg' elsif node.attr? 'scaledwidth' img_attrs << %(style="width: #{node.attr 'scaledwidth'}") end %(<img src="#{target}" #{img_attrs * ' '}/>) end end def convert_inline_indexterm node node.type == :visible ? node.text : '' end def convert_inline_kbd node if (keys = node.attr 'keys').size == 1 %(<kbd>#{keys[0]}</kbd>) else key_combo = keys.map {|key| %(<kbd>#{key}</kbd>) }.join '+' %(<span class="keyseq">#{key_combo}</span>) end end def convert_inline_menu node menu = node.attr 'menu' # NOTE we swap right angle quote with chevron right from FontAwesome using CSS caret = %(#{NoBreakSpace}<span class="caret">#{RightAngleQuote}</span> ) if !(submenus = node.attr 'submenus').empty? submenu_path = submenus.map {|submenu| %(<span class="submenu">#{submenu}</span>#{caret}) }.join.chop %(<span class="menuseq"><span class="menu">#{menu}</span>#{caret}#{submenu_path} <span class="menuitem">#{node.attr 'menuitem'}</span></span>) elsif (menuitem = node.attr 'menuitem') %(<span class="menuseq"><span class="menu">#{menu}</span>#{caret}<span class="menuitem">#{menuitem}</span></span>) else %(<span class="menu">#{menu}</span>) end end def convert_inline_quoted node case node.type when :strong %(<strong>#{node.text}</strong>) when :emphasis %(<em>#{node.text}</em>) when :monospaced %(<code class="literal">#{node.text}</code>) when :double #%(&#x201c;#{node.text}&#x201d;) %(“#{node.text}”) when :single #%(&#x2018;#{node.text}&#x2019;) %(‘#{node.text}’) when :superscript %(<sup>#{node.text}</sup>) when :subscript %(<sub>#{node.text}</sub>) else node.text end end def output_content node node.content_model == :simple ? %(<p>#{node.content}</p>) : node.content end # FIXME: merge into with xml_sanitize helper def xml_sanitize value, target = :attribute sanitized = (value.include? '<') ? value.gsub(XmlElementRx, '').strip.tr_s(' ', ' ') : value if target == :plain && (sanitized.include? ';') sanitized = sanitized.gsub(CharEntityRx) { [$1.to_i].pack 'U*' } if sanitized.include? '&#' sanitized = sanitized.gsub FromHtmlSpecialCharsRx, FromHtmlSpecialCharsMap elsif target == :attribute sanitized = sanitized.gsub '"', '&quot;' if sanitized.include? '"' end sanitized end # TODO: make check for last content paragraph a feature of Asciidoctor def mark_last_paragraph root return unless (last_block = root.blocks[-1]) last_block = last_block.blocks[-1] while last_block.context == :section && last_block.blocks? if last_block.context == :paragraph last_block.attributes['role'] = last_block.role? ? %(#{last_block.role} last) : 'last' end nil end # Prepend a space to the value if it's non-nil, otherwise return empty string. def prepend_space value value ? %( #{value}) : '' end end class DocumentIdGenerator ReservedIds = %w(cover nav ncx) CharRefRx = /&(?:([a-zA-Z][a-zA-Z]+\d{0,2})|#(\d\d\d{0,4})|#x([\da-fA-F][\da-fA-F][\da-fA-F]{0,3}));/ if defined? __dir__ InvalidIdCharsRx = /[^\p{Word}]+/ LeadingDigitRx = /^\p{Nd}/ else InvalidIdCharsRx = /[^[:word:]]+/ LeadingDigitRx = /^[[:digit:]]/ end class << self def generate_id doc, pre = nil, sep = nil synthetic = false unless (id = doc.id) # NOTE we assume pre is a valid ID prefix and that pre and sep only contain valid ID chars pre ||= '_' sep = sep ? sep.chr : '_' if doc.header? id = doc.doctitle sanitize: true id = id.gsub CharRefRx do $1 ? ($1 == 'amp' ? 'and' : sep) : ((d = $2 ? $2.to_i : $3.hex) == 8217 ? '' : ([d].pack 'U*')) end if id.include? '&' id = id.downcase.gsub InvalidIdCharsRx, sep if id.empty? id, synthetic = nil, true else unless sep.empty? if (id = id.tr_s sep, sep).end_with? sep if id == sep id, synthetic = nil, true else id = (id.start_with? sep) ? id[1..-2] : id.chop end elsif id.start_with? sep id = id[1..-1] end end unless synthetic if pre.empty? id = %(_#{id}) if LeadingDigitRx =~ id elsif !(id.start_with? pre) id = %(#{pre}#{id}) end end end elsif (first_section = doc.first_section) id = first_section.id else synthetic = true end id = %(#{pre}document#{sep}#{doc.object_id}) if synthetic end logger.error %(chapter uses a reserved ID: #{id}) if !synthetic && (ReservedIds.include? id) id end end end require_relative 'packager' Extensions.register do if (document = @document).backend == 'epub3' document.attributes['spine'] = '' document.set_attribute 'listing-caption', 'Listing' # pygments.rb hangs on JRuby for Windows, see https://github.com/asciidoctor/asciidoctor-epub3/issues/253 if !(::RUBY_ENGINE == 'jruby' && Gem.win_platform?) && (Gem.try_activate 'pygments.rb') if document.set_attribute 'source-highlighter', 'pygments' document.set_attribute 'pygments-css', 'style' document.set_attribute 'pygments-style', 'bw' end end case (ebook_format = document.attributes['ebook-format']) when 'epub3', 'kf8' # all good when 'mobi' ebook_format = document.attributes['ebook-format'] = 'kf8' else # QUESTION should we display a warning? ebook_format = document.attributes['ebook-format'] = 'epub3' end document.attributes[%(ebook-format-#{ebook_format})] = '' # Only fire SpineItemProcessor for top-level include directives include_processor SpineItemProcessor.new(document) treeprocessor do process do |doc| doc.id = DocumentIdGenerator.generate_id doc, (doc.attr 'idprefix'), (doc.attr 'idseparator') nil end end end end end end
module Gifts class RepoTable < TableBase def table_name "repo" end def define_schema Groonga::Schema.define do |schema| schema.create_table(table_name, type: :hash) do |table| table.string("path") end end end def add(path) git_repo = Repo.new(path) db_repo = table[path] || table.add(path, path: path) @db.commits.add(git_repo, db_repo) end def remove(path) end end end Use absolute path of repo. module Gifts class RepoTable < TableBase def table_name "repo" end def define_schema Groonga::Schema.define do |schema| schema.create_table(table_name, type: :hash) do |table| table.string("path") end end end def add(path) path = File.expand_path(path) git_repo = Repo.new(path) db_repo = table[path] || table.add(path, path: path) @db.commits.add(git_repo, db_repo) end def remove(path) end end end
# encoding: UTF-8 module Asciidoctor # A built-in {Converter} implementation that generates HTML 5 output # consistent with the html5 backend from AsciiDoc Python. class Converter::Html5Converter < Converter::BuiltIn QUOTE_TAGS = { :emphasis => ['<em>', '</em>', true], :strong => ['<strong>', '</strong>', true], :monospaced => ['<code>', '</code>', true], :superscript => ['<sup>', '</sup>', true], :subscript => ['<sub>', '</sub>', true], :double => ['&#8220;', '&#8221;', false], :single => ['&#8216;', '&#8217;', false], :mark => ['<mark>', '</mark>', true], :asciimath => ['\\$', '\\$', false], :latexmath => ['\\(', '\\)', false] # Opal can't resolve these constants when referenced here #:asciimath => INLINE_MATH_DELIMITERS[:asciimath] + [false], #:latexmath => INLINE_MATH_DELIMITERS[:latexmath] + [false] } QUOTE_TAGS.default = [nil, nil, nil] def initialize backend, opts = {} @xml_mode = opts[:htmlsyntax] == 'xml' @void_element_slash = @xml_mode ? '/' : nil @stylesheets = Stylesheets.instance end def document node result = [] slash = @void_element_slash br = %(<br#{slash}>) asset_uri_scheme = (node.attr 'asset-uri-scheme', 'https') asset_uri_scheme = %(#{asset_uri_scheme}:) unless asset_uri_scheme.empty? cdn_base = %(#{asset_uri_scheme}//cdnjs.cloudflare.com/ajax/libs) linkcss = node.safe >= SafeMode::SECURE || (node.attr? 'linkcss') result << '<!DOCTYPE html>' lang_attribute = (node.attr? 'nolang') ? nil : %( lang="#{node.attr 'lang', 'en'}") result << %(<html#{@xml_mode ? ' xmlns="http://www.w3.org/1999/xhtml"' : nil}#{lang_attribute}>) result << %(<head> <meta charset="#{node.attr 'encoding', 'UTF-8'}"#{slash}> <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"#{slash}><![endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"#{slash}> <meta name="generator" content="Asciidoctor #{node.attr 'asciidoctor-version'}"#{slash}>) result << %(<meta name="application-name" content="#{node.attr 'app-name'}"#{slash}>) if node.attr? 'app-name' result << %(<meta name="description" content="#{node.attr 'description'}"#{slash}>) if node.attr? 'description' result << %(<meta name="keywords" content="#{node.attr 'keywords'}"#{slash}>) if node.attr? 'keywords' result << %(<meta name="author" content="#{node.attr 'authors'}"#{slash}>) if node.attr? 'authors' result << %(<meta name="copyright" content="#{node.attr 'copyright'}"#{slash}>) if node.attr? 'copyright' result << %(<title>#{node.doctitle :sanitize => true, :use_fallback => true}</title>) if DEFAULT_STYLESHEET_KEYS.include?(node.attr 'stylesheet') if (webfonts = node.attr 'webfonts') result << %(<link rel="stylesheet" href="#{asset_uri_scheme}//fonts.googleapis.com/css?family=#{webfonts.empty? ? 'Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400' : webfonts}"#{slash}>) end if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path DEFAULT_STYLESHEET_NAME, (node.attr 'stylesdir', ''), false}"#{slash}>) else result << @stylesheets.embed_primary_stylesheet end elsif node.attr? 'stylesheet' if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path((node.attr 'stylesheet'), (node.attr 'stylesdir', ''))}"#{slash}>) else result << %(<style> #{node.read_asset node.normalize_system_path((node.attr 'stylesheet'), (node.attr 'stylesdir', '')), :warn_on_failure => true} </style>) end end if node.attr? 'icons', 'font' if node.attr? 'iconfont-remote' result << %(<link rel="stylesheet" href="#{node.attr 'iconfont-cdn', %[#{cdn_base}/font-awesome/4.2.0/css/font-awesome.min.css]}"#{slash}>) else iconfont_stylesheet = %(#{node.attr 'iconfont-name', 'font-awesome'}.css) result << %(<link rel="stylesheet" href="#{node.normalize_web_path iconfont_stylesheet, (node.attr 'stylesdir', ''), false}"#{slash}>) end end case node.attr 'source-highlighter' when 'coderay' if (node.attr 'coderay-css', 'class') == 'class' if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path @stylesheets.coderay_stylesheet_name, (node.attr 'stylesdir', ''), false}"#{slash}>) else result << @stylesheets.embed_coderay_stylesheet end end when 'pygments' if (node.attr 'pygments-css', 'class') == 'class' pygments_style = node.attr 'pygments-style' if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path @stylesheets.pygments_stylesheet_name(pygments_style), (node.attr 'stylesdir', ''), false}"#{slash}>) else result << (@stylesheets.embed_pygments_stylesheet pygments_style) end end when 'highlightjs', 'highlight.js' highlightjs_path = node.attr 'highlightjsdir', %(#{cdn_base}/highlight.js/8.4) result << %(<link rel="stylesheet" href="#{highlightjs_path}/styles/#{node.attr 'highlightjs-theme', 'github'}.min.css"#{slash}> <script src="#{highlightjs_path}/highlight.min.js"></script> <script>hljs.initHighlightingOnLoad()</script>) when 'prettify' prettify_path = node.attr 'prettifydir', %(#{cdn_base}/prettify/r298) result << %(<link rel="stylesheet" href="#{prettify_path}/#{node.attr 'prettify-theme', 'prettify'}.min.css"#{slash}> <script src="#{prettify_path}/prettify.min.js"></script> <script>document.addEventListener('DOMContentLoaded', prettyPrint)</script>) end if node.attr? 'stem' # IMPORTANT to_s calls on delimiter arrays are intentional for JavaScript compat (emulates JSON.stringify) eqnums_val = node.attr 'eqnums', 'none' eqnums_val = 'AMS' if eqnums_val == '' eqnums_opt = %( equationNumbers: { autoNumber: "#{eqnums_val}" } ) result << %(<script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: { inlineMath: [#{INLINE_MATH_DELIMITERS[:latexmath].to_s}], displayMath: [#{BLOCK_MATH_DELIMITERS[:latexmath].to_s}], ignoreClass: "nostem|nolatexmath" }, asciimath2jax: { delimiters: [#{BLOCK_MATH_DELIMITERS[:asciimath].to_s}], ignoreClass: "nostem|noasciimath" }, TeX: {#{eqnums_opt}} }); </script> <script src="#{cdn_base}/mathjax/2.4.0/MathJax.js?config=TeX-MML-AM_HTMLorMML"></script>) end unless (docinfo_content = node.docinfo).empty? result << docinfo_content end result << '</head>' body_attrs = [] if node.id body_attrs << %(id="#{node.id}") end if (node.attr? 'toc-class') && (node.attr? 'toc') && (node.attr? 'toc-placement', 'auto') body_attrs << %(class="#{node.doctype} #{node.attr 'toc-class'} toc-#{node.attr 'toc-position', 'header'}") else body_attrs << %(class="#{node.doctype}") end if node.attr? 'max-width' body_attrs << %(style="max-width: #{node.attr 'max-width'};") end result << %(<body #{body_attrs * ' '}>) unless node.noheader result << '<div id="header">' if node.doctype == 'manpage' result << %(<h1>#{node.doctitle} Manual Page</h1>) if (node.attr? 'toc') && (node.attr? 'toc-placement', 'auto') result << %(<div id="toc" class="#{node.attr 'toc-class', 'toc'}"> <div id="toctitle">#{node.attr 'toc-title'}</div> #{outline node} </div>) end result << %(<h2>#{node.attr 'manname-title'}</h2> <div class="sectionbody"> <p>#{node.attr 'manname'} - #{node.attr 'manpurpose'}</p> </div>) else if node.has_header? result << %(<h1>#{node.header.title}</h1>) unless node.notitle details = [] if node.attr? 'author' details << %(<span id="author" class="author">#{node.attr 'author'}</span>#{br}) if node.attr? 'email' details << %(<span id="email" class="email">#{node.sub_macros(node.attr 'email')}</span>#{br}) end if (authorcount = (node.attr 'authorcount').to_i) > 1 (2..authorcount).each do |idx| details << %(<span id="author#{idx}" class="author">#{node.attr "author_#{idx}"}</span>#{br}) if node.attr? %(email_#{idx}) details << %(<span id="email#{idx}" class="email">#{node.sub_macros(node.attr "email_#{idx}")}</span>#{br}) end end end end if node.attr? 'revnumber' details << %(<span id="revnumber">#{((node.attr 'version-label') || '').downcase} #{node.attr 'revnumber'}#{(node.attr? 'revdate') ? ',' : ''}</span>) end if node.attr? 'revdate' details << %(<span id="revdate">#{node.attr 'revdate'}</span>) end if node.attr? 'revremark' details << %(#{br}<span id="revremark">#{node.attr 'revremark'}</span>) end unless details.empty? result << '<div class="details">' result.concat details result << '</div>' end end if (node.attr? 'toc') && (node.attr? 'toc-placement', 'auto') result << %(<div id="toc" class="#{node.attr 'toc-class', 'toc'}"> <div id="toctitle">#{node.attr 'toc-title'}</div> #{outline node} </div>) end end result << '</div>' end result << %(<div id="content"> #{node.content} </div>) if node.footnotes? && !(node.attr? 'nofootnotes') result << %(<div id="footnotes"> <hr#{slash}>) node.footnotes.each do |footnote| result << %(<div class="footnote" id="_footnote_#{footnote.index}"> <a href="#_footnoteref_#{footnote.index}">#{footnote.index}</a>. #{footnote.text} </div>) end result << '</div>' end unless node.nofooter result << '<div id="footer">' result << '<div id="footer-text">' if node.attr? 'revnumber' result << %(#{node.attr 'version-label'} #{node.attr 'revnumber'}#{br}) end if node.attr? 'last-update-label' result << %(#{node.attr 'last-update-label'} #{node.attr 'docdatetime'}) end result << '</div>' unless (docinfo_content = node.docinfo :footer).empty? result << docinfo_content end result << '</div>' end result << '</body>' result << '</html>' result * EOL end def embedded node result = [] if !node.notitle && node.has_header? id_attr = node.id ? %( id="#{node.id}") : nil result << %(<h1#{id_attr}>#{node.header.title}</h1>) end result << node.content if node.footnotes? && !(node.attr? 'nofootnotes') result << %(<div id="footnotes"> <hr#{@void_element_slash}>) node.footnotes.each do |footnote| result << %(<div class="footnote" id="_footnote_#{footnote.index}"> <a href="#_footnoteref_#{footnote.index}">#{footnote.index}</a> #{footnote.text} </div>) end result << '</div>' end result * EOL end def outline node, opts = {} return if (sections = node.sections).empty? sectnumlevels = opts[:sectnumlevels] || (node.document.attr 'sectnumlevels', 3).to_i toclevels = opts[:toclevels] || (node.document.attr 'toclevels', 2).to_i result = [] # FIXME the level for special sections should be set correctly in the model # slevel will only be 0 if we have a book doctype with parts slevel = (first_section = sections[0]).level slevel = 1 if slevel == 0 && first_section.special result << %(<ul class="sectlevel#{slevel}">) sections.each do |section| section_num = (section.numbered && !section.caption && section.level <= sectnumlevels) ? %(#{section.sectnum} ) : nil if section.level < toclevels && (child_toc_level = outline section, :toclevels => toclevels, :secnumlevels => sectnumlevels) result << %(<li><a href="##{section.id}">#{section_num}#{section.captioned_title}</a>) result << child_toc_level result << '</li>' else result << %(<li><a href="##{section.id}">#{section_num}#{section.captioned_title}</a></li>) end end result << '</ul>' result * EOL end def section node slevel = node.level # QUESTION should the check for slevel be done in section? slevel = 1 if slevel == 0 && node.special htag = %(h#{slevel + 1}) id_attr = anchor = link_start = link_end = nil if node.id id_attr = %( id="#{node.id}") if node.document.attr? 'sectanchors' anchor = %(<a class="anchor" href="##{node.id}"></a>) # possible idea - anchor icons GitHub-style #if node.document.attr? 'icons', 'font' # anchor = %(<a class="anchor" href="##{node.id}"><i class="fa fa-anchor"></i></a>) #else elsif node.document.attr? 'sectlinks' link_start = %(<a class="link" href="##{node.id}">) link_end = '</a>' end end if slevel == 0 %(<h1#{id_attr} class="sect0">#{anchor}#{link_start}#{node.title}#{link_end}</h1> #{node.content}) else class_attr = (role = node.role) ? %( class="sect#{slevel} #{role}") : %( class="sect#{slevel}") sectnum = if node.numbered && !node.caption && slevel <= (node.document.attr 'sectnumlevels', 3).to_i %(#{node.sectnum} ) end %(<div#{class_attr}> <#{htag}#{id_attr}>#{anchor}#{link_start}#{sectnum}#{node.captioned_title}#{link_end}</#{htag}> #{slevel == 1 ? %[<div class="sectionbody">\n#{node.content}\n</div>] : node.content} </div>) end end def admonition node id_attr = node.id ? %( id="#{node.id}") : nil name = node.attr 'name' title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil caption = if node.document.attr? 'icons' if node.document.attr? 'icons', 'font' %(<i class="fa icon-#{name}" title="#{node.caption}"></i>) else %(<img src="#{node.icon_uri name}" alt="#{node.caption}"#{@void_element_slash}>) end else %(<div class="title">#{node.caption}</div>) end %(<div#{id_attr} class="admonitionblock #{name}#{(role = node.role) && " #{role}"}"> <table> <tr> <td class="icon"> #{caption} </td> <td class="content"> #{title_element}#{node.content} </td> </tr> </table> </div>) end def audio node xml = node.document.attr? 'htmlsyntax', 'xml' id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['audioblock', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(<div class="title">#{node.captioned_title}</div>\n) : nil %(<div#{id_attribute}#{class_attribute}> #{title_element}<div class="content"> <audio src="#{node.media_uri(node.attr 'target')}"#{(node.option? 'autoplay') ? (append_boolean_attribute 'autoplay', xml) : nil}#{(node.option? 'nocontrols') ? nil : (append_boolean_attribute 'controls', xml)}#{(node.option? 'loop') ? (append_boolean_attribute 'loop', xml) : nil}> Your browser does not support the audio tag. </audio> </div> </div>) end def colist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['colist', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") result << %(<div#{id_attribute}#{class_attribute}>) result << %(<div class="title">#{node.title}</div>) if node.title? if node.document.attr? 'icons' result << '<table>' font_icons = node.document.attr? 'icons', 'font' node.items.each_with_index do |item, i| num = i + 1 num_element = if font_icons %(<i class="conum" data-value="#{num}"></i><b>#{num}</b>) else %(<img src="#{node.icon_uri "callouts/#{num}"}" alt="#{num}"#{@void_element_slash}>) end result << %(<tr> <td>#{num_element}</td> <td>#{item.text}</td> </tr>) end result << '</table>' else result << '<ol>' node.items.each do |item| result << %(<li> <p>#{item.text}</p> </li>) end result << '</ol>' end result << '</div>' result * EOL end def dlist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = case node.style when 'qanda' ['qlist', 'qanda', node.role] when 'horizontal' ['hdlist', node.role] else ['dlist', node.style, node.role] end.compact class_attribute = %( class="#{classes * ' '}") result << %(<div#{id_attribute}#{class_attribute}>) result << %(<div class="title">#{node.title}</div>) if node.title? case node.style when 'qanda' result << '<ol>' node.items.each do |terms, dd| result << '<li>' [*terms].each do |dt| result << %(<p><em>#{dt.text}</em></p>) end if dd result << %(<p>#{dd.text}</p>) if dd.text? result << dd.content if dd.blocks? end result << '</li>' end result << '</ol>' when 'horizontal' slash = @void_element_slash result << '<table>' if (node.attr? 'labelwidth') || (node.attr? 'itemwidth') result << '<colgroup>' col_style_attribute = (node.attr? 'labelwidth') ? %( style="width: #{(node.attr 'labelwidth').chomp '%'}%;") : nil result << %(<col#{col_style_attribute}#{slash}>) col_style_attribute = (node.attr? 'itemwidth') ? %( style="width: #{(node.attr 'itemwidth').chomp '%'}%;") : nil result << %(<col#{col_style_attribute}#{slash}>) result << '</colgroup>' end node.items.each do |terms, dd| result << '<tr>' result << %(<td class="hdlist1#{(node.option? 'strong') ? ' strong' : nil}">) terms_array = [*terms] last_term = terms_array[-1] terms_array.each do |dt| result << dt.text result << %(<br#{slash}>) if dt != last_term end result << '</td>' result << '<td class="hdlist2">' if dd result << %(<p>#{dd.text}</p>) if dd.text? result << dd.content if dd.blocks? end result << '</td>' result << '</tr>' end result << '</table>' else result << '<dl>' dt_style_attribute = node.style ? nil : ' class="hdlist1"' node.items.each do |terms, dd| [*terms].each do |dt| result << %(<dt#{dt_style_attribute}>#{dt.text}</dt>) end if dd result << '<dd>' result << %(<p>#{dd.text}</p>) if dd.text? result << dd.content if dd.blocks? result << '</dd>' end end result << '</dl>' end result << '</div>' result * EOL end def example node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.captioned_title}</div>\n) : nil %(<div#{id_attribute} class="#{(role = node.role) ? ['exampleblock', role] * ' ' : 'exampleblock'}"> #{title_element}<div class="content"> #{node.content} </div> </div>) end def floating_title node tag_name = %(h#{node.level + 1}) id_attribute = node.id ? %( id="#{node.id}") : nil classes = [node.style, node.role].compact %(<#{tag_name}#{id_attribute} class="#{classes * ' '}">#{node.title}</#{tag_name}>) end def image node align = (node.attr? 'align') ? (node.attr 'align') : nil float = (node.attr? 'float') ? (node.attr 'float') : nil style_attribute = if align || float styles = [align ? %(text-align: #{align}) : nil, float ? %(float: #{float}) : nil].compact %( style="#{styles * ';'}") end width_attribute = (node.attr? 'width') ? %( width="#{node.attr 'width'}") : nil height_attribute = (node.attr? 'height') ? %( height="#{node.attr 'height'}") : nil img_element = %(<img src="#{node.image_uri node.attr('target')}" alt="#{node.attr 'alt'}"#{width_attribute}#{height_attribute}#{@void_element_slash}>) if (link = node.attr 'link') img_element = %(<a class="image" href="#{link}">#{img_element}</a>) end id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['imageblock', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.captioned_title}</div>) : nil %(<div#{id_attribute}#{class_attribute}#{style_attribute}> <div class="content"> #{img_element} </div>#{title_element} </div>) end def listing node nowrap = !(node.document.attr? 'prewrap') || (node.option? 'nowrap') if node.style == 'source' if (language = node.attr 'language', nil, false) code_attrs = %( data-lang="#{language}") else code_attrs = nil end case node.document.attr 'source-highlighter' when 'coderay' pre_class = %( class="CodeRay highlight#{nowrap ? ' nowrap' : nil}") when 'pygments' pre_class = %( class="pygments highlight#{nowrap ? ' nowrap' : nil}") when 'highlightjs', 'highlight.js' pre_class = %( class="highlightjs highlight#{nowrap ? ' nowrap' : nil}") code_attrs = %( class="language-#{language}"#{code_attrs}) if language when 'prettify' pre_class = %( class="prettyprint highlight#{nowrap ? ' nowrap' : nil}#{(node.attr? 'linenums') ? ' linenums' : nil}") code_attrs = %( class="language-#{language}"#{code_attrs}) if language when 'html-pipeline' pre_class = language ? %( lang="#{language}") : nil code_attrs = nil else pre_class = %( class="highlight#{nowrap ? ' nowrap' : nil}") code_attrs = %( class="language-#{language}"#{code_attrs}) if language end pre_start = %(<pre#{pre_class}><code#{code_attrs}>) pre_end = '</code></pre>' else pre_start = %(<pre#{nowrap ? ' class="nowrap"' : nil}>) pre_end = '</pre>' end id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.captioned_title}</div>\n) : nil %(<div#{id_attribute} class="listingblock#{(role = node.role) && " #{role}"}"> #{title_element}<div class="content"> #{pre_start}#{node.content}#{pre_end} </div> </div>) end def literal node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil nowrap = !(node.document.attr? 'prewrap') || (node.option? 'nowrap') %(<div#{id_attribute} class="literalblock#{(role = node.role) && " #{role}"}"> #{title_element}<div class="content"> <pre#{nowrap ? ' class="nowrap"' : nil}>#{node.content}</pre> </div> </div>) end def stem node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil open, close = BLOCK_MATH_DELIMITERS[node.style.to_sym] unless ((equation = node.content).start_with? open) && (equation.end_with? close) equation = %(#{open}#{equation}#{close}) end %(<div#{id_attribute} class="#{(role = node.role) ? ['stemblock', role] * ' ' : 'stemblock'}"> #{title_element}<div class="content"> #{equation} </div> </div>) end def olist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['olist', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") result << %(<div#{id_attribute}#{class_attribute}>) result << %(<div class="title">#{node.title}</div>) if node.title? type_attribute = (keyword = node.list_marker_keyword) ? %( type="#{keyword}") : nil start_attribute = (node.attr? 'start') ? %( start="#{node.attr 'start'}") : nil result << %(<ol class="#{node.style}"#{type_attribute}#{start_attribute}>) node.items.each do |item| result << '<li>' result << %(<p>#{item.text}</p>) result << item.content if item.blocks? result << '</li>' end result << '</ol>' result << '</div>' result * EOL end def open node if (style = node.style) == 'abstract' if node.parent == node.document && node.document.doctype == 'book' warn 'asciidoctor: WARNING: abstract block cannot be used in a document without a title when doctype is book. Excluding block content.' '' else id_attr = node.id ? %( id="#{node.id}") : nil title_el = node.title? ? %(<div class="title">#{node.title}</div>) : nil %(<div#{id_attr} class="quoteblock abstract#{(role = node.role) && " #{role}"}"> #{title_el}<blockquote> #{node.content} </blockquote> </div>) end elsif style == 'partintro' && (node.level != 0 || node.parent.context != :section || node.document.doctype != 'book') warn 'asciidoctor: ERROR: partintro block can only be used when doctype is book and it\'s a child of a book part. Excluding block content.' '' else id_attr = node.id ? %( id="#{node.id}") : nil title_el = node.title? ? %(<div class="title">#{node.title}</div>) : nil %(<div#{id_attr} class="openblock#{style && style != 'open' ? " #{style}" : ''}#{(role = node.role) && " #{role}"}"> #{title_el}<div class="content"> #{node.content} </div> </div>) end end def page_break node '<div style="page-break-after: always;"></div>' end def paragraph node attributes = if node.id if node.role %( id="#{node.id}" class="paragraph #{node.role}") else %( id="#{node.id}" class="paragraph") end elsif node.role %( class="paragraph #{node.role}") else ' class="paragraph"' end if node.title? %(<div#{attributes}> <div class="title">#{node.title}</div> <p>#{node.content}</p> </div>) else %(<div#{attributes}> <p>#{node.content}</p> </div>) end end def preamble node toc = if (node.attr? 'toc') && (node.attr? 'toc-placement', 'preamble') %(\n<div id="toc" class="#{node.attr 'toc-class', 'toc'}"> <div id="toctitle">#{node.attr 'toc-title'}</div> #{outline node.document} </div>) end %(<div id="preamble"> <div class="sectionbody"> #{node.content} </div>#{toc} </div>) end def quote node id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['quoteblock', node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.title}</div>) : nil attribution = (node.attr? 'attribution') ? (node.attr 'attribution') : nil citetitle = (node.attr? 'citetitle') ? (node.attr 'citetitle') : nil if attribution || citetitle cite_element = citetitle ? %(<cite>#{citetitle}</cite>) : nil attribution_text = attribution ? %(&#8212; #{attribution}#{citetitle ? "<br#{@void_element_slash}>\n" : nil}) : nil attribution_element = %(\n<div class="attribution">\n#{attribution_text}#{cite_element}\n</div>) else attribution_element = nil end %(<div#{id_attribute}#{class_attribute}>#{title_element} <blockquote> #{node.content} </blockquote>#{attribution_element} </div>) end def thematic_break node %(<hr#{@void_element_slash}>) end def sidebar node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil %(<div#{id_attribute} class="#{(role = node.role) ? ['sidebarblock', role] * ' ' : 'sidebarblock'}"> <div class="content"> #{title_element}#{node.content} </div> </div>) end def table node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['tableblock', %(frame-#{node.attr 'frame', 'all'}), %(grid-#{node.attr 'grid', 'all'})] styles = [] unless node.option? 'autowidth' if (tablepcwidth = node.attr 'tablepcwidth') == 100 classes << 'spread' else styles << %(width: #{tablepcwidth}%;) end end if (role = node.role) classes << role end class_attribute = %( class="#{classes * ' '}") styles << %(float: #{node.attr 'float'};) if node.attr? 'float' style_attribute = styles.empty? ? nil : %( style="#{styles * ' '}") result << %(<table#{id_attribute}#{class_attribute}#{style_attribute}>) result << %(<caption class="title">#{node.captioned_title}</caption>) if node.title? if (node.attr 'rowcount') > 0 slash = @void_element_slash result << '<colgroup>' if node.option? 'autowidth' tag = %(<col#{slash}>) node.columns.size.times do result << tag end else node.columns.each do |col| result << %(<col style="width: #{col.attr 'colpcwidth'}%;"#{slash}>) end end result << '</colgroup>' [:head, :foot, :body].select {|tsec| !node.rows[tsec].empty? }.each do |tsec| result << %(<t#{tsec}>) node.rows[tsec].each do |row| result << '<tr>' row.each do |cell| if tsec == :head cell_content = cell.text else case cell.style when :asciidoc cell_content = %(<div>#{cell.content}</div>) when :verse cell_content = %(<div class="verse">#{cell.text}</div>) when :literal cell_content = %(<div class="literal"><pre>#{cell.text}</pre></div>) else cell_content = '' cell.content.each do |text| cell_content = %(#{cell_content}<p class="tableblock">#{text}</p>) end end end cell_tag_name = (tsec == :head || cell.style == :header ? 'th' : 'td') cell_class_attribute = %( class="tableblock halign-#{cell.attr 'halign'} valign-#{cell.attr 'valign'}") cell_colspan_attribute = cell.colspan ? %( colspan="#{cell.colspan}") : nil cell_rowspan_attribute = cell.rowspan ? %( rowspan="#{cell.rowspan}") : nil cell_style_attribute = (node.document.attr? 'cellbgcolor') ? %( style="background-color: #{node.document.attr 'cellbgcolor'};") : nil result << %(<#{cell_tag_name}#{cell_class_attribute}#{cell_colspan_attribute}#{cell_rowspan_attribute}#{cell_style_attribute}>#{cell_content}</#{cell_tag_name}>) end result << '</tr>' end result << %(</t#{tsec}>) end end result << '</table>' result * EOL end def toc node return '<!-- toc disabled -->' unless (doc = node.document).attr?('toc-placement', 'macro') && doc.attr?('toc') if node.id id_attr = %( id="#{node.id}") title_id_attr = %( id="#{node.id}title") else id_attr = ' id="toc"' title_id_attr = ' id="toctitle"' end title = node.title? ? node.title : (doc.attr 'toc-title') levels = (node.attr? 'levels') ? (node.attr 'levels').to_i : nil role = node.role? ? node.role : (doc.attr 'toc-class', 'toc') %(<div#{id_attr} class="#{role}"> <div#{title_id_attr} class="title">#{title}</div> #{outline doc, :toclevels => levels} </div>) end def ulist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil div_classes = ['ulist', node.style, node.role].compact marker_checked = nil marker_unchecked = nil if (checklist = node.option? 'checklist') div_classes.insert 1, 'checklist' ul_class_attribute = ' class="checklist"' if node.option? 'interactive' if node.document.attr? 'htmlsyntax', 'xml' marker_checked = '<input type="checkbox" data-item-complete="1" checked="checked"/> ' marker_unchecked = '<input type="checkbox" data-item-complete="0"/> ' else marker_checked = '<input type="checkbox" data-item-complete="1" checked> ' marker_unchecked = '<input type="checkbox" data-item-complete="0"> ' end else if node.document.attr? 'icons', 'font' marker_checked = '<i class="fa fa-check-square-o"></i> ' marker_unchecked = '<i class="fa fa-square-o"></i> ' else marker_checked = '&#10003; ' marker_unchecked = '&#10063; ' end end else ul_class_attribute = node.style ? %( class="#{node.style}") : nil end result << %(<div#{id_attribute} class="#{div_classes * ' '}">) result << %(<div class="title">#{node.title}</div>) if node.title? result << %(<ul#{ul_class_attribute}>) node.items.each do |item| result << '<li>' if checklist && (item.attr? 'checkbox') result << %(<p>#{(item.attr? 'checked') ? marker_checked : marker_unchecked}#{item.text}</p>) else result << %(<p>#{item.text}</p>) end result << item.content if item.blocks? result << '</li>' end result << '</ul>' result << '</div>' result * EOL end def verse node id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['verseblock', node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.title}</div>) : nil attribution = (node.attr? 'attribution') ? (node.attr 'attribution') : nil citetitle = (node.attr? 'citetitle') ? (node.attr 'citetitle') : nil if attribution || citetitle cite_element = citetitle ? %(<cite>#{citetitle}</cite>) : nil attribution_text = attribution ? %(&#8212; #{attribution}#{citetitle ? "<br#{@void_element_slash}>\n" : nil}) : nil attribution_element = %(\n<div class="attribution">\n#{attribution_text}#{cite_element}\n</div>) else attribution_element = nil end %(<div#{id_attribute}#{class_attribute}>#{title_element} <pre class="content">#{node.content}</pre>#{attribution_element} </div>) end def video node xml = node.document.attr? 'htmlsyntax', 'xml' id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['videoblock', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.captioned_title}</div>) : nil width_attribute = (node.attr? 'width') ? %( width="#{node.attr 'width'}") : nil height_attribute = (node.attr? 'height') ? %( height="#{node.attr 'height'}") : nil case node.attr 'poster' when 'vimeo' start_anchor = (node.attr? 'start', nil, false) ? %(#at=#{node.attr 'start'}) : nil delimiter = '?' autoplay_param = (node.option? 'autoplay') ? %(#{delimiter}autoplay=1) : nil delimiter = '&amp;' if autoplay_param loop_param = (node.option? 'loop') ? %(#{delimiter}loop=1) : nil %(<div#{id_attribute}#{class_attribute}>#{title_element} <div class="content"> <iframe#{width_attribute}#{height_attribute} src="//player.vimeo.com/video/#{node.attr 'target'}#{start_anchor}#{autoplay_param}#{loop_param}" frameborder="0"#{(node.option? 'nofullscreen') ? nil : (append_boolean_attribute 'allowfullscreen', xml)}></iframe> </div> </div>) when 'youtube' rel_param_val = (node.option? 'related') ? 1 : 0 start_param = (node.attr? 'start', nil, false) ? %(&amp;start=#{node.attr 'start'}) : nil end_param = (node.attr? 'end', nil, false) ? %(&amp;end=#{node.attr 'end'}) : nil autoplay_param = (node.option? 'autoplay') ? '&amp;autoplay=1' : nil loop_param = (node.option? 'loop') ? '&amp;loop=1' : nil controls_param = (node.option? 'nocontrols') ? '&amp;controls=0' : nil # cover both ways of controlling fullscreen option if node.option? 'nofullscreen' fs_param = '&amp;fs=0' fs_attribute = nil else fs_param = nil fs_attribute = append_boolean_attribute 'allowfullscreen', xml end modest_param = (node.option? 'modest') ? '&amp;modestbranding=1' : nil theme_param = (node.attr? 'theme', nil, false) ? %(&amp;theme=#{node.attr 'theme'}) : nil hl_param = (node.attr? 'lang') ? %(&amp;hl=#{node.attr 'lang'}) : nil # parse video_id/list_id syntax where list_id (i.e., playlist) is optional target, list = (node.attr 'target').split '/', 2 if (list ||= (node.attr 'list', nil, false)) list_param = %(&amp;list=#{list}) else # parse dynamic playlist syntax: video_id1,video_id2,... target, playlist = target.split ',', 2 if (playlist ||= (node.attr 'playlist', nil, false)) # INFO playlist bar doesn't appear in Firefox unless showinfo=1 and modestbranding=1 list_param = %(&amp;playlist=#{playlist}) else list_param = nil end end %(<div#{id_attribute}#{class_attribute}>#{title_element} <div class="content"> <iframe#{width_attribute}#{height_attribute} src="//www.youtube.com/embed/#{target}?rel=#{rel_param_val}#{start_param}#{end_param}#{autoplay_param}#{loop_param}#{controls_param}#{list_param}#{fs_param}#{modest_param}#{theme_param}#{hl_param}" frameborder="0"#{fs_attribute}></iframe> </div> </div>) else poster_attribute = %(#{poster = node.attr 'poster'}).empty? ? nil : %( poster="#{node.media_uri poster}") start_t = node.attr 'start', nil, false end_t = node.attr 'end', nil, false time_anchor = (start_t || end_t) ? %(#t=#{start_t}#{end_t ? ',' : nil}#{end_t}) : nil %(<div#{id_attribute}#{class_attribute}>#{title_element} <div class="content"> <video src="#{node.media_uri(node.attr 'target')}#{time_anchor}"#{width_attribute}#{height_attribute}#{poster_attribute}#{(node.option? 'autoplay') ? (append_boolean_attribute 'autoplay', xml) : nil}#{(node.option? 'nocontrols') ? nil : (append_boolean_attribute 'controls', xml)}#{(node.option? 'loop') ? (append_boolean_attribute 'loop', xml) : nil}> Your browser does not support the video tag. </video> </div> </div>) end end def inline_anchor node target = node.target case node.type when :xref refid = (node.attr 'refid') || target # NOTE we lookup text in converter because DocBook doesn't need this logic text = node.text || (node.document.references[:ids][refid] || %([#{refid}])) # FIXME shouldn't target be refid? logic seems confused here %(<a href="#{target}">#{text}</a>) when :ref %(<a id="#{target}"></a>) when :link attrs = [] attrs << %( id="#{node.id}") if node.id if (role = node.role) attrs << %( class="#{role}") end attrs << %( title="#{node.attr 'title'}") if node.attr? 'title' attrs << %( target="#{node.attr 'window'}") if node.attr? 'window' %(<a href="#{target}"#{attrs.join}>#{node.text}</a>) when :bibref %(<a id="#{target}"></a>[#{target}]) else warn %(asciidoctor: WARNING: unknown anchor type: #{node.type.inspect}) end end def inline_break node %(#{node.text}<br#{@void_element_slash}>) end def inline_button node %(<b class="button">#{node.text}</b>) end def inline_callout node if node.document.attr? 'icons', 'font' %(<i class="conum" data-value="#{node.text}"></i><b>(#{node.text})</b>) elsif node.document.attr? 'icons' src = node.icon_uri("callouts/#{node.text}") %(<img src="#{src}" alt="#{node.text}"#{@void_element_slash}>) else %(<b class="conum">(#{node.text})</b>) end end def inline_footnote node if (index = node.attr 'index') if node.type == :xref %(<span class="footnoteref">[<a class="footnote" href="#_footnote_#{index}" title="View footnote.">#{index}</a>]</span>) else id_attr = node.id ? %( id="_footnote_#{node.id}") : nil %(<span class="footnote"#{id_attr}>[<a id="_footnoteref_#{index}" class="footnote" href="#_footnote_#{index}" title="View footnote.">#{index}</a>]</span>) end elsif node.type == :xref %(<span class="footnoteref red" title="Unresolved footnote reference.">[#{node.text}]</span>) end end def inline_image node if (type = node.type) == 'icon' && (node.document.attr? 'icons', 'font') style_class = %(fa fa-#{node.target}) if node.attr? 'size' style_class = %(#{style_class} fa-#{node.attr 'size'}) end if node.attr? 'rotate' style_class = %(#{style_class} fa-rotate-#{node.attr 'rotate'}) end if node.attr? 'flip' style_class = %(#{style_class} fa-flip-#{node.attr 'flip'}) end title_attribute = (node.attr? 'title') ? %( title="#{node.attr 'title'}") : nil img = %(<i class="#{style_class}"#{title_attribute}></i>) elsif type == 'icon' && !(node.document.attr? 'icons') img = %([#{node.attr 'alt'}]) else resolved_target = (type == 'icon') ? (node.icon_uri node.target) : (node.image_uri node.target) attrs = ['alt', 'width', 'height', 'title'].map {|name| (node.attr? name) ? %( #{name}="#{node.attr name}") : nil }.join img = %(<img src="#{resolved_target}"#{attrs}#{@void_element_slash}>) end if node.attr? 'link' window_attr = (node.attr? 'window') ? %( target="#{node.attr 'window'}") : nil img = %(<a class="image" href="#{node.attr 'link'}"#{window_attr}>#{img}</a>) end style_classes = (role = node.role) ? %(#{type} #{role}) : type style_attr = (node.attr? 'float') ? %( style="float: #{node.attr 'float'}") : nil %(<span class="#{style_classes}"#{style_attr}>#{img}</span>) end def inline_indexterm node node.type == :visible ? node.text : '' end def inline_kbd node if (keys = node.attr 'keys').size == 1 %(<kbd>#{keys[0]}</kbd>) else key_combo = keys.map {|key| %(<kbd>#{key}</kbd>+) }.join.chop %(<span class="keyseq">#{key_combo}</span>) end end def inline_menu node menu = node.attr 'menu' if !(submenus = node.attr 'submenus').empty? submenu_path = submenus.map {|submenu| %(<span class="submenu">#{submenu}</span>&#160;&#9656; ) }.join.chop %(<span class="menuseq"><span class="menu">#{menu}</span>&#160;&#9656; #{submenu_path} <span class="menuitem">#{node.attr 'menuitem'}</span></span>) elsif (menuitem = node.attr 'menuitem') %(<span class="menuseq"><span class="menu">#{menu}</span>&#160;&#9656; <span class="menuitem">#{menuitem}</span></span>) else %(<span class="menu">#{menu}</span>) end end def inline_quoted node open, close, is_tag = QUOTE_TAGS[node.type] if (role = node.role) if is_tag quoted_text = %(#{open.chop} class="#{role}">#{node.text}#{close}) else quoted_text = %(<span class="#{role}">#{open}#{node.text}#{close}</span>) end else quoted_text = %(#{open}#{node.text}#{close}) end node.id ? %(<a id="#{node.id}"></a>#{quoted_text}) : quoted_text end def append_boolean_attribute name, xml xml ? %( #{name}="#{name}") : %( #{name}) end end end resolve #1198 (again) use .inspect to print MathJax delimiters # encoding: UTF-8 module Asciidoctor # A built-in {Converter} implementation that generates HTML 5 output # consistent with the html5 backend from AsciiDoc Python. class Converter::Html5Converter < Converter::BuiltIn QUOTE_TAGS = { :emphasis => ['<em>', '</em>', true], :strong => ['<strong>', '</strong>', true], :monospaced => ['<code>', '</code>', true], :superscript => ['<sup>', '</sup>', true], :subscript => ['<sub>', '</sub>', true], :double => ['&#8220;', '&#8221;', false], :single => ['&#8216;', '&#8217;', false], :mark => ['<mark>', '</mark>', true], :asciimath => ['\\$', '\\$', false], :latexmath => ['\\(', '\\)', false] # Opal can't resolve these constants when referenced here #:asciimath => INLINE_MATH_DELIMITERS[:asciimath] + [false], #:latexmath => INLINE_MATH_DELIMITERS[:latexmath] + [false] } QUOTE_TAGS.default = [nil, nil, nil] def initialize backend, opts = {} @xml_mode = opts[:htmlsyntax] == 'xml' @void_element_slash = @xml_mode ? '/' : nil @stylesheets = Stylesheets.instance end def document node result = [] slash = @void_element_slash br = %(<br#{slash}>) asset_uri_scheme = (node.attr 'asset-uri-scheme', 'https') asset_uri_scheme = %(#{asset_uri_scheme}:) unless asset_uri_scheme.empty? cdn_base = %(#{asset_uri_scheme}//cdnjs.cloudflare.com/ajax/libs) linkcss = node.safe >= SafeMode::SECURE || (node.attr? 'linkcss') result << '<!DOCTYPE html>' lang_attribute = (node.attr? 'nolang') ? nil : %( lang="#{node.attr 'lang', 'en'}") result << %(<html#{@xml_mode ? ' xmlns="http://www.w3.org/1999/xhtml"' : nil}#{lang_attribute}>) result << %(<head> <meta charset="#{node.attr 'encoding', 'UTF-8'}"#{slash}> <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"#{slash}><![endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"#{slash}> <meta name="generator" content="Asciidoctor #{node.attr 'asciidoctor-version'}"#{slash}>) result << %(<meta name="application-name" content="#{node.attr 'app-name'}"#{slash}>) if node.attr? 'app-name' result << %(<meta name="description" content="#{node.attr 'description'}"#{slash}>) if node.attr? 'description' result << %(<meta name="keywords" content="#{node.attr 'keywords'}"#{slash}>) if node.attr? 'keywords' result << %(<meta name="author" content="#{node.attr 'authors'}"#{slash}>) if node.attr? 'authors' result << %(<meta name="copyright" content="#{node.attr 'copyright'}"#{slash}>) if node.attr? 'copyright' result << %(<title>#{node.doctitle :sanitize => true, :use_fallback => true}</title>) if DEFAULT_STYLESHEET_KEYS.include?(node.attr 'stylesheet') if (webfonts = node.attr 'webfonts') result << %(<link rel="stylesheet" href="#{asset_uri_scheme}//fonts.googleapis.com/css?family=#{webfonts.empty? ? 'Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400' : webfonts}"#{slash}>) end if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path DEFAULT_STYLESHEET_NAME, (node.attr 'stylesdir', ''), false}"#{slash}>) else result << @stylesheets.embed_primary_stylesheet end elsif node.attr? 'stylesheet' if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path((node.attr 'stylesheet'), (node.attr 'stylesdir', ''))}"#{slash}>) else result << %(<style> #{node.read_asset node.normalize_system_path((node.attr 'stylesheet'), (node.attr 'stylesdir', '')), :warn_on_failure => true} </style>) end end if node.attr? 'icons', 'font' if node.attr? 'iconfont-remote' result << %(<link rel="stylesheet" href="#{node.attr 'iconfont-cdn', %[#{cdn_base}/font-awesome/4.2.0/css/font-awesome.min.css]}"#{slash}>) else iconfont_stylesheet = %(#{node.attr 'iconfont-name', 'font-awesome'}.css) result << %(<link rel="stylesheet" href="#{node.normalize_web_path iconfont_stylesheet, (node.attr 'stylesdir', ''), false}"#{slash}>) end end case node.attr 'source-highlighter' when 'coderay' if (node.attr 'coderay-css', 'class') == 'class' if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path @stylesheets.coderay_stylesheet_name, (node.attr 'stylesdir', ''), false}"#{slash}>) else result << @stylesheets.embed_coderay_stylesheet end end when 'pygments' if (node.attr 'pygments-css', 'class') == 'class' pygments_style = node.attr 'pygments-style' if linkcss result << %(<link rel="stylesheet" href="#{node.normalize_web_path @stylesheets.pygments_stylesheet_name(pygments_style), (node.attr 'stylesdir', ''), false}"#{slash}>) else result << (@stylesheets.embed_pygments_stylesheet pygments_style) end end when 'highlightjs', 'highlight.js' highlightjs_path = node.attr 'highlightjsdir', %(#{cdn_base}/highlight.js/8.4) result << %(<link rel="stylesheet" href="#{highlightjs_path}/styles/#{node.attr 'highlightjs-theme', 'github'}.min.css"#{slash}> <script src="#{highlightjs_path}/highlight.min.js"></script> <script>hljs.initHighlightingOnLoad()</script>) when 'prettify' prettify_path = node.attr 'prettifydir', %(#{cdn_base}/prettify/r298) result << %(<link rel="stylesheet" href="#{prettify_path}/#{node.attr 'prettify-theme', 'prettify'}.min.css"#{slash}> <script src="#{prettify_path}/prettify.min.js"></script> <script>document.addEventListener('DOMContentLoaded', prettyPrint)</script>) end if node.attr? 'stem' # IMPORTANT to_s calls on delimiter arrays are intentional for JavaScript compat (emulates JSON.stringify) eqnums_val = node.attr 'eqnums', 'none' eqnums_val = 'AMS' if eqnums_val == '' eqnums_opt = %( equationNumbers: { autoNumber: "#{eqnums_val}" } ) result << %(<script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: { inlineMath: [#{INLINE_MATH_DELIMITERS[:latexmath].inspect}], displayMath: [#{BLOCK_MATH_DELIMITERS[:latexmath].inspect}], ignoreClass: "nostem|nolatexmath" }, asciimath2jax: { delimiters: [#{BLOCK_MATH_DELIMITERS[:asciimath].inspect}], ignoreClass: "nostem|noasciimath" }, TeX: {#{eqnums_opt}} }); </script> <script src="#{cdn_base}/mathjax/2.4.0/MathJax.js?config=TeX-MML-AM_HTMLorMML"></script>) end unless (docinfo_content = node.docinfo).empty? result << docinfo_content end result << '</head>' body_attrs = [] if node.id body_attrs << %(id="#{node.id}") end if (node.attr? 'toc-class') && (node.attr? 'toc') && (node.attr? 'toc-placement', 'auto') body_attrs << %(class="#{node.doctype} #{node.attr 'toc-class'} toc-#{node.attr 'toc-position', 'header'}") else body_attrs << %(class="#{node.doctype}") end if node.attr? 'max-width' body_attrs << %(style="max-width: #{node.attr 'max-width'};") end result << %(<body #{body_attrs * ' '}>) unless node.noheader result << '<div id="header">' if node.doctype == 'manpage' result << %(<h1>#{node.doctitle} Manual Page</h1>) if (node.attr? 'toc') && (node.attr? 'toc-placement', 'auto') result << %(<div id="toc" class="#{node.attr 'toc-class', 'toc'}"> <div id="toctitle">#{node.attr 'toc-title'}</div> #{outline node} </div>) end result << %(<h2>#{node.attr 'manname-title'}</h2> <div class="sectionbody"> <p>#{node.attr 'manname'} - #{node.attr 'manpurpose'}</p> </div>) else if node.has_header? result << %(<h1>#{node.header.title}</h1>) unless node.notitle details = [] if node.attr? 'author' details << %(<span id="author" class="author">#{node.attr 'author'}</span>#{br}) if node.attr? 'email' details << %(<span id="email" class="email">#{node.sub_macros(node.attr 'email')}</span>#{br}) end if (authorcount = (node.attr 'authorcount').to_i) > 1 (2..authorcount).each do |idx| details << %(<span id="author#{idx}" class="author">#{node.attr "author_#{idx}"}</span>#{br}) if node.attr? %(email_#{idx}) details << %(<span id="email#{idx}" class="email">#{node.sub_macros(node.attr "email_#{idx}")}</span>#{br}) end end end end if node.attr? 'revnumber' details << %(<span id="revnumber">#{((node.attr 'version-label') || '').downcase} #{node.attr 'revnumber'}#{(node.attr? 'revdate') ? ',' : ''}</span>) end if node.attr? 'revdate' details << %(<span id="revdate">#{node.attr 'revdate'}</span>) end if node.attr? 'revremark' details << %(#{br}<span id="revremark">#{node.attr 'revremark'}</span>) end unless details.empty? result << '<div class="details">' result.concat details result << '</div>' end end if (node.attr? 'toc') && (node.attr? 'toc-placement', 'auto') result << %(<div id="toc" class="#{node.attr 'toc-class', 'toc'}"> <div id="toctitle">#{node.attr 'toc-title'}</div> #{outline node} </div>) end end result << '</div>' end result << %(<div id="content"> #{node.content} </div>) if node.footnotes? && !(node.attr? 'nofootnotes') result << %(<div id="footnotes"> <hr#{slash}>) node.footnotes.each do |footnote| result << %(<div class="footnote" id="_footnote_#{footnote.index}"> <a href="#_footnoteref_#{footnote.index}">#{footnote.index}</a>. #{footnote.text} </div>) end result << '</div>' end unless node.nofooter result << '<div id="footer">' result << '<div id="footer-text">' if node.attr? 'revnumber' result << %(#{node.attr 'version-label'} #{node.attr 'revnumber'}#{br}) end if node.attr? 'last-update-label' result << %(#{node.attr 'last-update-label'} #{node.attr 'docdatetime'}) end result << '</div>' unless (docinfo_content = node.docinfo :footer).empty? result << docinfo_content end result << '</div>' end result << '</body>' result << '</html>' result * EOL end def embedded node result = [] if !node.notitle && node.has_header? id_attr = node.id ? %( id="#{node.id}") : nil result << %(<h1#{id_attr}>#{node.header.title}</h1>) end result << node.content if node.footnotes? && !(node.attr? 'nofootnotes') result << %(<div id="footnotes"> <hr#{@void_element_slash}>) node.footnotes.each do |footnote| result << %(<div class="footnote" id="_footnote_#{footnote.index}"> <a href="#_footnoteref_#{footnote.index}">#{footnote.index}</a> #{footnote.text} </div>) end result << '</div>' end result * EOL end def outline node, opts = {} return if (sections = node.sections).empty? sectnumlevels = opts[:sectnumlevels] || (node.document.attr 'sectnumlevels', 3).to_i toclevels = opts[:toclevels] || (node.document.attr 'toclevels', 2).to_i result = [] # FIXME the level for special sections should be set correctly in the model # slevel will only be 0 if we have a book doctype with parts slevel = (first_section = sections[0]).level slevel = 1 if slevel == 0 && first_section.special result << %(<ul class="sectlevel#{slevel}">) sections.each do |section| section_num = (section.numbered && !section.caption && section.level <= sectnumlevels) ? %(#{section.sectnum} ) : nil if section.level < toclevels && (child_toc_level = outline section, :toclevels => toclevels, :secnumlevels => sectnumlevels) result << %(<li><a href="##{section.id}">#{section_num}#{section.captioned_title}</a>) result << child_toc_level result << '</li>' else result << %(<li><a href="##{section.id}">#{section_num}#{section.captioned_title}</a></li>) end end result << '</ul>' result * EOL end def section node slevel = node.level # QUESTION should the check for slevel be done in section? slevel = 1 if slevel == 0 && node.special htag = %(h#{slevel + 1}) id_attr = anchor = link_start = link_end = nil if node.id id_attr = %( id="#{node.id}") if node.document.attr? 'sectanchors' anchor = %(<a class="anchor" href="##{node.id}"></a>) # possible idea - anchor icons GitHub-style #if node.document.attr? 'icons', 'font' # anchor = %(<a class="anchor" href="##{node.id}"><i class="fa fa-anchor"></i></a>) #else elsif node.document.attr? 'sectlinks' link_start = %(<a class="link" href="##{node.id}">) link_end = '</a>' end end if slevel == 0 %(<h1#{id_attr} class="sect0">#{anchor}#{link_start}#{node.title}#{link_end}</h1> #{node.content}) else class_attr = (role = node.role) ? %( class="sect#{slevel} #{role}") : %( class="sect#{slevel}") sectnum = if node.numbered && !node.caption && slevel <= (node.document.attr 'sectnumlevels', 3).to_i %(#{node.sectnum} ) end %(<div#{class_attr}> <#{htag}#{id_attr}>#{anchor}#{link_start}#{sectnum}#{node.captioned_title}#{link_end}</#{htag}> #{slevel == 1 ? %[<div class="sectionbody">\n#{node.content}\n</div>] : node.content} </div>) end end def admonition node id_attr = node.id ? %( id="#{node.id}") : nil name = node.attr 'name' title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil caption = if node.document.attr? 'icons' if node.document.attr? 'icons', 'font' %(<i class="fa icon-#{name}" title="#{node.caption}"></i>) else %(<img src="#{node.icon_uri name}" alt="#{node.caption}"#{@void_element_slash}>) end else %(<div class="title">#{node.caption}</div>) end %(<div#{id_attr} class="admonitionblock #{name}#{(role = node.role) && " #{role}"}"> <table> <tr> <td class="icon"> #{caption} </td> <td class="content"> #{title_element}#{node.content} </td> </tr> </table> </div>) end def audio node xml = node.document.attr? 'htmlsyntax', 'xml' id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['audioblock', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(<div class="title">#{node.captioned_title}</div>\n) : nil %(<div#{id_attribute}#{class_attribute}> #{title_element}<div class="content"> <audio src="#{node.media_uri(node.attr 'target')}"#{(node.option? 'autoplay') ? (append_boolean_attribute 'autoplay', xml) : nil}#{(node.option? 'nocontrols') ? nil : (append_boolean_attribute 'controls', xml)}#{(node.option? 'loop') ? (append_boolean_attribute 'loop', xml) : nil}> Your browser does not support the audio tag. </audio> </div> </div>) end def colist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['colist', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") result << %(<div#{id_attribute}#{class_attribute}>) result << %(<div class="title">#{node.title}</div>) if node.title? if node.document.attr? 'icons' result << '<table>' font_icons = node.document.attr? 'icons', 'font' node.items.each_with_index do |item, i| num = i + 1 num_element = if font_icons %(<i class="conum" data-value="#{num}"></i><b>#{num}</b>) else %(<img src="#{node.icon_uri "callouts/#{num}"}" alt="#{num}"#{@void_element_slash}>) end result << %(<tr> <td>#{num_element}</td> <td>#{item.text}</td> </tr>) end result << '</table>' else result << '<ol>' node.items.each do |item| result << %(<li> <p>#{item.text}</p> </li>) end result << '</ol>' end result << '</div>' result * EOL end def dlist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = case node.style when 'qanda' ['qlist', 'qanda', node.role] when 'horizontal' ['hdlist', node.role] else ['dlist', node.style, node.role] end.compact class_attribute = %( class="#{classes * ' '}") result << %(<div#{id_attribute}#{class_attribute}>) result << %(<div class="title">#{node.title}</div>) if node.title? case node.style when 'qanda' result << '<ol>' node.items.each do |terms, dd| result << '<li>' [*terms].each do |dt| result << %(<p><em>#{dt.text}</em></p>) end if dd result << %(<p>#{dd.text}</p>) if dd.text? result << dd.content if dd.blocks? end result << '</li>' end result << '</ol>' when 'horizontal' slash = @void_element_slash result << '<table>' if (node.attr? 'labelwidth') || (node.attr? 'itemwidth') result << '<colgroup>' col_style_attribute = (node.attr? 'labelwidth') ? %( style="width: #{(node.attr 'labelwidth').chomp '%'}%;") : nil result << %(<col#{col_style_attribute}#{slash}>) col_style_attribute = (node.attr? 'itemwidth') ? %( style="width: #{(node.attr 'itemwidth').chomp '%'}%;") : nil result << %(<col#{col_style_attribute}#{slash}>) result << '</colgroup>' end node.items.each do |terms, dd| result << '<tr>' result << %(<td class="hdlist1#{(node.option? 'strong') ? ' strong' : nil}">) terms_array = [*terms] last_term = terms_array[-1] terms_array.each do |dt| result << dt.text result << %(<br#{slash}>) if dt != last_term end result << '</td>' result << '<td class="hdlist2">' if dd result << %(<p>#{dd.text}</p>) if dd.text? result << dd.content if dd.blocks? end result << '</td>' result << '</tr>' end result << '</table>' else result << '<dl>' dt_style_attribute = node.style ? nil : ' class="hdlist1"' node.items.each do |terms, dd| [*terms].each do |dt| result << %(<dt#{dt_style_attribute}>#{dt.text}</dt>) end if dd result << '<dd>' result << %(<p>#{dd.text}</p>) if dd.text? result << dd.content if dd.blocks? result << '</dd>' end end result << '</dl>' end result << '</div>' result * EOL end def example node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.captioned_title}</div>\n) : nil %(<div#{id_attribute} class="#{(role = node.role) ? ['exampleblock', role] * ' ' : 'exampleblock'}"> #{title_element}<div class="content"> #{node.content} </div> </div>) end def floating_title node tag_name = %(h#{node.level + 1}) id_attribute = node.id ? %( id="#{node.id}") : nil classes = [node.style, node.role].compact %(<#{tag_name}#{id_attribute} class="#{classes * ' '}">#{node.title}</#{tag_name}>) end def image node align = (node.attr? 'align') ? (node.attr 'align') : nil float = (node.attr? 'float') ? (node.attr 'float') : nil style_attribute = if align || float styles = [align ? %(text-align: #{align}) : nil, float ? %(float: #{float}) : nil].compact %( style="#{styles * ';'}") end width_attribute = (node.attr? 'width') ? %( width="#{node.attr 'width'}") : nil height_attribute = (node.attr? 'height') ? %( height="#{node.attr 'height'}") : nil img_element = %(<img src="#{node.image_uri node.attr('target')}" alt="#{node.attr 'alt'}"#{width_attribute}#{height_attribute}#{@void_element_slash}>) if (link = node.attr 'link') img_element = %(<a class="image" href="#{link}">#{img_element}</a>) end id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['imageblock', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.captioned_title}</div>) : nil %(<div#{id_attribute}#{class_attribute}#{style_attribute}> <div class="content"> #{img_element} </div>#{title_element} </div>) end def listing node nowrap = !(node.document.attr? 'prewrap') || (node.option? 'nowrap') if node.style == 'source' if (language = node.attr 'language', nil, false) code_attrs = %( data-lang="#{language}") else code_attrs = nil end case node.document.attr 'source-highlighter' when 'coderay' pre_class = %( class="CodeRay highlight#{nowrap ? ' nowrap' : nil}") when 'pygments' pre_class = %( class="pygments highlight#{nowrap ? ' nowrap' : nil}") when 'highlightjs', 'highlight.js' pre_class = %( class="highlightjs highlight#{nowrap ? ' nowrap' : nil}") code_attrs = %( class="language-#{language}"#{code_attrs}) if language when 'prettify' pre_class = %( class="prettyprint highlight#{nowrap ? ' nowrap' : nil}#{(node.attr? 'linenums') ? ' linenums' : nil}") code_attrs = %( class="language-#{language}"#{code_attrs}) if language when 'html-pipeline' pre_class = language ? %( lang="#{language}") : nil code_attrs = nil else pre_class = %( class="highlight#{nowrap ? ' nowrap' : nil}") code_attrs = %( class="language-#{language}"#{code_attrs}) if language end pre_start = %(<pre#{pre_class}><code#{code_attrs}>) pre_end = '</code></pre>' else pre_start = %(<pre#{nowrap ? ' class="nowrap"' : nil}>) pre_end = '</pre>' end id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.captioned_title}</div>\n) : nil %(<div#{id_attribute} class="listingblock#{(role = node.role) && " #{role}"}"> #{title_element}<div class="content"> #{pre_start}#{node.content}#{pre_end} </div> </div>) end def literal node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil nowrap = !(node.document.attr? 'prewrap') || (node.option? 'nowrap') %(<div#{id_attribute} class="literalblock#{(role = node.role) && " #{role}"}"> #{title_element}<div class="content"> <pre#{nowrap ? ' class="nowrap"' : nil}>#{node.content}</pre> </div> </div>) end def stem node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil open, close = BLOCK_MATH_DELIMITERS[node.style.to_sym] unless ((equation = node.content).start_with? open) && (equation.end_with? close) equation = %(#{open}#{equation}#{close}) end %(<div#{id_attribute} class="#{(role = node.role) ? ['stemblock', role] * ' ' : 'stemblock'}"> #{title_element}<div class="content"> #{equation} </div> </div>) end def olist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['olist', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") result << %(<div#{id_attribute}#{class_attribute}>) result << %(<div class="title">#{node.title}</div>) if node.title? type_attribute = (keyword = node.list_marker_keyword) ? %( type="#{keyword}") : nil start_attribute = (node.attr? 'start') ? %( start="#{node.attr 'start'}") : nil result << %(<ol class="#{node.style}"#{type_attribute}#{start_attribute}>) node.items.each do |item| result << '<li>' result << %(<p>#{item.text}</p>) result << item.content if item.blocks? result << '</li>' end result << '</ol>' result << '</div>' result * EOL end def open node if (style = node.style) == 'abstract' if node.parent == node.document && node.document.doctype == 'book' warn 'asciidoctor: WARNING: abstract block cannot be used in a document without a title when doctype is book. Excluding block content.' '' else id_attr = node.id ? %( id="#{node.id}") : nil title_el = node.title? ? %(<div class="title">#{node.title}</div>) : nil %(<div#{id_attr} class="quoteblock abstract#{(role = node.role) && " #{role}"}"> #{title_el}<blockquote> #{node.content} </blockquote> </div>) end elsif style == 'partintro' && (node.level != 0 || node.parent.context != :section || node.document.doctype != 'book') warn 'asciidoctor: ERROR: partintro block can only be used when doctype is book and it\'s a child of a book part. Excluding block content.' '' else id_attr = node.id ? %( id="#{node.id}") : nil title_el = node.title? ? %(<div class="title">#{node.title}</div>) : nil %(<div#{id_attr} class="openblock#{style && style != 'open' ? " #{style}" : ''}#{(role = node.role) && " #{role}"}"> #{title_el}<div class="content"> #{node.content} </div> </div>) end end def page_break node '<div style="page-break-after: always;"></div>' end def paragraph node attributes = if node.id if node.role %( id="#{node.id}" class="paragraph #{node.role}") else %( id="#{node.id}" class="paragraph") end elsif node.role %( class="paragraph #{node.role}") else ' class="paragraph"' end if node.title? %(<div#{attributes}> <div class="title">#{node.title}</div> <p>#{node.content}</p> </div>) else %(<div#{attributes}> <p>#{node.content}</p> </div>) end end def preamble node toc = if (node.attr? 'toc') && (node.attr? 'toc-placement', 'preamble') %(\n<div id="toc" class="#{node.attr 'toc-class', 'toc'}"> <div id="toctitle">#{node.attr 'toc-title'}</div> #{outline node.document} </div>) end %(<div id="preamble"> <div class="sectionbody"> #{node.content} </div>#{toc} </div>) end def quote node id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['quoteblock', node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.title}</div>) : nil attribution = (node.attr? 'attribution') ? (node.attr 'attribution') : nil citetitle = (node.attr? 'citetitle') ? (node.attr 'citetitle') : nil if attribution || citetitle cite_element = citetitle ? %(<cite>#{citetitle}</cite>) : nil attribution_text = attribution ? %(&#8212; #{attribution}#{citetitle ? "<br#{@void_element_slash}>\n" : nil}) : nil attribution_element = %(\n<div class="attribution">\n#{attribution_text}#{cite_element}\n</div>) else attribution_element = nil end %(<div#{id_attribute}#{class_attribute}>#{title_element} <blockquote> #{node.content} </blockquote>#{attribution_element} </div>) end def thematic_break node %(<hr#{@void_element_slash}>) end def sidebar node id_attribute = node.id ? %( id="#{node.id}") : nil title_element = node.title? ? %(<div class="title">#{node.title}</div>\n) : nil %(<div#{id_attribute} class="#{(role = node.role) ? ['sidebarblock', role] * ' ' : 'sidebarblock'}"> <div class="content"> #{title_element}#{node.content} </div> </div>) end def table node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['tableblock', %(frame-#{node.attr 'frame', 'all'}), %(grid-#{node.attr 'grid', 'all'})] styles = [] unless node.option? 'autowidth' if (tablepcwidth = node.attr 'tablepcwidth') == 100 classes << 'spread' else styles << %(width: #{tablepcwidth}%;) end end if (role = node.role) classes << role end class_attribute = %( class="#{classes * ' '}") styles << %(float: #{node.attr 'float'};) if node.attr? 'float' style_attribute = styles.empty? ? nil : %( style="#{styles * ' '}") result << %(<table#{id_attribute}#{class_attribute}#{style_attribute}>) result << %(<caption class="title">#{node.captioned_title}</caption>) if node.title? if (node.attr 'rowcount') > 0 slash = @void_element_slash result << '<colgroup>' if node.option? 'autowidth' tag = %(<col#{slash}>) node.columns.size.times do result << tag end else node.columns.each do |col| result << %(<col style="width: #{col.attr 'colpcwidth'}%;"#{slash}>) end end result << '</colgroup>' [:head, :foot, :body].select {|tsec| !node.rows[tsec].empty? }.each do |tsec| result << %(<t#{tsec}>) node.rows[tsec].each do |row| result << '<tr>' row.each do |cell| if tsec == :head cell_content = cell.text else case cell.style when :asciidoc cell_content = %(<div>#{cell.content}</div>) when :verse cell_content = %(<div class="verse">#{cell.text}</div>) when :literal cell_content = %(<div class="literal"><pre>#{cell.text}</pre></div>) else cell_content = '' cell.content.each do |text| cell_content = %(#{cell_content}<p class="tableblock">#{text}</p>) end end end cell_tag_name = (tsec == :head || cell.style == :header ? 'th' : 'td') cell_class_attribute = %( class="tableblock halign-#{cell.attr 'halign'} valign-#{cell.attr 'valign'}") cell_colspan_attribute = cell.colspan ? %( colspan="#{cell.colspan}") : nil cell_rowspan_attribute = cell.rowspan ? %( rowspan="#{cell.rowspan}") : nil cell_style_attribute = (node.document.attr? 'cellbgcolor') ? %( style="background-color: #{node.document.attr 'cellbgcolor'};") : nil result << %(<#{cell_tag_name}#{cell_class_attribute}#{cell_colspan_attribute}#{cell_rowspan_attribute}#{cell_style_attribute}>#{cell_content}</#{cell_tag_name}>) end result << '</tr>' end result << %(</t#{tsec}>) end end result << '</table>' result * EOL end def toc node return '<!-- toc disabled -->' unless (doc = node.document).attr?('toc-placement', 'macro') && doc.attr?('toc') if node.id id_attr = %( id="#{node.id}") title_id_attr = %( id="#{node.id}title") else id_attr = ' id="toc"' title_id_attr = ' id="toctitle"' end title = node.title? ? node.title : (doc.attr 'toc-title') levels = (node.attr? 'levels') ? (node.attr 'levels').to_i : nil role = node.role? ? node.role : (doc.attr 'toc-class', 'toc') %(<div#{id_attr} class="#{role}"> <div#{title_id_attr} class="title">#{title}</div> #{outline doc, :toclevels => levels} </div>) end def ulist node result = [] id_attribute = node.id ? %( id="#{node.id}") : nil div_classes = ['ulist', node.style, node.role].compact marker_checked = nil marker_unchecked = nil if (checklist = node.option? 'checklist') div_classes.insert 1, 'checklist' ul_class_attribute = ' class="checklist"' if node.option? 'interactive' if node.document.attr? 'htmlsyntax', 'xml' marker_checked = '<input type="checkbox" data-item-complete="1" checked="checked"/> ' marker_unchecked = '<input type="checkbox" data-item-complete="0"/> ' else marker_checked = '<input type="checkbox" data-item-complete="1" checked> ' marker_unchecked = '<input type="checkbox" data-item-complete="0"> ' end else if node.document.attr? 'icons', 'font' marker_checked = '<i class="fa fa-check-square-o"></i> ' marker_unchecked = '<i class="fa fa-square-o"></i> ' else marker_checked = '&#10003; ' marker_unchecked = '&#10063; ' end end else ul_class_attribute = node.style ? %( class="#{node.style}") : nil end result << %(<div#{id_attribute} class="#{div_classes * ' '}">) result << %(<div class="title">#{node.title}</div>) if node.title? result << %(<ul#{ul_class_attribute}>) node.items.each do |item| result << '<li>' if checklist && (item.attr? 'checkbox') result << %(<p>#{(item.attr? 'checked') ? marker_checked : marker_unchecked}#{item.text}</p>) else result << %(<p>#{item.text}</p>) end result << item.content if item.blocks? result << '</li>' end result << '</ul>' result << '</div>' result * EOL end def verse node id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['verseblock', node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.title}</div>) : nil attribution = (node.attr? 'attribution') ? (node.attr 'attribution') : nil citetitle = (node.attr? 'citetitle') ? (node.attr 'citetitle') : nil if attribution || citetitle cite_element = citetitle ? %(<cite>#{citetitle}</cite>) : nil attribution_text = attribution ? %(&#8212; #{attribution}#{citetitle ? "<br#{@void_element_slash}>\n" : nil}) : nil attribution_element = %(\n<div class="attribution">\n#{attribution_text}#{cite_element}\n</div>) else attribution_element = nil end %(<div#{id_attribute}#{class_attribute}>#{title_element} <pre class="content">#{node.content}</pre>#{attribution_element} </div>) end def video node xml = node.document.attr? 'htmlsyntax', 'xml' id_attribute = node.id ? %( id="#{node.id}") : nil classes = ['videoblock', node.style, node.role].compact class_attribute = %( class="#{classes * ' '}") title_element = node.title? ? %(\n<div class="title">#{node.captioned_title}</div>) : nil width_attribute = (node.attr? 'width') ? %( width="#{node.attr 'width'}") : nil height_attribute = (node.attr? 'height') ? %( height="#{node.attr 'height'}") : nil case node.attr 'poster' when 'vimeo' start_anchor = (node.attr? 'start', nil, false) ? %(#at=#{node.attr 'start'}) : nil delimiter = '?' autoplay_param = (node.option? 'autoplay') ? %(#{delimiter}autoplay=1) : nil delimiter = '&amp;' if autoplay_param loop_param = (node.option? 'loop') ? %(#{delimiter}loop=1) : nil %(<div#{id_attribute}#{class_attribute}>#{title_element} <div class="content"> <iframe#{width_attribute}#{height_attribute} src="//player.vimeo.com/video/#{node.attr 'target'}#{start_anchor}#{autoplay_param}#{loop_param}" frameborder="0"#{(node.option? 'nofullscreen') ? nil : (append_boolean_attribute 'allowfullscreen', xml)}></iframe> </div> </div>) when 'youtube' rel_param_val = (node.option? 'related') ? 1 : 0 start_param = (node.attr? 'start', nil, false) ? %(&amp;start=#{node.attr 'start'}) : nil end_param = (node.attr? 'end', nil, false) ? %(&amp;end=#{node.attr 'end'}) : nil autoplay_param = (node.option? 'autoplay') ? '&amp;autoplay=1' : nil loop_param = (node.option? 'loop') ? '&amp;loop=1' : nil controls_param = (node.option? 'nocontrols') ? '&amp;controls=0' : nil # cover both ways of controlling fullscreen option if node.option? 'nofullscreen' fs_param = '&amp;fs=0' fs_attribute = nil else fs_param = nil fs_attribute = append_boolean_attribute 'allowfullscreen', xml end modest_param = (node.option? 'modest') ? '&amp;modestbranding=1' : nil theme_param = (node.attr? 'theme', nil, false) ? %(&amp;theme=#{node.attr 'theme'}) : nil hl_param = (node.attr? 'lang') ? %(&amp;hl=#{node.attr 'lang'}) : nil # parse video_id/list_id syntax where list_id (i.e., playlist) is optional target, list = (node.attr 'target').split '/', 2 if (list ||= (node.attr 'list', nil, false)) list_param = %(&amp;list=#{list}) else # parse dynamic playlist syntax: video_id1,video_id2,... target, playlist = target.split ',', 2 if (playlist ||= (node.attr 'playlist', nil, false)) # INFO playlist bar doesn't appear in Firefox unless showinfo=1 and modestbranding=1 list_param = %(&amp;playlist=#{playlist}) else list_param = nil end end %(<div#{id_attribute}#{class_attribute}>#{title_element} <div class="content"> <iframe#{width_attribute}#{height_attribute} src="//www.youtube.com/embed/#{target}?rel=#{rel_param_val}#{start_param}#{end_param}#{autoplay_param}#{loop_param}#{controls_param}#{list_param}#{fs_param}#{modest_param}#{theme_param}#{hl_param}" frameborder="0"#{fs_attribute}></iframe> </div> </div>) else poster_attribute = %(#{poster = node.attr 'poster'}).empty? ? nil : %( poster="#{node.media_uri poster}") start_t = node.attr 'start', nil, false end_t = node.attr 'end', nil, false time_anchor = (start_t || end_t) ? %(#t=#{start_t}#{end_t ? ',' : nil}#{end_t}) : nil %(<div#{id_attribute}#{class_attribute}>#{title_element} <div class="content"> <video src="#{node.media_uri(node.attr 'target')}#{time_anchor}"#{width_attribute}#{height_attribute}#{poster_attribute}#{(node.option? 'autoplay') ? (append_boolean_attribute 'autoplay', xml) : nil}#{(node.option? 'nocontrols') ? nil : (append_boolean_attribute 'controls', xml)}#{(node.option? 'loop') ? (append_boolean_attribute 'loop', xml) : nil}> Your browser does not support the video tag. </video> </div> </div>) end end def inline_anchor node target = node.target case node.type when :xref refid = (node.attr 'refid') || target # NOTE we lookup text in converter because DocBook doesn't need this logic text = node.text || (node.document.references[:ids][refid] || %([#{refid}])) # FIXME shouldn't target be refid? logic seems confused here %(<a href="#{target}">#{text}</a>) when :ref %(<a id="#{target}"></a>) when :link attrs = [] attrs << %( id="#{node.id}") if node.id if (role = node.role) attrs << %( class="#{role}") end attrs << %( title="#{node.attr 'title'}") if node.attr? 'title' attrs << %( target="#{node.attr 'window'}") if node.attr? 'window' %(<a href="#{target}"#{attrs.join}>#{node.text}</a>) when :bibref %(<a id="#{target}"></a>[#{target}]) else warn %(asciidoctor: WARNING: unknown anchor type: #{node.type.inspect}) end end def inline_break node %(#{node.text}<br#{@void_element_slash}>) end def inline_button node %(<b class="button">#{node.text}</b>) end def inline_callout node if node.document.attr? 'icons', 'font' %(<i class="conum" data-value="#{node.text}"></i><b>(#{node.text})</b>) elsif node.document.attr? 'icons' src = node.icon_uri("callouts/#{node.text}") %(<img src="#{src}" alt="#{node.text}"#{@void_element_slash}>) else %(<b class="conum">(#{node.text})</b>) end end def inline_footnote node if (index = node.attr 'index') if node.type == :xref %(<span class="footnoteref">[<a class="footnote" href="#_footnote_#{index}" title="View footnote.">#{index}</a>]</span>) else id_attr = node.id ? %( id="_footnote_#{node.id}") : nil %(<span class="footnote"#{id_attr}>[<a id="_footnoteref_#{index}" class="footnote" href="#_footnote_#{index}" title="View footnote.">#{index}</a>]</span>) end elsif node.type == :xref %(<span class="footnoteref red" title="Unresolved footnote reference.">[#{node.text}]</span>) end end def inline_image node if (type = node.type) == 'icon' && (node.document.attr? 'icons', 'font') style_class = %(fa fa-#{node.target}) if node.attr? 'size' style_class = %(#{style_class} fa-#{node.attr 'size'}) end if node.attr? 'rotate' style_class = %(#{style_class} fa-rotate-#{node.attr 'rotate'}) end if node.attr? 'flip' style_class = %(#{style_class} fa-flip-#{node.attr 'flip'}) end title_attribute = (node.attr? 'title') ? %( title="#{node.attr 'title'}") : nil img = %(<i class="#{style_class}"#{title_attribute}></i>) elsif type == 'icon' && !(node.document.attr? 'icons') img = %([#{node.attr 'alt'}]) else resolved_target = (type == 'icon') ? (node.icon_uri node.target) : (node.image_uri node.target) attrs = ['alt', 'width', 'height', 'title'].map {|name| (node.attr? name) ? %( #{name}="#{node.attr name}") : nil }.join img = %(<img src="#{resolved_target}"#{attrs}#{@void_element_slash}>) end if node.attr? 'link' window_attr = (node.attr? 'window') ? %( target="#{node.attr 'window'}") : nil img = %(<a class="image" href="#{node.attr 'link'}"#{window_attr}>#{img}</a>) end style_classes = (role = node.role) ? %(#{type} #{role}) : type style_attr = (node.attr? 'float') ? %( style="float: #{node.attr 'float'}") : nil %(<span class="#{style_classes}"#{style_attr}>#{img}</span>) end def inline_indexterm node node.type == :visible ? node.text : '' end def inline_kbd node if (keys = node.attr 'keys').size == 1 %(<kbd>#{keys[0]}</kbd>) else key_combo = keys.map {|key| %(<kbd>#{key}</kbd>+) }.join.chop %(<span class="keyseq">#{key_combo}</span>) end end def inline_menu node menu = node.attr 'menu' if !(submenus = node.attr 'submenus').empty? submenu_path = submenus.map {|submenu| %(<span class="submenu">#{submenu}</span>&#160;&#9656; ) }.join.chop %(<span class="menuseq"><span class="menu">#{menu}</span>&#160;&#9656; #{submenu_path} <span class="menuitem">#{node.attr 'menuitem'}</span></span>) elsif (menuitem = node.attr 'menuitem') %(<span class="menuseq"><span class="menu">#{menu}</span>&#160;&#9656; <span class="menuitem">#{menuitem}</span></span>) else %(<span class="menu">#{menu}</span>) end end def inline_quoted node open, close, is_tag = QUOTE_TAGS[node.type] if (role = node.role) if is_tag quoted_text = %(#{open.chop} class="#{role}">#{node.text}#{close}) else quoted_text = %(<span class="#{role}">#{open}#{node.text}#{close}</span>) end else quoted_text = %(#{open}#{node.text}#{close}) end node.id ? %(<a id="#{node.id}"></a>#{quoted_text}) : quoted_text end def append_boolean_attribute name, xml xml ? %( #{name}="#{name}") : %( #{name}) end end end
module Githubber class Issues include HTTParty base_uri "https://api.github.com" def initialize(auth_token) @auth = { "Authorization" => "token #{auth_token}", "User-Agent" => "HTTParty" } end #implement 4 methods below =) # add a new issue def add_issue(owner, repo, title) options = { title: title } self.class.post("/repos/#{owner}/#{repo}/issues", :headers => @auth, :body => options.to_json) end # add a comment to an issue def add_comment(owner, repo, number, comment) options = { body: comment } self.class.post("/repos/#{owner}/#{repo}/issues/#{number}/comments", :headers => @auth, :body => options.to_json) end # list issues for a repo def list_issues self.class.get("/issues", :headers => @auth) end # close an issue def close_issue(owner, repo, number) self.class.patch("/repos/#{owner}/#{repo}/issues/#{number}", :headers => @auth, :body => { "state": "closed" }.to_json) end end end add a blank line module Githubber class Issues include HTTParty base_uri "https://api.github.com" def initialize(auth_token) @auth = { "Authorization" => "token #{auth_token}", "User-Agent" => "HTTParty" } end #implement 4 methods below =) # add a new issue def add_issue(owner, repo, title) options = { title: title } self.class.post("/repos/#{owner}/#{repo}/issues", :headers => @auth, :body => options.to_json) end # add a comment to an issue def add_comment(owner, repo, number, comment) options = { body: comment } self.class.post("/repos/#{owner}/#{repo}/issues/#{number}/comments", :headers => @auth, :body => options.to_json) end # list issues for a repo def list_issues self.class.get("/issues", :headers => @auth) end # close an issue def close_issue(owner, repo, number) self.class.patch("/repos/#{owner}/#{repo}/issues/#{number}", :headers => @auth, :body => { "state": "closed" }.to_json) end end end
require 'ox' require 'json' module Bibliothecary module Parsers class Nuget include Bibliothecary::Analyser extend Bibliothecary::MultiParsers::JSONRuntime def self.mapping { match_filename("Project.json") => { kind: 'manifest', parser: :parse_json_runtime_manifest }, match_filename("Project.lock.json") => { kind: 'lockfile', parser: :parse_project_lock_json }, match_filename("packages.lock.json") => { kind: 'lockfile', parser: :parse_packages_lock_json }, match_filename("packages.config") => { kind: 'manifest', parser: :parse_packages_config }, match_extension(".nuspec") => { kind: 'manifest', parser: :parse_nuspec }, match_extension(".csproj") => { kind: 'manifest', parser: :parse_csproj }, match_filename("paket.lock") => { kind: 'lockfile', parser: :parse_paket_lock }, match_filename("project.assets.json") => { kind: 'lockfile', parser: :parse_project_assets_json } } end add_multi_parser(Bibliothecary::MultiParsers::CycloneDX) add_multi_parser(Bibliothecary::MultiParsers::DependenciesCSV) def self.parse_project_lock_json(file_contents, options: {}) manifest = JSON.parse file_contents manifest.fetch('libraries',[]).map do |name, _requirement| dep = name.split('/') { name: dep[0], requirement: dep[1], type: 'runtime' } end end def self.parse_packages_lock_json(file_contents, options: {}) manifest = JSON.parse file_contents frameworks = {} manifest.fetch('dependencies',[]).each do |framework, deps| frameworks[framework] = deps.map do |name, details| { name: name, # 'resolved' has been set in all examples so far # so fallback to requested is pure paranoia requirement: details.fetch('resolved', details.fetch('requested', '*')), type: 'runtime' } end end if frameworks.size > 0 # we should really return multiple manifests, but bibliothecary doesn't # do that yet so at least pick deterministically. # Note, frameworks can be empty, so remove empty ones and then return the last sorted item if any frameworks = frameworks.delete_if { |_k, v| v.empty? } return frameworks[frameworks.keys.sort.last] unless frameworks.empty? end [] end def self.parse_packages_config(file_contents, options: {}) manifest = Ox.parse file_contents manifest.packages.locate('package').map do |dependency| { name: dependency.id, requirement: (dependency.version if dependency.respond_to? "version") || "*", type: dependency.respond_to?("developmentDependency") && dependency.developmentDependency == "true" ? 'development' : 'runtime' } end rescue [] end def self.parse_csproj(file_contents, options: {}) manifest = Ox.parse file_contents packages = manifest.locate('ItemGroup/PackageReference').select{ |dep| dep.respond_to? "Include" }.map do |dependency| .map do |dependency| requirement = (dependency.Version if dependency.respond_to? "Version") || "*" if requirement.is_a?(Ox::Element) requirement = dependency.nodes.detect{ |n| n.value == "Version" }&.text end type = if dependency.nodes.first && dependency.nodes.first.nodes.include?("all") && dependency.nodes.first.value.include?("PrivateAssets") || dependency.attributes[:PrivateAssets] == "All" "development" else "runtime" end { name: dependency.Include, requirement: requirement, type: type } end packages.uniq {|package| package[:name] } rescue [] end def self.parse_nuspec(file_contents, options: {}) manifest = Ox.parse file_contents manifest.package.metadata.dependencies.locate('dependency').map do |dependency| { name: dependency.id, requirement: dependency.attributes[:version] || '*', type: dependency.respond_to?("developmentDependency") && dependency.developmentDependency == "true" ? 'development' : 'runtime' } end rescue [] end def self.parse_paket_lock(file_contents, options: {}) lines = file_contents.split("\n") package_version_re = /\s+(?<name>\S+)\s\((?<version>\d+\.\d+[\.\d+[\.\d+]*]*)\)/ packages = lines.select { |line| package_version_re.match(line) }.map { |line| package_version_re.match(line) }.map do |match| { name: match[:name].strip, requirement: match[:version], type: 'runtime' } end # we only have to enforce uniqueness by name because paket ensures that there is only the single version globally in the project packages.uniq {|package| package[:name] } end def self.parse_project_assets_json(file_contents, options: {}) manifest = JSON.parse file_contents frameworks = {} manifest.fetch("targets",[]).each do |framework, deps| frameworks[framework] = deps .select { |_name, details| details["type"] == "package" } .map do |name, _details| name_split = name.split("/") { name: name_split[0], requirement: name_split[1], type: "runtime" } end end if frameworks.size > 0 # we should really return multiple manifests, but bibliothecary doesn't # do that yet so at least pick deterministically. # Note, frameworks can be empty, so remove empty ones and then return the last sorted item if any frameworks = frameworks.delete_if { |_k, v| v.empty? } return frameworks[frameworks.keys.sort.last] unless frameworks.empty? end [] end end end end Remove extra line added during merge conflict fix (#552) require 'ox' require 'json' module Bibliothecary module Parsers class Nuget include Bibliothecary::Analyser extend Bibliothecary::MultiParsers::JSONRuntime def self.mapping { match_filename("Project.json") => { kind: 'manifest', parser: :parse_json_runtime_manifest }, match_filename("Project.lock.json") => { kind: 'lockfile', parser: :parse_project_lock_json }, match_filename("packages.lock.json") => { kind: 'lockfile', parser: :parse_packages_lock_json }, match_filename("packages.config") => { kind: 'manifest', parser: :parse_packages_config }, match_extension(".nuspec") => { kind: 'manifest', parser: :parse_nuspec }, match_extension(".csproj") => { kind: 'manifest', parser: :parse_csproj }, match_filename("paket.lock") => { kind: 'lockfile', parser: :parse_paket_lock }, match_filename("project.assets.json") => { kind: 'lockfile', parser: :parse_project_assets_json } } end add_multi_parser(Bibliothecary::MultiParsers::CycloneDX) add_multi_parser(Bibliothecary::MultiParsers::DependenciesCSV) def self.parse_project_lock_json(file_contents, options: {}) manifest = JSON.parse file_contents manifest.fetch('libraries',[]).map do |name, _requirement| dep = name.split('/') { name: dep[0], requirement: dep[1], type: 'runtime' } end end def self.parse_packages_lock_json(file_contents, options: {}) manifest = JSON.parse file_contents frameworks = {} manifest.fetch('dependencies',[]).each do |framework, deps| frameworks[framework] = deps.map do |name, details| { name: name, # 'resolved' has been set in all examples so far # so fallback to requested is pure paranoia requirement: details.fetch('resolved', details.fetch('requested', '*')), type: 'runtime' } end end if frameworks.size > 0 # we should really return multiple manifests, but bibliothecary doesn't # do that yet so at least pick deterministically. # Note, frameworks can be empty, so remove empty ones and then return the last sorted item if any frameworks = frameworks.delete_if { |_k, v| v.empty? } return frameworks[frameworks.keys.sort.last] unless frameworks.empty? end [] end def self.parse_packages_config(file_contents, options: {}) manifest = Ox.parse file_contents manifest.packages.locate('package').map do |dependency| { name: dependency.id, requirement: (dependency.version if dependency.respond_to? "version") || "*", type: dependency.respond_to?("developmentDependency") && dependency.developmentDependency == "true" ? 'development' : 'runtime' } end rescue [] end def self.parse_csproj(file_contents, options: {}) manifest = Ox.parse file_contents packages = manifest.locate('ItemGroup/PackageReference').select{ |dep| dep.respond_to? "Include" }.map do |dependency| requirement = (dependency.Version if dependency.respond_to? "Version") || "*" if requirement.is_a?(Ox::Element) requirement = dependency.nodes.detect{ |n| n.value == "Version" }&.text end type = if dependency.nodes.first && dependency.nodes.first.nodes.include?("all") && dependency.nodes.first.value.include?("PrivateAssets") || dependency.attributes[:PrivateAssets] == "All" "development" else "runtime" end { name: dependency.Include, requirement: requirement, type: type } end packages.uniq {|package| package[:name] } rescue [] end def self.parse_nuspec(file_contents, options: {}) manifest = Ox.parse file_contents manifest.package.metadata.dependencies.locate('dependency').map do |dependency| { name: dependency.id, requirement: dependency.attributes[:version] || '*', type: dependency.respond_to?("developmentDependency") && dependency.developmentDependency == "true" ? 'development' : 'runtime' } end rescue [] end def self.parse_paket_lock(file_contents, options: {}) lines = file_contents.split("\n") package_version_re = /\s+(?<name>\S+)\s\((?<version>\d+\.\d+[\.\d+[\.\d+]*]*)\)/ packages = lines.select { |line| package_version_re.match(line) }.map { |line| package_version_re.match(line) }.map do |match| { name: match[:name].strip, requirement: match[:version], type: 'runtime' } end # we only have to enforce uniqueness by name because paket ensures that there is only the single version globally in the project packages.uniq {|package| package[:name] } end def self.parse_project_assets_json(file_contents, options: {}) manifest = JSON.parse file_contents frameworks = {} manifest.fetch("targets",[]).each do |framework, deps| frameworks[framework] = deps .select { |_name, details| details["type"] == "package" } .map do |name, _details| name_split = name.split("/") { name: name_split[0], requirement: name_split[1], type: "runtime" } end end if frameworks.size > 0 # we should really return multiple manifests, but bibliothecary doesn't # do that yet so at least pick deterministically. # Note, frameworks can be empty, so remove empty ones and then return the last sorted item if any frameworks = frameworks.delete_if { |_k, v| v.empty? } return frameworks[frameworks.keys.sort.last] unless frameworks.empty? end [] end end end end
module Gitlab module Blacklist extend self def path %w(admin dashboard groups help profile projects search public assets u s teams merge_requests issues users snippets services repository hooks) end end end Add 'notes' to path blacklist, fixes #4967 module Gitlab module Blacklist extend self def path %w(admin dashboard groups help profile projects search public assets u s teams merge_requests issues users snippets services repository hooks notes) end end end
require 'gitlab/oauth/user' # LDAP extension for User model # # * Find or create user from omniauth.auth data # * Links LDAP account with existing user # * Auth LDAP user with login and password # module Gitlab module LDAP class User < Gitlab::OAuth::User class << self def find_or_create(auth) @auth = auth if uid.blank? || email.blank? || username.blank? raise_error("Account must provide a dn, uid and email address") end user = find(auth) unless user # Look for user with same emails # # Possible cases: # * When user already has account and need to link their LDAP account. # * LDAP uid changed for user with same email and we need to update their uid # user = model.find_by(email: email) if user user.update_attributes(extern_uid: uid, provider: provider) log.info("(LDAP) Updating legacy LDAP user #{email} with extern_uid => #{uid}") else # Create a new user inside GitLab database # based on LDAP credentials # # user = create(auth) end end user end def authenticate(login, password) # Check user against LDAP backend if user is not authenticated # Only check with valid login and password to prevent anonymous bind results return nil unless ldap_conf.enabled && login.present? && password.present? ldap = OmniAuth::LDAP::Adaptor.new(ldap_conf) filter = Net::LDAP::Filter.eq(ldap.uid, login) # Apply LDAP user filter if present if ldap_conf['user_filter'].present? user_filter = Net::LDAP::Filter.construct(ldap_conf['user_filter']) filter = Net::LDAP::Filter.join(filter, user_filter) end ldap_user = ldap.bind_as( filter: filter, size: 1, password: password ) find_by_uid(ldap_user.dn) if ldap_user end private def find_by_uid_and_provider find_by_uid(uid) end def find_by_uid(uid) # LDAP distinguished name is case-insensitive model.where("provider = ? and lower(extern_uid) = ?", provider, uid.downcase).last end def username auth.info.nickname.to_s.force_encoding("utf-8") end def provider 'ldap' end def raise_error(message) raise OmniAuth::Error, "(LDAP) " + message end def ldap_conf Gitlab.config.ldap end end end end end Remove duplicate method require 'gitlab/oauth/user' # LDAP extension for User model # # * Find or create user from omniauth.auth data # * Links LDAP account with existing user # * Auth LDAP user with login and password # module Gitlab module LDAP class User < Gitlab::OAuth::User class << self def find_or_create(auth) @auth = auth if uid.blank? || email.blank? || username.blank? raise_error("Account must provide a dn, uid and email address") end user = find(auth) unless user # Look for user with same emails # # Possible cases: # * When user already has account and need to link their LDAP account. # * LDAP uid changed for user with same email and we need to update their uid # user = model.find_by(email: email) if user user.update_attributes(extern_uid: uid, provider: provider) log.info("(LDAP) Updating legacy LDAP user #{email} with extern_uid => #{uid}") else # Create a new user inside GitLab database # based on LDAP credentials # # user = create(auth) end end user end def authenticate(login, password) # Check user against LDAP backend if user is not authenticated # Only check with valid login and password to prevent anonymous bind results return nil unless ldap_conf.enabled && login.present? && password.present? ldap = OmniAuth::LDAP::Adaptor.new(ldap_conf) filter = Net::LDAP::Filter.eq(ldap.uid, login) # Apply LDAP user filter if present if ldap_conf['user_filter'].present? user_filter = Net::LDAP::Filter.construct(ldap_conf['user_filter']) filter = Net::LDAP::Filter.join(filter, user_filter) end ldap_user = ldap.bind_as( filter: filter, size: 1, password: password ) find_by_uid(ldap_user.dn) if ldap_user end private def find_by_uid_and_provider find_by_uid(uid) end def find_by_uid(uid) # LDAP distinguished name is case-insensitive model.where("provider = ? and lower(extern_uid) = ?", provider, uid.downcase).last end def provider 'ldap' end def raise_error(message) raise OmniAuth::Error, "(LDAP) " + message end def ldap_conf Gitlab.config.ldap end end end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = 'hyperion_http' spec.version = '0.2.0' spec.authors = ['Indigo BioAutomation, Inc.'] spec.email = ['pwinton@indigobio.com'] spec.summary = 'Ruby REST client' spec.description = 'Ruby REST client for internal service architecture' spec.homepage = '' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 1.7' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'yard' spec.add_development_dependency 'rspec', '~> 3.0' spec.add_development_dependency 'json_spec' spec.add_development_dependency 'rspec_junit_formatter' spec.add_runtime_dependency 'abstractivator', '~> 0.0' spec.add_runtime_dependency 'activesupport' spec.add_runtime_dependency 'immutable_struct', '~> 1.1' spec.add_runtime_dependency 'oj', '~> 2.12' spec.add_runtime_dependency 'typhoeus', '~> 0.7' spec.add_runtime_dependency 'rack' spec.add_runtime_dependency 'logatron' end Update version to 0.2.1 # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = 'hyperion_http' spec.version = '0.2.1' spec.authors = ['Indigo BioAutomation, Inc.'] spec.email = ['pwinton@indigobio.com'] spec.summary = 'Ruby REST client' spec.description = 'Ruby REST client for internal service architecture' spec.homepage = '' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 1.7' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'yard' spec.add_development_dependency 'rspec', '~> 3.0' spec.add_development_dependency 'json_spec' spec.add_development_dependency 'rspec_junit_formatter' spec.add_runtime_dependency 'abstractivator', '~> 0.0' spec.add_runtime_dependency 'activesupport' spec.add_runtime_dependency 'immutable_struct', '~> 1.1' spec.add_runtime_dependency 'oj', '~> 2.12' spec.add_runtime_dependency 'typhoeus', '~> 0.7' spec.add_runtime_dependency 'rack' spec.add_runtime_dependency 'logatron' end
module Gitlab class LfsToken attr_accessor :actor TOKEN_LENGTH = 50 EXPIRY_TIME = 1800 def initialize(actor) @actor = case actor when DeployKey, User actor when Key actor.user else raise 'Bad Actor' end end def token Gitlab::Redis.with do |redis| token = redis.get(redis_key) if token redis.expire(redis_key, EXPIRY_TIME) else token = Devise.friendly_token(TOKEN_LENGTH) redis.set(redis_key, token, ex: EXPIRY_TIME) end token end end def user? actor.is_a?(User) end def type actor.is_a?(User) ? :lfs_token : :lfs_deploy_token end def actor_name actor.is_a?(User) ? actor.username : "lfs+deploy-key-#{actor.id}" end private def redis_key "gitlab:lfs_token:#{actor.class.name.underscore}_#{actor.id}" if actor end end end Fix race condition that can be triggered if the token expires right after we retrieve it, but before we can set the new expiry time. module Gitlab class LfsToken attr_accessor :actor TOKEN_LENGTH = 50 EXPIRY_TIME = 1800 def initialize(actor) @actor = case actor when DeployKey, User actor when Key actor.user else raise 'Bad Actor' end end def token Gitlab::Redis.with do |redis| token = redis.get(redis_key) token ||= Devise.friendly_token(TOKEN_LENGTH) redis.set(redis_key, token, ex: EXPIRY_TIME) token end end def user? actor.is_a?(User) end def type actor.is_a?(User) ? :lfs_token : :lfs_deploy_token end def actor_name actor.is_a?(User) ? actor.username : "lfs+deploy-key-#{actor.id}" end private def redis_key "gitlab:lfs_token:#{actor.class.name.underscore}_#{actor.id}" if actor end end end
module Gmindapp module Helpers # methods from application_controller def gma_comment?(s) s[0]==35 end def get_ip request.env['HTTP_X_FORWARDED_FOR'] || request.env['REMOTE_ADDR'] end def get_default_role default_role= Gmindapp::Role.where(:code =>'default').first return default_role ? default_role.name.to_s : '' end def name2code(s) # rather not ignore # symbol cause it could be comment code, name = s.split(':') code.downcase.strip.gsub(' ','_').gsub(/[^#_\/a-zA-Z0-9]/,'') end def name2camel(s) s.gsub(' ','_').camelcase end def true_action?(s) %w(call ws redirect invoke email).include? s end def set_global $xmain= @xmain ; $runseq = @runseq ; $user = current_user ; $xvars= @xmain.xvars end def authorize? # use in pending tasks @runseq= @xmain.runseqs.find @xmain.current_runseq return false unless @runseq @user = current_user set_global return false unless eval(@runseq.rule) if @runseq.rule return true if true_action?(@runseq.action) # return false if check_wait return true if @runseq.role.blank? if @runseq.role return false unless @user.role return @user.role.upcase.split(',').include?(@runseq.role.upcase) end end def authorize_init? # use when initialize new transaction xml= @service.xml step1 = REXML::Document.new(xml).root.elements['node'] role= get_option_xml("role", step1) || "" # rule= get_option_xml("rule", step1) || true return true if role=="" user= current_user unless user return role.blank? else return false unless user.role return user.role.upcase.split(',').include?(role.upcase) end end def gma_log(message) Gmindapp::Notice.create :message => message, :unread=> true end # methods from application_helper def ajax?(s) return s.match('file_field') ? false : true end def step(s, total) # square text s = (s==0)? 1: s.to_i total = total.to_i out ="<div class='step'>" (s-1).times {|ss| out += "<span class='steps_done'>#{(ss+1)}</span>" } out += %Q@<span class='step_now' >@ out += s.to_s out += "</span>" out += %Q@@ for i in s+1..total out += "<span class='steps_more'>#{i}</span>" end out += "</div>" end # old methods, don't know where they came from def current_user if session[:user_id] return @user ||= User.find(session[:user_id]) else return nil end end def ui_action?(s) %w(form output mail pdf).include? s end def handle_gma_notice if Gmindapp::Notice.recent.count>0 notice= Gmindapp::Notice.recent.last notice.update_attribute :unread, false "<script>notice('#{notice.message}');</script>" else "" end end def process_services # todo: persist mm_md5 xml= @app||get_app if defined? session md5= Digest::MD5.hexdigest(xml.to_s) if session[:mm_md5] return if session[:mm_md5]==md5 else session[:mm_md5]= md5 end end protected_services = [] protected_modules = [] mseq= 0 @services= xml.elements["//node[@TEXT='services']"] || REXML::Document.new @services.each_element('node') do |m| ss= m.attributes["TEXT"] code, name= ss.split(':', 2) next if code.blank? next if code.comment? module_code= code.to_code # create or update to GmaModule gma_module= Gmindapp::Module.find_or_create_by :code=>module_code gma_module.update_attributes :uid=>gma_module.id.to_s protected_modules << gma_module.uid name = module_code if name.blank? gma_module.update_attributes :name=> name.strip, :seq=> mseq mseq += 1 seq= 0 m.each_element('node') do |s| service_name= s.attributes["TEXT"].to_s scode, sname= service_name.split(':', 2) sname ||= scode; sname.strip! scode= scode.to_code if scode=="role" gma_module.update_attribute :role, sname next end if scode.downcase=="link" role= get_option_xml("role", s) || "" rule= get_option_xml("rule", s) || "" gma_service= Gmindapp::Service.find_or_create_by :module_code=> gma_module.code, :code=> scode, :name=> sname gma_service.update_attributes :xml=>s.to_s, :name=>sname, :list=>listed(s), :secured=>secured?(s), :module_id=>gma_module.id, :seq => seq, :confirm=> get_option_xml("confirm", xml), :role => role, :rule => rule, :uid=> gma_service.id.to_s seq += 1 protected_services << gma_service.uid else # normal service step1 = s.elements['node'] role= get_option_xml("role", step1) || "" rule= get_option_xml("rule", step1) || "" gma_service= Gmindapp::Service.find_or_create_by :module_code=> gma_module.code, :code=> scode gma_service.update_attributes :xml=>s.to_s, :name=>sname, :list=>listed(s), :secured=>secured?(s), :module_id=>gma_module.id, :seq => seq, :confirm=> get_option_xml("confirm", xml), :role => role, :rule => rule, :uid=> gma_service.id.to_s seq += 1 protected_services << gma_service.uid end end end Gmindapp::Module.not_in(:uid=>protected_modules).delete_all Gmindapp::Service.not_in(:uid=>protected_services).delete_all end def get_app dir= "#{Rails.root}/app/gmindapp" f= "#{dir}/index.mm" t= REXML::Document.new(File.read(f).gsub("\n","")).root recheck= true ; first_pass= true while recheck recheck= false t.elements.each("//node") do |n| if n.attributes['LINK'] # has attached file if first_pass f= "#{dir}/#{n.attributes['LINK']}" else f= n.attributes['LINK'] end next unless File.exists?(f) tt= REXML::Document.new(File.read(f).gsub("\n","")).root.elements["node"] make_folders_absolute(f,tt) tt.elements.each("node") do |tt_node| n.parent.insert_before n, tt_node end recheck= true n.parent.delete_element n end end first_pass = false end return t end def controller_exists?(modul) File.exists? "#{Rails.root}/app/controllers/#{modul}_controller.rb" end def dup_hash(a) h = Hash.new(0) a.each do |aa| h[aa] += 1 end return h end def login? session[:user_id] != nil end def own_xmain? if $xvars return current_user.id==$xvars[:user_id] else return true end end def get_option_xml(opt, xml) if xml url='' xml.each_element('node') do |n| text= n.attributes['TEXT'] url= text if text =~/^#{opt}/ end return nil if url.blank? c, h= url.split(':', 2) opt= h ? h.strip : true else return nil end end def listed(node) icons=[] node.each_element("icon") do |nn| icons << nn.attributes["BUILTIN"] end return !icons.include?("closed") end def secured?(node) icons=[] node.each_element("icon") do |nn| icons << nn.attributes["BUILTIN"] end return icons.include?("password") end def freemind2action(s) case s.downcase #when 'bookmark' # Excellent # 'call' when 'bookmark' # Excellent 'do' when 'attach' # Look here 'form' when 'edit' # Refine 'pdf' when 'wizard' # Magic 'ws' when 'help' # Question 'if' when 'forward' # Forward 'redirect' when 'kaddressbook' #Phone 'invoke' # invoke new service along the way when 'pencil' 'output' when 'mail' 'mail' end end def affirm(s) return s =~ /[y|yes|t|true]/i ? true : false end def negate(s) return s =~ /[n|no|f|false]/i ? true : false end module FormBuilder def date_field(method, options = {}) default= self.object.send(method) || Date.today data_options= ({"mode"=>"calbox"}).merge(options) %Q(<input name='#{self.object_name}[#{method}]' id='#{self.object_name}_#{method}' value='#{default.strftime("%F")}' type='date' data-role='datebox' data-options='#{data_options.to_json}'>).html_safe end end end end class String def comment? self[0]==35 # check if first char is # end def to_code s= self.dup # s.downcase! # s.gsub! /[\s\-_]/, "" # s code, name = s.split(':') code.downcase.strip.gsub(' ','_').gsub(/[^#_\/a-zA-Z0-9]/,'') end end FormBuilder for ActionView::Helpers module Gmindapp module Helpers # methods from application_controller def gma_comment?(s) s[0]==35 end def get_ip request.env['HTTP_X_FORWARDED_FOR'] || request.env['REMOTE_ADDR'] end def get_default_role default_role= Gmindapp::Role.where(:code =>'default').first return default_role ? default_role.name.to_s : '' end def name2code(s) # rather not ignore # symbol cause it could be comment code, name = s.split(':') code.downcase.strip.gsub(' ','_').gsub(/[^#_\/a-zA-Z0-9]/,'') end def name2camel(s) s.gsub(' ','_').camelcase end def true_action?(s) %w(call ws redirect invoke email).include? s end def set_global $xmain= @xmain ; $runseq = @runseq ; $user = current_user ; $xvars= @xmain.xvars end def authorize? # use in pending tasks @runseq= @xmain.runseqs.find @xmain.current_runseq return false unless @runseq @user = current_user set_global return false unless eval(@runseq.rule) if @runseq.rule return true if true_action?(@runseq.action) # return false if check_wait return true if @runseq.role.blank? if @runseq.role return false unless @user.role return @user.role.upcase.split(',').include?(@runseq.role.upcase) end end def authorize_init? # use when initialize new transaction xml= @service.xml step1 = REXML::Document.new(xml).root.elements['node'] role= get_option_xml("role", step1) || "" # rule= get_option_xml("rule", step1) || true return true if role=="" user= current_user unless user return role.blank? else return false unless user.role return user.role.upcase.split(',').include?(role.upcase) end end def gma_log(message) Gmindapp::Notice.create :message => message, :unread=> true end # methods from application_helper def ajax?(s) return s.match('file_field') ? false : true end def step(s, total) # square text s = (s==0)? 1: s.to_i total = total.to_i out ="<div class='step'>" (s-1).times {|ss| out += "<span class='steps_done'>#{(ss+1)}</span>" } out += %Q@<span class='step_now' >@ out += s.to_s out += "</span>" out += %Q@@ for i in s+1..total out += "<span class='steps_more'>#{i}</span>" end out += "</div>" out.html_safe end # old methods, don't know where they came from def current_user if session[:user_id] return @user ||= User.find(session[:user_id]) else return nil end end def ui_action?(s) %w(form output mail pdf).include? s end def handle_gma_notice if Gmindapp::Notice.recent.count>0 notice= Gmindapp::Notice.recent.last notice.update_attribute :unread, false "<script>notice('#{notice.message}');</script>" else "" end end def process_services # todo: persist mm_md5 xml= @app||get_app if defined? session md5= Digest::MD5.hexdigest(xml.to_s) if session[:mm_md5] return if session[:mm_md5]==md5 else session[:mm_md5]= md5 end end protected_services = [] protected_modules = [] mseq= 0 @services= xml.elements["//node[@TEXT='services']"] || REXML::Document.new @services.each_element('node') do |m| ss= m.attributes["TEXT"] code, name= ss.split(':', 2) next if code.blank? next if code.comment? module_code= code.to_code # create or update to GmaModule gma_module= Gmindapp::Module.find_or_create_by :code=>module_code gma_module.update_attributes :uid=>gma_module.id.to_s protected_modules << gma_module.uid name = module_code if name.blank? gma_module.update_attributes :name=> name.strip, :seq=> mseq mseq += 1 seq= 0 m.each_element('node') do |s| service_name= s.attributes["TEXT"].to_s scode, sname= service_name.split(':', 2) sname ||= scode; sname.strip! scode= scode.to_code if scode=="role" gma_module.update_attribute :role, sname next end if scode.downcase=="link" role= get_option_xml("role", s) || "" rule= get_option_xml("rule", s) || "" gma_service= Gmindapp::Service.find_or_create_by :module_code=> gma_module.code, :code=> scode, :name=> sname gma_service.update_attributes :xml=>s.to_s, :name=>sname, :list=>listed(s), :secured=>secured?(s), :module_id=>gma_module.id, :seq => seq, :confirm=> get_option_xml("confirm", xml), :role => role, :rule => rule, :uid=> gma_service.id.to_s seq += 1 protected_services << gma_service.uid else # normal service step1 = s.elements['node'] role= get_option_xml("role", step1) || "" rule= get_option_xml("rule", step1) || "" gma_service= Gmindapp::Service.find_or_create_by :module_code=> gma_module.code, :code=> scode gma_service.update_attributes :xml=>s.to_s, :name=>sname, :list=>listed(s), :secured=>secured?(s), :module_id=>gma_module.id, :seq => seq, :confirm=> get_option_xml("confirm", xml), :role => role, :rule => rule, :uid=> gma_service.id.to_s seq += 1 protected_services << gma_service.uid end end end Gmindapp::Module.not_in(:uid=>protected_modules).delete_all Gmindapp::Service.not_in(:uid=>protected_services).delete_all end def get_app dir= "#{Rails.root}/app/gmindapp" f= "#{dir}/index.mm" t= REXML::Document.new(File.read(f).gsub("\n","")).root recheck= true ; first_pass= true while recheck recheck= false t.elements.each("//node") do |n| if n.attributes['LINK'] # has attached file if first_pass f= "#{dir}/#{n.attributes['LINK']}" else f= n.attributes['LINK'] end next unless File.exists?(f) tt= REXML::Document.new(File.read(f).gsub("\n","")).root.elements["node"] make_folders_absolute(f,tt) tt.elements.each("node") do |tt_node| n.parent.insert_before n, tt_node end recheck= true n.parent.delete_element n end end first_pass = false end return t end def controller_exists?(modul) File.exists? "#{Rails.root}/app/controllers/#{modul}_controller.rb" end def dup_hash(a) h = Hash.new(0) a.each do |aa| h[aa] += 1 end return h end def login? session[:user_id] != nil end def own_xmain? if $xvars return current_user.id==$xvars[:user_id] else return true end end def get_option_xml(opt, xml) if xml url='' xml.each_element('node') do |n| text= n.attributes['TEXT'] url= text if text =~/^#{opt}/ end return nil if url.blank? c, h= url.split(':', 2) opt= h ? h.strip : true else return nil end end def listed(node) icons=[] node.each_element("icon") do |nn| icons << nn.attributes["BUILTIN"] end return !icons.include?("closed") end def secured?(node) icons=[] node.each_element("icon") do |nn| icons << nn.attributes["BUILTIN"] end return icons.include?("password") end def freemind2action(s) case s.downcase #when 'bookmark' # Excellent # 'call' when 'bookmark' # Excellent 'do' when 'attach' # Look here 'form' when 'edit' # Refine 'pdf' when 'wizard' # Magic 'ws' when 'help' # Question 'if' when 'forward' # Forward 'redirect' when 'kaddressbook' #Phone 'invoke' # invoke new service along the way when 'pencil' 'output' when 'mail' 'mail' end end def affirm(s) return s =~ /[y|yes|t|true]/i ? true : false end def negate(s) return s =~ /[n|no|f|false]/i ? true : false end module FormBuilder def date_field(method, options = {}) default= self.object.send(method) || Date.today data_options= ({"mode"=>"calbox"}).merge(options) %Q(<input name='#{self.object_name}[#{method}]' id='#{self.object_name}_#{method}' value='#{default.strftime("%F")}' type='date' data-role='datebox' data-options='#{data_options.to_json}'>).html_safe end end end end class String def comment? self[0]==35 # check if first char is # end def to_code s= self.dup # s.downcase! # s.gsub! /[\s\-_]/, "" # s code, name = s.split(':') code.downcase.strip.gsub(' ','_').gsub(/[^#_\/a-zA-Z0-9]/,'') end end module ActionView module Helpers class FormBuilder # def date_select_thai(method) # self.date_select method, :use_month_names=>THAI_MONTHS, :order=>[:day, :month, :year] # end def date_field(method, options = {}) default= self.object.send(method) || Date.today data_options= ({"mode"=>"calbox"}).merge(options) out= %Q(<input name='#{self.object_name}[#{method}]' id='#{self.object_name}_#{method}' value='#{default.strftime("%F")}' type='date' data-role='datebox' data-options='#{data_options.to_json}'>) out.html_safe end def time_field(method, options = {}) default= self.object.send(method) || Time.now data_options= ({"mode"=>"timebox"}).merge(options) out=%Q(<input name='#{self.object_name}[#{method}]' id='#{self.object_name}_#{method}' value='#{default}' type='date' data-role='datebox' data-options='#{data_options.to_json}'>) out.html_safe end def date_select_thai(method, default= Time.now, disabled=false) date_select method, :default => default, :use_month_names=>THAI_MONTHS, :order=>[:day, :month, :year], :disabled=>disabled end def datetime_select_thai(method, default= Time.now, disabled=false) datetime_select method, :default => default, :use_month_names=>THAI_MONTHS, :order=>[:day, :month, :year], :disabled=>disabled end def point(o={}) o[:zoom]= 11 unless o[:zoom] o[:width]= '500px' unless o[:width] o[:height]= '300px' unless o[:height] if o[:lat].blank? o[:lat] = 37.5 o[:lng] = -95 o[:zoom] = 4 end out = <<-EOT <script type='text/javascript'> //<![CDATA[ var latLng; var map_#{self.object_name}; var marker_#{self.object_name}; function initialize() { var lat = #{o[:lat]}; var lng = #{o[:lng]}; //var lat = position.coords.latitude"; // HTML5 pass position in function initialize(position) // google.loader.ClientLocation.latitude; //var lng = position.coords.longitude; // google.loader.ClientLocation.longitude; latLng = new google.maps.LatLng(lat, lng); map_#{self.object_name} = new google.maps.Map(document.getElementById("map_#{self.object_name}"), { zoom: #{o[:zoom]}, center: latLng, mapTypeId: google.maps.MapTypeId.ROADMAP }); marker_#{self.object_name} = new google.maps.Marker({ position: latLng, map: map_#{self.object_name}, draggable: true, }); google.maps.event.addListener(marker_#{self.object_name}, 'dragend', function(event) { $('##{self.object_name}_lat').val(event.latLng.lat()); $('##{self.object_name}_lng').val(event.latLng.lng()); }); google.maps.event.addListener(map_#{self.object_name}, 'click', function(event) { $('##{self.object_name}_lat').val(event.latLng.lat()); $('##{self.object_name}_lng').val(event.latLng.lng()); move(); }); $('##{self.object_name}_lat').val(lat); $('##{self.object_name}_lng').val(lng); }; function move() { latLng = new google.maps.LatLng($('##{self.object_name}_lat').val(), $('##{self.object_name}_lng').val()); map_#{self.object_name}.panTo(latLng); marker_#{self.object_name}.setPosition(latLng); } google.maps.event.addDomListener(window, 'load', initialize); //if (navigator.geolocation) { // navigator.geolocation.getCurrentPosition(initialize); //} else { // google.maps.event.addDomListener(window, 'load', no_geo); //} //]]> </script> Latitude: #{self.text_field :lat, :style=>"width:100px;" } Longitude: #{self.text_field :lng, :style=>"width:100px;" } <p/> <div id='map_#{self.object_name}' style='width:#{o[:width]}; height:#{o[:height]};'></div> <script> $('##{self.object_name}_lat').change(function() {move()}) $('##{self.object_name}_lng').change(function() {move()}) var w= $("input[id*=lat]").parent().width(); $("input[id*=lat]").css('width',w/4.5+'px') $("input[id*=lng]").css('width',w/4.5+'px') </script> EOT out.html_safe end end end end
module Bitfinex module V1::HistoricalDataClient # View all of your balance ledger entries. # # @param currency [string] (optional) Specify the currency, default "USD" # @param params :since [time] (optional) Return only the history after this timestamp. # @param params :until [time] (optional) Return only the history before this timestamp. # @param params :limit [int] (optional) Limit the number of entries to return. Default is 500. # @param params :wallet [string] (optional) Return only entries that took place in this wallet. Accepted inputs are: “trading”, “exchange”, “deposit” # @return [Array] # @example: # client.history def history(currency="usd", params = {}) check_params(params, %i{since until limit wallet}) params.merge!({currency: currency}) authenticated_post("history", params: params).body end # View your past deposits/withdrawals. # # @param currency [string] (optional) Specify the currency, default "USD" # @param params :method (optional) The method of the deposit/withdrawal (can be “bitcoin”, “litecoin”, “darkcoin”, “wire”) # @param params :since (optional) Return only the history after this timestamp # @param params :until [time] (optional) Return only the history before this timestamp. # @param params :limit [int] (optional) Limit the number of entries to return. Default is 500. # @return [Array] # @example: # client.movements def movements(currency="usd", params = {}) check_params(params, %i{method since until limit}) params.merge!({currency: currency}) authenticated_post("history/movements", params: params).body end # View your past trades. # # @param symbol The pair traded (BTCUSD, LTCUSD, LTCBTC) # @param params :until [time] (optional) Return only the history before this timestamp. # @param params :timestamp [time] (optional) Trades made before this timestamp won’t be returned # @param params :until [time] (optional) Trades made after this timestamp won’t be returned # @param params :limit_trades [int] Limit the number of trades returned. Default is 50. # @param params :reverse [int] Return trades in reverse order (the oldest comes first). Default is returning newest trades first. # @return [Array] # @example: # client.mytrades def mytrades(symbol, params = {}) check_params(params, %i{until limit_trades reverse timestamp}) params.merge!({symbol: symbol}) authenticated_post("mytrades", params: params).body end end end add since_movement and until_movement to query module Bitfinex module V1::HistoricalDataClient # View all of your balance ledger entries. # # @param currency [string] (optional) Specify the currency, default "USD" # @param params :since [time] (optional) Return only the history after this timestamp. # @param params :until [time] (optional) Return only the history before this timestamp. # @param params :limit [int] (optional) Limit the number of entries to return. Default is 500. # @param params :wallet [string] (optional) Return only entries that took place in this wallet. Accepted inputs are: “trading”, “exchange”, “deposit” # @return [Array] # @example: # client.history def history(currency="usd", params = {}) check_params(params, %i{since until limit wallet}) params.merge!({currency: currency}) authenticated_post("history", params: params).body end # View your past deposits/withdrawals. # # @param currency [string] (optional) Specify the currency, default "USD" # @param params :method (optional) The method of the deposit/withdrawal (can be “bitcoin”, “litecoin”, “darkcoin”, “wire”) # @param params :since (optional) Return only the history after this timestamp # @param params :until [time] (optional) Return only the history before this timestamp. # @param params :limit [int] (optional) Limit the number of entries to return. Default is 500. # @return [Array] # @example: # client.movements def movements(currency="usd", params = {}) check_params(params, %i{method since until limit since_movement until_movement}) params.merge!({currency: currency}) authenticated_post("history/movements", params: params).body end # View your past trades. # # @param symbol The pair traded (BTCUSD, LTCUSD, LTCBTC) # @param params :until [time] (optional) Return only the history before this timestamp. # @param params :timestamp [time] (optional) Trades made before this timestamp won’t be returned # @param params :until [time] (optional) Trades made after this timestamp won’t be returned # @param params :limit_trades [int] Limit the number of trades returned. Default is 50. # @param params :reverse [int] Return trades in reverse order (the oldest comes first). Default is returning newest trades first. # @return [Array] # @example: # client.mytrades def mytrades(symbol, params = {}) check_params(params, %i{until limit_trades reverse timestamp}) params.merge!({symbol: symbol}) authenticated_post("mytrades", params: params).body end end end
require 'gorillib/string/simple_inflector' require 'gorillib/model' require 'gorillib/model/field' require 'gorillib/model/defaults' module Gorillib module Builder extend Gorillib::Concern include Gorillib::Model def initialize(attrs={}, &block) receive!(attrs, &block) end def receive!(*args, &block) super(*args) if block_given? (block.arity == 1) ? block.call(self) : self.instance_eval(&block) end self end def getset(field, *args, &block) ArgumentError.check_arity!(args, 0..1) if args.empty? val = read_attribute(field.name) else val = write_attribute(field.name, args.first) end val end def getset_member(field, *args, &block) ArgumentError.check_arity!(args, 0..1) attrs = args.first if attrs.is_a?(field.type) # actual object: assign it into field val = attrs write_attribute(field.name, val) else val = read_attribute(field.name) if val.present? val.receive!(*args, &block) if args.present? elsif attrs.blank? # missing item (read): return nil return nil else # missing item (write): construct item and add to collection val = field.type.receive(*args, &block) write_attribute(field.name, val) end end val end def getset_collection_item(field, item_key, attrs={}, &block) clxn = collection_of(field.plural_name) if attrs.is_a?(field.type) # actual object: assign it into collection val = attrs clxn[item_key] = val elsif clxn.include?(item_key) # existing item: retrieve it, updating as directed val = clxn[item_key] val.receive!(attrs, &block) else # missing item: autovivify item and add to collection val = field.type.receive({ key_method => item_key, :owner => self }.merge(attrs), &block) clxn[item_key] = val end val end def key_method :name end def collection_of(plural_name) self.read_attribute(plural_name) end module ClassMethods include Gorillib::Model::ClassMethods def field(field_name, type, options={}) super(field_name, type, {:field_type => ::Gorillib::Builder::GetsetField}.merge(options)) end def member(field_name, type, options={}) field(field_name, type, {:field_type => ::Gorillib::Builder::MemberField}.merge(options)) end def collection(field_name, type, options={}) field(field_name, type, {:field_type => ::Gorillib::Builder::CollectionField}.merge(options)) end protected def define_attribute_getset(field) define_meta_module_method(field.name, field.visibility(:reader)) do |*args, &block| getset(field, *args, &block) end end def define_member_getset(field) define_meta_module_method(field.name, field.visibility(:reader)) do |*args, &block| getset_member(field, *args, &block) end end def define_collection_getset(field) define_meta_module_method(field.singular_name, field.visibility(:collection_getset)) do |*args, &block| getset_collection_item(field, *args, &block) end end def define_collection_tester(field) plural_name = field.plural_name define_meta_module_method("has_#{field.singular_name}?", field.visibility(:collection_tester)) do |item_key| collection_of(plural_name).include?(item_key) end end end end module FancyBuilder extend Gorillib::Concern include Gorillib::Builder def inspect(detailed=true) str = super detailed ? str : ([str[0..-2], " #{read_attribute(key_method)}>"].join) end included do |base| base.field :name, Symbol end module ClassMethods include Gorillib::Builder::ClassMethods def belongs_to(field_name, type, options={}) field = field(field_name, type, {:field_type => ::Gorillib::Builder::MemberField }.merge(options)) define_meta_module_method "#{field.name}_name" do val = getset_member(field) or return nil val.name end field end def collects(type, clxn_name) type_handle = type.handle define_meta_module_method type_handle do |item_name, attrs={}, options={}, &block| send(clxn_name, item_name, attrs, options.merge(:factory => type), &block) end end end end module Builder class GetsetField < Gorillib::Model::Field self.visibilities = visibilities.merge(:writer => false, :tester => false, :getset => true) def inscribe_methods(model) model.__send__(:define_attribute_getset, self) model.__send__(:define_attribute_writer, self) model.__send__(:define_attribute_tester, self) model.__send__(:define_attribute_receiver, self) end end class MemberField < Gorillib::Model::Field self.visibilities = visibilities.merge(:writer => false, :tester => true) def inscribe_methods(model) model.__send__(:define_member_getset, self) model.__send__(:define_attribute_writer, self) model.__send__(:define_attribute_tester, self) model.__send__(:define_attribute_receiver, self) end end class CollectionField < Gorillib::Model::Field field :singular_name, Symbol, :default => ->{ Gorillib::Inflector.singularize(name.to_s).to_sym } self.visibilities = visibilities.merge(:writer => false, :tester => false, :collection_getset => :public, :collection_tester => true) alias_method :plural_name, :name def singular_name @singular_name ||= Gorillib::Inflector.singularize(name.to_s).to_sym end def collection_key :name end def inscribe_methods(model) type = self.type collection_key = self.collection_key self.default = ->{ Gorillib::Collection.new(type, collection_key) } raise "Plural and singular names must differ: #{self.plural_name}" if (singular_name == plural_name) # @visibilities[:writer] = false super model.__send__(:define_collection_getset, self) model.__send__(:define_collection_tester, self) end end end end added simple field method to builder require 'gorillib/string/simple_inflector' require 'gorillib/model' require 'gorillib/model/field' require 'gorillib/model/defaults' module Gorillib module Builder extend Gorillib::Concern include Gorillib::Model def initialize(attrs={}, &block) receive!(attrs, &block) end def receive!(*args, &block) super(*args) if block_given? (block.arity == 1) ? block.call(self) : self.instance_eval(&block) end self end def getset(field, *args, &block) ArgumentError.check_arity!(args, 0..1) if args.empty? val = read_attribute(field.name) else val = write_attribute(field.name, args.first) end val end def getset_member(field, *args, &block) ArgumentError.check_arity!(args, 0..1) attrs = args.first if attrs.is_a?(field.type) # actual object: assign it into field val = attrs write_attribute(field.name, val) else val = read_attribute(field.name) if val.present? val.receive!(*args, &block) if args.present? elsif attrs.blank? # missing item (read): return nil return nil else # missing item (write): construct item and add to collection val = field.type.receive(*args, &block) write_attribute(field.name, val) end end val end def getset_collection_item(field, item_key, attrs={}, &block) clxn = collection_of(field.plural_name) if attrs.is_a?(field.type) # actual object: assign it into collection val = attrs clxn[item_key] = val elsif clxn.include?(item_key) # existing item: retrieve it, updating as directed val = clxn[item_key] val.receive!(attrs, &block) else # missing item: autovivify item and add to collection val = field.type.receive({ key_method => item_key, :owner => self }.merge(attrs), &block) clxn[item_key] = val end val end def key_method :name end def collection_of(plural_name) self.read_attribute(plural_name) end module ClassMethods include Gorillib::Model::ClassMethods def field(field_name, type, options={}) super(field_name, type, {:field_type => ::Gorillib::Builder::GetsetField}.merge(options)) end def member(field_name, type, options={}) field(field_name, type, {:field_type => ::Gorillib::Builder::MemberField}.merge(options)) end def collection(field_name, type, options={}) field(field_name, type, {:field_type => ::Gorillib::Builder::CollectionField}.merge(options)) end def simple_field(field_name, type, options={}) field(field_name, type, {:field_type => ::Gorillib::Model::Field}.merge(options)) end protected def define_attribute_getset(field) define_meta_module_method(field.name, field.visibility(:reader)) do |*args, &block| getset(field, *args, &block) end end def define_member_getset(field) define_meta_module_method(field.name, field.visibility(:reader)) do |*args, &block| getset_member(field, *args, &block) end end def define_collection_getset(field) define_meta_module_method(field.singular_name, field.visibility(:collection_getset)) do |*args, &block| getset_collection_item(field, *args, &block) end end def define_collection_tester(field) plural_name = field.plural_name define_meta_module_method("has_#{field.singular_name}?", field.visibility(:collection_tester)) do |item_key| collection_of(plural_name).include?(item_key) end end end end module FancyBuilder extend Gorillib::Concern include Gorillib::Builder def inspect(detailed=true) str = super detailed ? str : ([str[0..-2], " #{read_attribute(key_method)}>"].join) end included do |base| base.field :name, Symbol end module ClassMethods include Gorillib::Builder::ClassMethods def belongs_to(field_name, type, options={}) field = field(field_name, type, {:field_type => ::Gorillib::Builder::MemberField }.merge(options)) define_meta_module_method "#{field.name}_name" do val = getset_member(field) or return nil val.name end field end def collects(type, clxn_name) type_handle = type.handle define_meta_module_method type_handle do |item_name, attrs={}, options={}, &block| send(clxn_name, item_name, attrs, options.merge(:factory => type), &block) end end end end module Builder class GetsetField < Gorillib::Model::Field self.visibilities = visibilities.merge(:writer => false, :tester => false, :getset => true) def inscribe_methods(model) model.__send__(:define_attribute_getset, self) model.__send__(:define_attribute_writer, self) model.__send__(:define_attribute_tester, self) model.__send__(:define_attribute_receiver, self) end end class MemberField < Gorillib::Model::Field self.visibilities = visibilities.merge(:writer => false, :tester => true) def inscribe_methods(model) model.__send__(:define_member_getset, self) model.__send__(:define_attribute_writer, self) model.__send__(:define_attribute_tester, self) model.__send__(:define_attribute_receiver, self) end end class CollectionField < Gorillib::Model::Field field :singular_name, Symbol, :default => ->{ Gorillib::Inflector.singularize(name.to_s).to_sym } self.visibilities = visibilities.merge(:writer => false, :tester => false, :collection_getset => :public, :collection_tester => true) alias_method :plural_name, :name def singular_name @singular_name ||= Gorillib::Inflector.singularize(name.to_s).to_sym end def collection_key :name end def inscribe_methods(model) type = self.type collection_key = self.collection_key self.default = ->{ Gorillib::Collection.new(type, collection_key) } raise "Plural and singular names must differ: #{self.plural_name}" if (singular_name == plural_name) # @visibilities[:writer] = false super model.__send__(:define_collection_getset, self) model.__send__(:define_collection_tester, self) end end end end
module Haystack VERSION = '0.11.17' end Incrementa versão module Haystack VERSION = '0.11.18' end
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # BuildrPlus::FeatureManager.feature(:config) do |f| f.enhance(:Config) do attr_writer :application_config_location def application_config_location base_directory = File.dirname(Buildr.application.buildfile.to_s) "#{base_directory}/config/application.yml" end def application_config_example_location application_config_location.gsub(/\.yml$/, '.example.yml') end def application_config @application_config ||= load_application_config end attr_writer :environment def environment @environment || 'development' end def environment_config raise "Attempting to configuration for #{self.environment} environment which is not present." unless self.application_config.environment_by_key?(self.environment) self.application_config.environment_by_key(self.environment) end def domain_environment_var(domain, key, default_value = nil) domain_name = Redfish::Naming.uppercase_constantize(domain.name) scope = self.app_scope code = self.env_code return ENV["#{domain_name}_#{scope}_#{key}_#{code}"] if scope && ENV["#{domain_name}_#{scope}_#{key}_#{code}"] return ENV["#{domain_name}_#{key}_#{code}"] if ENV["#{domain_name}_#{key}_#{code}"] return ENV["#{scope}_#{key}_#{code}"] if scope && ENV["#{scope}_#{key}_#{code}"] ENV["#{scope}_#{key}_#{code}"] || ENV["#{key}_#{code}"] || ENV[key] || default_value end def environment_var(key, default_value = nil) scope = self.app_scope code = self.env_code return ENV["#{scope}_#{key}_#{code}"] if scope && ENV["#{scope}_#{key}_#{code}"] ENV["#{key}_#{code}"] || ENV[key] || default_value end def user ENV['USER'] end def app_scope ENV['APP_SCOPE'] || ENV['JOB_NAME'] end def env_code(environment = self.environment) if environment == 'development' 'DEV' elsif environment == 'test' 'TEST' elsif environment == 'uat' 'UAT' elsif environment == 'training' 'TRN' elsif environment == 'ci' 'CI' elsif environment == 'production' 'PRD' else environment end end def load_application_config! @application_config = load_application_config unless @application_config end def reload_application_config! @application_config = nil load_application_config! end def get_buildr_project if ::Buildr.application.current_scope.size > 0 ::Buildr.project(::Buildr.application.current_scope.join(':')) rescue nil else Buildr.projects[0] end end private def load_application_config if !File.exist?(self.application_config_location) && File.exist?(self.application_config_example_location) FileUtils.cp self.application_config_example_location, self.application_config_location end data = File.exist?(self.application_config_location) ? YAML::load(ERB.new(IO.read(self.application_config_location)).result) : {} config = BuildrPlus::Config::ApplicationConfig.new(data) populate_configuration(config) if BuildrPlus::FeatureManager.activated?(:dbt) ::Dbt.repository.configuration_data = config.to_database_yml ::SSRS::Config.config_data = config.to_database_yml if BuildrPlus::FeatureManager.activated?(:rptman) # Also need to write file out for processes that pick up database.yml (like packaged # database definitions run via java -jar) FileUtils.mkdir_p File.dirname(::Dbt::Config.config_filename) File.open(::Dbt::Config.config_filename, 'wb') do |file| file.write "# DO NOT EDIT: File is auto-generated\n" file.write config.to_database_yml(:jruby => true).to_yaml end end buildr_project = get_buildr_project.root_project if BuildrPlus::FeatureManager.activated?(:rails) && BuildrPlus::FeatureManager.activated?(:redfish) && Redfish.domain_by_key?(buildr_project.name) domain = Redfish.domain_by_key(buildr_project.name) buildr_project.task(':domgen:all' => ['rails:config:generate']) if BuildrPlus::FeatureManager.activated?(:domgen) buildr_project.task(':rails:config:generate' => ["#{domain.task_prefix}:setup_env_vars"]) do # Also need to populate rails configuration properties = BuildrPlus::Redfish.build_property_set(domain, BuildrPlus::Config.environment_config) base_directory = File.dirname(Buildr.application.buildfile.to_s) FileUtils.mkdir_p "#{base_directory}/config" File.open("#{base_directory}/config/config.properties", 'wb') do |file| file.write "# DO NOT EDIT: File is auto-generated\n" data = '' domain.data['custom_resources'].each_pair do |key, resource_config| value = resource_config['properties']['value'] data += "#{key.gsub('/', '.')}=#{value}\n" end properties.each_pair do |key, value| data.gsub!("${#{key}}", value) end data = Redfish::Interpreter::Interpolater.interpolate(domain.to_task_context, :data => data)[:data] file.write data end end end config end def populate_configuration(config) %w(development test).each do |environment_key| config.environment(environment_key) unless config.environment_by_key?(environment_key) populate_environment_configuration(config.environment_by_key(environment_key), false) end copy_development_settings(config.environment_by_key('development'), config.environment_by_key('test')) config.environments.each do |environment| unless %w(development test).include?(environment.key.to_s) populate_environment_configuration(environment, true) end end end def copy_development_settings(from, to) from.settings.each_pair do |key, value| to.setting(key, value) unless to.setting?(key) end end def populate_environment_configuration(environment, check_only = false) populate_database_configuration(environment, check_only) populate_broker_configuration(environment, check_only) populate_ssrs_configuration(environment, check_only) populate_volume_configuration(environment) unless check_only end def populate_volume_configuration(environment) buildr_project = get_buildr_project.root_project if BuildrPlus::FeatureManager.activated?(:redfish) && Redfish.domain_by_key?(buildr_project.name) domain = Redfish.domain_by_key(buildr_project.name) domain.volume_requirements.keys.each do |key| environment.set_volume(key, "volumes/#{key}") unless environment.volume?(key) end end base_directory = File.dirname(::Buildr.application.buildfile.to_s) environment.volumes.each_pair do |key, local_path| environment.set_volume(key, File.expand_path(local_path, base_directory)) end end def populate_database_configuration(environment, check_only) if !BuildrPlus::FeatureManager.activated?(:dbt) && !environment.databases.empty? raise "Databases defined in application configuration but BuildrPlus facet 'dbt' not enabled" elsif BuildrPlus::FeatureManager.activated?(:dbt) # Ensure all databases are registered in dbt environment.databases.each do |database| unless ::Dbt.database_for_key?(database.key) raise "Database '#{database.key}' defined in application configuration but has not been defined as a dbt database" end end # Create database configurations if in Dbt but configuration does not already exist ::Dbt.repository.database_keys.each do |database_key| environment.database(database_key) unless environment.database_by_key?(database_key) end unless check_only scope = self.app_scope buildr_project = get_buildr_project environment.databases.each do |database| dbt_database = ::Dbt.database_for_key(database.key) dbt_imports = !dbt_database.imports.empty? || (dbt_database.packaged? && dbt_database.extra_actions.any? { |a| a.to_s =~ /import/ }) short_name = BuildrPlus::Naming.uppercase_constantize(database.key.to_s == 'default' ? buildr_project.root_project.name : database.key.to_s) database.database = "#{user || 'NOBODY'}#{scope.nil? ? '' : "_#{scope}"}_#{short_name}_#{self.env_code(environment.key)}" unless database.database database.import_from = "PROD_CLONE_#{short_name}" unless database.import_from || !dbt_imports database.host = environment_var('DB_SERVER_HOST') unless database.host unless database.port_set? port = environment_var('DB_SERVER_PORT', database.port) database.port = port.to_i if port end database.admin_username = environment_var('DB_SERVER_USERNAME') unless database.admin_username database.admin_password = environment_var('DB_SERVER_PASSWORD') unless database.admin_password if database.is_a?(BuildrPlus::Config::MssqlDatabaseConfig) database.delete_backup_history = environment_var('DB_SERVER_DELETE_BACKUP_HISTORY', 'true') unless database.delete_backup_history_set? unless database.instance instance = environment_var('DB_SERVER_INSTANCE', '') database.instance = instance unless instance == '' end end raise "Configuration for database key #{database.key} is missing host attribute and can not be derived from environment variable DB_SERVER_HOST" unless database.host raise "Configuration for database key #{database.key} is missing admin_username attribute and can not be derived from environment variable DB_SERVER_USERNAME" unless database.admin_username raise "Configuration for database key #{database.key} is missing admin_password attribute and can not be derived from environment variable DB_SERVER_PASSWORD" unless database.admin_password raise "Configuration for database key #{database.key} specifies import_from but dbt defines no import for database" if database.import_from && !dbt_imports end end end def populate_ssrs_configuration(environment, check_only) endpoint = BuildrPlus::Config.environment_var('RPTMAN_ENDPOINT') domain = BuildrPlus::Config.environment_var('RPTMAN_DOMAIN') username = BuildrPlus::Config.environment_var('RPTMAN_USERNAME') password = BuildrPlus::Config.environment_var('RPTMAN_PASSWORD') if !BuildrPlus::FeatureManager.activated?(:rptman) && environment.ssrs? raise "Ssrs defined in application configuration but BuildrPlus facet 'rptman' not enabled" elsif BuildrPlus::FeatureManager.activated?(:rptman) && !environment.ssrs? && !check_only environment.ssrs elsif !BuildrPlus::FeatureManager.activated?(:rptman) && !environment.ssrs? return elsif BuildrPlus::FeatureManager.activated?(:rptman) && !environment.ssrs? && check_only return end scope = self.app_scope environment.ssrs.report_target = endpoint if environment.ssrs.report_target.nil? environment.ssrs.domain = domain if environment.ssrs.domain.nil? environment.ssrs.admin_username = username if environment.ssrs.admin_username.nil? environment.ssrs.admin_password = password if environment.ssrs.admin_password.nil? if environment.ssrs.prefix.nil? buildr_project = get_buildr_project short_name = BuildrPlus::Naming.uppercase_constantize(buildr_project.root_project.name) environment.ssrs.prefix = "/Auto/#{user || 'NOBODY'}#{scope.nil? ? '' : "_#{scope}"}/#{self.env_code}/#{short_name}" end raise 'Configuration for ssrs is missing report_target attribute and can not be derived from environment variable RPTMAN_ENDPOINT' unless environment.ssrs.report_target raise 'Configuration for ssrs is missing domain attribute and can not be derived from environment variable RPTMAN_DOMAIN' unless environment.ssrs.domain raise 'Configuration for ssrs is missing admin_username attribute and can not be derived from environment variable RPTMAN_USERNAME' unless environment.ssrs.admin_username raise 'Configuration for ssrs is missing admin_password attribute and can not be derived from environment variable RPTMAN_PASSWORD' unless environment.ssrs.admin_password end def populate_broker_configuration(environment, check_only) if !BuildrPlus::FeatureManager.activated?(:jms) && environment.broker? raise "Broker defined in application configuration but BuildrPlus facet 'jms' not enabled" elsif BuildrPlus::FeatureManager.activated?(:jms) && !environment.broker? && !check_only host = BuildrPlus::Config.environment_var('OPENMQ_HOST', 'localhost') port = BuildrPlus::Config.environment_var('OPENMQ_PORT', '7676') username = BuildrPlus::Config.environment_var('OPENMQ_ADMIN_USERNAME', 'admin') password = BuildrPlus::Config.environment_var('OPENMQ_ADMIN_PASSWORD', 'admin') environment.broker(:host => host, :port => port, :admin_username => username, :admin_password => password) end end end f.enhance(:ProjectExtension) do after_define do |project| if project.ipr? project.task(':domgen:all' => ['config:expand_application_yml']) if BuildrPlus::FeatureManager.activated?(:domgen) desc 'Generate a complete application configuration from context' project.task(':config:expand_application_yml') do filename = project._('generated/buildr_plus/config/application.yml') trace("Expanding application configuration to #{filename}") FileUtils.mkdir_p File.dirname(filename) File.open(filename, 'wb') do |file| file.write "# DO NOT EDIT: File is auto-generated\n" file.write BuildrPlus::Config.application_config.to_h.to_yaml end database_filename = project._('generated/buildr_plus/config/database.yml') trace("Expanding database configuration to #{database_filename}") File.open(database_filename, 'wb') do |file| file.write "# DO NOT EDIT: File is auto-generated\n" file.write BuildrPlus::Config.application_config.to_database_yml.to_yaml end end end end end end Allow import_from if there is a database name filter used during imports # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # BuildrPlus::FeatureManager.feature(:config) do |f| f.enhance(:Config) do attr_writer :application_config_location def application_config_location base_directory = File.dirname(Buildr.application.buildfile.to_s) "#{base_directory}/config/application.yml" end def application_config_example_location application_config_location.gsub(/\.yml$/, '.example.yml') end def application_config @application_config ||= load_application_config end attr_writer :environment def environment @environment || 'development' end def environment_config raise "Attempting to configuration for #{self.environment} environment which is not present." unless self.application_config.environment_by_key?(self.environment) self.application_config.environment_by_key(self.environment) end def domain_environment_var(domain, key, default_value = nil) domain_name = Redfish::Naming.uppercase_constantize(domain.name) scope = self.app_scope code = self.env_code return ENV["#{domain_name}_#{scope}_#{key}_#{code}"] if scope && ENV["#{domain_name}_#{scope}_#{key}_#{code}"] return ENV["#{domain_name}_#{key}_#{code}"] if ENV["#{domain_name}_#{key}_#{code}"] return ENV["#{scope}_#{key}_#{code}"] if scope && ENV["#{scope}_#{key}_#{code}"] ENV["#{scope}_#{key}_#{code}"] || ENV["#{key}_#{code}"] || ENV[key] || default_value end def environment_var(key, default_value = nil) scope = self.app_scope code = self.env_code return ENV["#{scope}_#{key}_#{code}"] if scope && ENV["#{scope}_#{key}_#{code}"] ENV["#{key}_#{code}"] || ENV[key] || default_value end def user ENV['USER'] end def app_scope ENV['APP_SCOPE'] || ENV['JOB_NAME'] end def env_code(environment = self.environment) if environment == 'development' 'DEV' elsif environment == 'test' 'TEST' elsif environment == 'uat' 'UAT' elsif environment == 'training' 'TRN' elsif environment == 'ci' 'CI' elsif environment == 'production' 'PRD' else environment end end def load_application_config! @application_config = load_application_config unless @application_config end def reload_application_config! @application_config = nil load_application_config! end def get_buildr_project if ::Buildr.application.current_scope.size > 0 ::Buildr.project(::Buildr.application.current_scope.join(':')) rescue nil else Buildr.projects[0] end end private def load_application_config if !File.exist?(self.application_config_location) && File.exist?(self.application_config_example_location) FileUtils.cp self.application_config_example_location, self.application_config_location end data = File.exist?(self.application_config_location) ? YAML::load(ERB.new(IO.read(self.application_config_location)).result) : {} config = BuildrPlus::Config::ApplicationConfig.new(data) populate_configuration(config) if BuildrPlus::FeatureManager.activated?(:dbt) ::Dbt.repository.configuration_data = config.to_database_yml ::SSRS::Config.config_data = config.to_database_yml if BuildrPlus::FeatureManager.activated?(:rptman) # Also need to write file out for processes that pick up database.yml (like packaged # database definitions run via java -jar) FileUtils.mkdir_p File.dirname(::Dbt::Config.config_filename) File.open(::Dbt::Config.config_filename, 'wb') do |file| file.write "# DO NOT EDIT: File is auto-generated\n" file.write config.to_database_yml(:jruby => true).to_yaml end end buildr_project = get_buildr_project.root_project if BuildrPlus::FeatureManager.activated?(:rails) && BuildrPlus::FeatureManager.activated?(:redfish) && Redfish.domain_by_key?(buildr_project.name) domain = Redfish.domain_by_key(buildr_project.name) buildr_project.task(':domgen:all' => ['rails:config:generate']) if BuildrPlus::FeatureManager.activated?(:domgen) buildr_project.task(':rails:config:generate' => ["#{domain.task_prefix}:setup_env_vars"]) do # Also need to populate rails configuration properties = BuildrPlus::Redfish.build_property_set(domain, BuildrPlus::Config.environment_config) base_directory = File.dirname(Buildr.application.buildfile.to_s) FileUtils.mkdir_p "#{base_directory}/config" File.open("#{base_directory}/config/config.properties", 'wb') do |file| file.write "# DO NOT EDIT: File is auto-generated\n" data = '' domain.data['custom_resources'].each_pair do |key, resource_config| value = resource_config['properties']['value'] data += "#{key.gsub('/', '.')}=#{value}\n" end properties.each_pair do |key, value| data.gsub!("${#{key}}", value) end data = Redfish::Interpreter::Interpolater.interpolate(domain.to_task_context, :data => data)[:data] file.write data end end end config end def populate_configuration(config) %w(development test).each do |environment_key| config.environment(environment_key) unless config.environment_by_key?(environment_key) populate_environment_configuration(config.environment_by_key(environment_key), false) end copy_development_settings(config.environment_by_key('development'), config.environment_by_key('test')) config.environments.each do |environment| unless %w(development test).include?(environment.key.to_s) populate_environment_configuration(environment, true) end end end def copy_development_settings(from, to) from.settings.each_pair do |key, value| to.setting(key, value) unless to.setting?(key) end end def populate_environment_configuration(environment, check_only = false) populate_database_configuration(environment, check_only) populate_broker_configuration(environment, check_only) populate_ssrs_configuration(environment, check_only) populate_volume_configuration(environment) unless check_only end def populate_volume_configuration(environment) buildr_project = get_buildr_project.root_project if BuildrPlus::FeatureManager.activated?(:redfish) && Redfish.domain_by_key?(buildr_project.name) domain = Redfish.domain_by_key(buildr_project.name) domain.volume_requirements.keys.each do |key| environment.set_volume(key, "volumes/#{key}") unless environment.volume?(key) end end base_directory = File.dirname(::Buildr.application.buildfile.to_s) environment.volumes.each_pair do |key, local_path| environment.set_volume(key, File.expand_path(local_path, base_directory)) end end def populate_database_configuration(environment, check_only) if !BuildrPlus::FeatureManager.activated?(:dbt) && !environment.databases.empty? raise "Databases defined in application configuration but BuildrPlus facet 'dbt' not enabled" elsif BuildrPlus::FeatureManager.activated?(:dbt) # Ensure all databases are registered in dbt environment.databases.each do |database| unless ::Dbt.database_for_key?(database.key) raise "Database '#{database.key}' defined in application configuration but has not been defined as a dbt database" end end # Create database configurations if in Dbt but configuration does not already exist ::Dbt.repository.database_keys.each do |database_key| environment.database(database_key) unless environment.database_by_key?(database_key) end unless check_only scope = self.app_scope buildr_project = get_buildr_project environment.databases.each do |database| dbt_database = ::Dbt.database_for_key(database.key) dbt_imports = !dbt_database.imports.empty? || (dbt_database.packaged? && dbt_database.extra_actions.any? { |a| a.to_s =~ /import/ }) environment.databases.select { |d| d != database }.each do |d| ::Dbt.database_for_key(d.key).filters.each do |f| if f.is_a?(Struct::DatabaseNameFilter) && f.database_key.to_s == database.key.to_s dbt_imports = true end end end unless dbt_imports short_name = BuildrPlus::Naming.uppercase_constantize(database.key.to_s == 'default' ? buildr_project.root_project.name : database.key.to_s) database.database = "#{user || 'NOBODY'}#{scope.nil? ? '' : "_#{scope}"}_#{short_name}_#{self.env_code(environment.key)}" unless database.database database.import_from = "PROD_CLONE_#{short_name}" unless database.import_from || !dbt_imports database.host = environment_var('DB_SERVER_HOST') unless database.host unless database.port_set? port = environment_var('DB_SERVER_PORT', database.port) database.port = port.to_i if port end database.admin_username = environment_var('DB_SERVER_USERNAME') unless database.admin_username database.admin_password = environment_var('DB_SERVER_PASSWORD') unless database.admin_password if database.is_a?(BuildrPlus::Config::MssqlDatabaseConfig) database.delete_backup_history = environment_var('DB_SERVER_DELETE_BACKUP_HISTORY', 'true') unless database.delete_backup_history_set? unless database.instance instance = environment_var('DB_SERVER_INSTANCE', '') database.instance = instance unless instance == '' end end raise "Configuration for database key #{database.key} is missing host attribute and can not be derived from environment variable DB_SERVER_HOST" unless database.host raise "Configuration for database key #{database.key} is missing admin_username attribute and can not be derived from environment variable DB_SERVER_USERNAME" unless database.admin_username raise "Configuration for database key #{database.key} is missing admin_password attribute and can not be derived from environment variable DB_SERVER_PASSWORD" unless database.admin_password raise "Configuration for database key #{database.key} specifies import_from but dbt defines no import for database" if database.import_from && !dbt_imports end end end def populate_ssrs_configuration(environment, check_only) endpoint = BuildrPlus::Config.environment_var('RPTMAN_ENDPOINT') domain = BuildrPlus::Config.environment_var('RPTMAN_DOMAIN') username = BuildrPlus::Config.environment_var('RPTMAN_USERNAME') password = BuildrPlus::Config.environment_var('RPTMAN_PASSWORD') if !BuildrPlus::FeatureManager.activated?(:rptman) && environment.ssrs? raise "Ssrs defined in application configuration but BuildrPlus facet 'rptman' not enabled" elsif BuildrPlus::FeatureManager.activated?(:rptman) && !environment.ssrs? && !check_only environment.ssrs elsif !BuildrPlus::FeatureManager.activated?(:rptman) && !environment.ssrs? return elsif BuildrPlus::FeatureManager.activated?(:rptman) && !environment.ssrs? && check_only return end scope = self.app_scope environment.ssrs.report_target = endpoint if environment.ssrs.report_target.nil? environment.ssrs.domain = domain if environment.ssrs.domain.nil? environment.ssrs.admin_username = username if environment.ssrs.admin_username.nil? environment.ssrs.admin_password = password if environment.ssrs.admin_password.nil? if environment.ssrs.prefix.nil? buildr_project = get_buildr_project short_name = BuildrPlus::Naming.uppercase_constantize(buildr_project.root_project.name) environment.ssrs.prefix = "/Auto/#{user || 'NOBODY'}#{scope.nil? ? '' : "_#{scope}"}/#{self.env_code}/#{short_name}" end raise 'Configuration for ssrs is missing report_target attribute and can not be derived from environment variable RPTMAN_ENDPOINT' unless environment.ssrs.report_target raise 'Configuration for ssrs is missing domain attribute and can not be derived from environment variable RPTMAN_DOMAIN' unless environment.ssrs.domain raise 'Configuration for ssrs is missing admin_username attribute and can not be derived from environment variable RPTMAN_USERNAME' unless environment.ssrs.admin_username raise 'Configuration for ssrs is missing admin_password attribute and can not be derived from environment variable RPTMAN_PASSWORD' unless environment.ssrs.admin_password end def populate_broker_configuration(environment, check_only) if !BuildrPlus::FeatureManager.activated?(:jms) && environment.broker? raise "Broker defined in application configuration but BuildrPlus facet 'jms' not enabled" elsif BuildrPlus::FeatureManager.activated?(:jms) && !environment.broker? && !check_only host = BuildrPlus::Config.environment_var('OPENMQ_HOST', 'localhost') port = BuildrPlus::Config.environment_var('OPENMQ_PORT', '7676') username = BuildrPlus::Config.environment_var('OPENMQ_ADMIN_USERNAME', 'admin') password = BuildrPlus::Config.environment_var('OPENMQ_ADMIN_PASSWORD', 'admin') environment.broker(:host => host, :port => port, :admin_username => username, :admin_password => password) end end end f.enhance(:ProjectExtension) do after_define do |project| if project.ipr? project.task(':domgen:all' => ['config:expand_application_yml']) if BuildrPlus::FeatureManager.activated?(:domgen) desc 'Generate a complete application configuration from context' project.task(':config:expand_application_yml') do filename = project._('generated/buildr_plus/config/application.yml') trace("Expanding application configuration to #{filename}") FileUtils.mkdir_p File.dirname(filename) File.open(filename, 'wb') do |file| file.write "# DO NOT EDIT: File is auto-generated\n" file.write BuildrPlus::Config.application_config.to_h.to_yaml end database_filename = project._('generated/buildr_plus/config/database.yml') trace("Expanding database configuration to #{database_filename}") File.open(database_filename, 'wb') do |file| file.write "# DO NOT EDIT: File is auto-generated\n" file.write BuildrPlus::Config.application_config.to_database_yml.to_yaml end end end end end end
class HBase # Boxed Ruby class for org.apache.hadoop.hbase.KeyValue # @!attribute [r] java # @return [org.apache.hadoop.hbase.KeyValue] class Cell attr_reader :java # Creates a boxed object for a KeyValue object # @param [org.apache.hadoop.hbase.KeyValue] key_value def initialize key_value @java = key_value @ck = nil end # Returns the rowkey of the cell decoded as the given type # @param [Symbol] type The type of the rowkey. # Can be one of :string, :symbol, :fixnum, :float, :short, :int, :bigdecimal, :boolean and :raw. # @return [String, byte[]] def rowkey type = :string Util.from_bytes type, @java.getRow end # Returns the ColumnKey object for the cell # @return [ColumnKey] def column_key @ck ||= ColumnKey.new @java.getFamily, @java.getQualifier end # Returns the name of the column family of the cell # @return [String] def family String.from_java_bytes @java.getFamily end alias cf family # Returns the column qualifier of the cell # @param [Symbol] type The type of the qualifier. # Can be one of :string, :symbol, :fixnum, :float, :short, :int, :bigdecimal, :boolean and :raw. # @return [Object] def qualifier type = :string Util.from_bytes type, @java.getQualifier end alias cq qualifier # Returns the timestamp of the cell # @return [Fixnum] def timestamp @java.getTimestamp end alias ts timestamp # Returns the value of the cell as a Java byte array # @return [byte[]] def value @java.getValue end alias raw value # Returns the column value as a String # @return [String] def string Util.from_bytes :string, value end alias str string # Returns the column value as a Symbol # @return [Symbol] def symbol Util.from_bytes :symbol, value end alias sym symbol # Returns the 8-byte column value as a Fixnum # @return [Fixnum] def fixnum Util.from_bytes :fixnum, value end alias long fixnum # Returns the 4-byte column value as a Fixnum # @return [Fixnum] def int Util.from_bytes :int, value end # Returns the 2-byte column value as a Fixnum # @return [Fixnum] def short Util.from_bytes :short, value end # Returns the 1-byte column value as a Fixnum # @return [Fixnum] def byte Util.from_bytes :byte, value end # Returns the column value as a BigDecimal # @return [BigDecimal] def bigdecimal Util.from_bytes :bigdecimal, value end # Returns the column value as a Float # @return [Float] def float Util.from_bytes :float, value end alias double float # Returns the column value as a boolean value # @return [true, false] def boolean Util.from_bytes :boolean, value end alias bool boolean # Implements column key order # @param [Cell] other # @return [Fixnum] -1, 0, or 1 def <=> other KeyValue.COMPARATOR.compare(@java, other.java) end # Checks if the cells are the same # @param [HBase::Cell] other def eql? other (self <=> other) == 0 end alias == eql? # Returns a printable version of this cell # @return [String] def inspect %[#{cf}:#{cq} = "#{string}"@#{ts}] end end#Cell end#HBase Add HBase::Cell#hash class HBase # Boxed Ruby class for org.apache.hadoop.hbase.KeyValue # @!attribute [r] java # @return [org.apache.hadoop.hbase.KeyValue] class Cell attr_reader :java # Creates a boxed object for a KeyValue object # @param [org.apache.hadoop.hbase.KeyValue] key_value def initialize key_value @java = key_value @ck = nil end # Returns the rowkey of the cell decoded as the given type # @param [Symbol] type The type of the rowkey. # Can be one of :string, :symbol, :fixnum, :float, :short, :int, :bigdecimal, :boolean and :raw. # @return [String, byte[]] def rowkey type = :string Util.from_bytes type, @java.getRow end # Returns the ColumnKey object for the cell # @return [ColumnKey] def column_key @ck ||= ColumnKey.new @java.getFamily, @java.getQualifier end # Returns the name of the column family of the cell # @return [String] def family String.from_java_bytes @java.getFamily end alias cf family # Returns the column qualifier of the cell # @param [Symbol] type The type of the qualifier. # Can be one of :string, :symbol, :fixnum, :float, :short, :int, :bigdecimal, :boolean and :raw. # @return [Object] def qualifier type = :string Util.from_bytes type, @java.getQualifier end alias cq qualifier # Returns the timestamp of the cell # @return [Fixnum] def timestamp @java.getTimestamp end alias ts timestamp # Returns the value of the cell as a Java byte array # @return [byte[]] def value @java.getValue end alias raw value # Returns the column value as a String # @return [String] def string Util.from_bytes :string, value end alias str string # Returns the column value as a Symbol # @return [Symbol] def symbol Util.from_bytes :symbol, value end alias sym symbol # Returns the 8-byte column value as a Fixnum # @return [Fixnum] def fixnum Util.from_bytes :fixnum, value end alias long fixnum # Returns the 4-byte column value as a Fixnum # @return [Fixnum] def int Util.from_bytes :int, value end # Returns the 2-byte column value as a Fixnum # @return [Fixnum] def short Util.from_bytes :short, value end # Returns the 1-byte column value as a Fixnum # @return [Fixnum] def byte Util.from_bytes :byte, value end # Returns the column value as a BigDecimal # @return [BigDecimal] def bigdecimal Util.from_bytes :bigdecimal, value end # Returns the column value as a Float # @return [Float] def float Util.from_bytes :float, value end alias double float # Returns the column value as a boolean value # @return [true, false] def boolean Util.from_bytes :boolean, value end alias bool boolean # Implements column key order # @param [Cell] other # @return [Fixnum] -1, 0, or 1 def <=> other KeyValue.COMPARATOR.compare(@java, other.java) end # Checks if the cells are the same # @param [HBase::Cell] other def eql? other (self <=> other) == 0 end alias == eql? def hash @java.hasCode end # Returns a printable version of this cell # @return [String] def inspect %[#{cf}:#{cq} = "#{string}"@#{ts}] end end#Cell end#HBase
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # BuildrPlus::Roles.role(:container) do if BuildrPlus::FeatureManager.activated?(:domgen) generators = [] generators << [:redfish_fragment] if BuildrPlus::FeatureManager.activated?(:redfish) generators << [:keycloak_client_config] if BuildrPlus::FeatureManager.activated?(:keycloak) generators += project.additional_domgen_generators Domgen::Build.define_generate_task(generators.flatten, :buildr_project => project) do |t| t.filter = project.domgen_filter end unless generators.empty? end project.publish = false BuildrPlus::Roles.projects.each do |p| other = project.project(p.name) unless other.test.compile.sources.empty? || !other.iml? other.idea_testng_configuration_created = true ipr.add_testng_configuration(p.name.to_s, :module => other.iml.name, :jvm_args => BuildrPlus::Testng.default_testng_args(other,p).join(' ')) end end # Need to use definitions as projects have yet to be when resolving # container project which is typically the root project if BuildrPlus::Roles.project_with_role?(:server) server_project = project(BuildrPlus::Roles.project_with_role(:server).name) model_project = BuildrPlus::Roles.project_with_role?(:model) ? project(BuildrPlus::Roles.project_with_role(:model).name) : nil shared_project = BuildrPlus::Roles.project_with_role?(:shared) ? project(BuildrPlus::Roles.project_with_role(:shared).name) : nil dependencies = [server_project, model_project, shared_project].compact # Spotbugs+jetbrains libs added otherwise CDI scanning slows down due to massive number of ClassNotFoundExceptions dependencies << BuildrPlus::Deps.spotbugs_provided dependencies << BuildrPlus::Deps.jetbrains_annotations dependencies << BuildrPlus::Deps.server_compile_deps war_module_names = [server_project.iml.name] jpa_module_names = [] jpa_module_names << model_project.iml.name if model_project ejb_module_names = [server_project.iml.name] ejb_module_names << model_project.iml.name if model_project exploded_war_name = "#{project.iml.id}-exploded" ipr.add_exploded_war_artifact(project, :name => exploded_war_name, :dependencies => dependencies, :war_module_names => war_module_names, :jpa_module_names => jpa_module_names, :ejb_module_names => ejb_module_names) war_name = "#{project.iml.id}-archive" ipr.add_war_artifact(project, :name => war_name, :dependencies => dependencies, :war_module_names => war_module_names, :jpa_module_names => jpa_module_names, :ejb_module_names => ejb_module_names) context_root = BuildrPlus::Glassfish.context_root || project.iml.id if BuildrPlus::Glassfish.support_remote_configuration? ipr.add_glassfish_remote_configuration(project, :server_name => 'GlassFish 5.2020.3', :artifacts => { war_name => context_root }, :packaged => BuildrPlus::Glassfish.remote_only_packaged_apps.dup.merge(BuildrPlus::Glassfish.packaged_apps)) end unless BuildrPlus::Redfish.local_domain_update_only? local_packaged_apps = BuildrPlus::Glassfish.non_remote_only_packaged_apps.dup.merge(BuildrPlus::Glassfish.packaged_apps) local_packaged_apps['greenmail'] = BuildrPlus::Libs.greenmail_server if BuildrPlus::FeatureManager.activated?(:mail) ipr.add_glassfish_configuration(project, :server_name => 'GlassFish 5.2020.3', :exploded => {exploded_war_name => context_root}, :packaged => local_packaged_apps) if BuildrPlus::Glassfish.support_app_only_configuration? only_packaged_apps = BuildrPlus::Glassfish.only_only_packaged_apps.dup ipr.add_glassfish_configuration(project, :configuration_name => "#{Reality::Naming.pascal_case(project.name)} Only - GlassFish 5.2020.3", :server_name => 'GlassFish 5.2020.3', :exploded => {exploded_war_name => context_root}, :packaged => only_packaged_apps) end end if BuildrPlus::FeatureManager.activated?(:db) iml.excluded_directories << project._('dataSources') iml.excluded_directories << project._('.ideaDataSources') end iml.excluded_directories << project._(:target, :generated, :gwt) if BuildrPlus::FeatureManager.activated?(:gwt) iml.excluded_directories << project._('tmp') iml.excluded_directories << project._('.shelf') BuildrPlus::Roles.buildr_projects_with_role(:user_experience).each do |p| gwt_modules = p.determine_top_level_gwt_modules('Dev') gwt_modules.each do |gwt_module| short_name = gwt_module.gsub(/.*\.([^.]+)Dev$/, '\1') path = short_name.gsub(/^#{Reality::Naming.pascal_case(project.name)}/, '') if path.size > 0 server_project = project(BuildrPlus::Roles.project_with_role(:server).name) %w(html jsp).each do |extension| candidate = "#{Reality::Naming.underscore(path)}.#{extension}" path = candidate if File.exist?(server_project._(:source, :main, :webapp_local, candidate)) end end ipr.add_gwt_configuration(p, :gwt_module => gwt_module, :start_javascript_debugger => false, :open_in_browser => false, :vm_parameters => '-Xmx3G', :shell_parameters => "-codeServerPort #{BuildrPlus::Gwt.code_server_port} -bindAddress 0.0.0.0 -deploy #{_(:target, :generated, :gwt, 'deploy')} -extra #{_(:target, :generated, :gwt, 'extra')} -war #{_(:target, :generated, :gwt, 'war')} -style PRETTY -XmethodNameDisplayMode FULL -noincremental -logLevel INFO -strict -nostartServer", :launch_page => "http://127.0.0.1:8080/#{p.root_project.name}/#{path}") end end end end Make sure that non-defualt entrypoints have correctly defined gwt configurations in idea # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # BuildrPlus::Roles.role(:container) do if BuildrPlus::FeatureManager.activated?(:domgen) generators = [] generators << [:redfish_fragment] if BuildrPlus::FeatureManager.activated?(:redfish) generators << [:keycloak_client_config] if BuildrPlus::FeatureManager.activated?(:keycloak) generators += project.additional_domgen_generators Domgen::Build.define_generate_task(generators.flatten, :buildr_project => project) do |t| t.filter = project.domgen_filter end unless generators.empty? end project.publish = false BuildrPlus::Roles.projects.each do |p| other = project.project(p.name) unless other.test.compile.sources.empty? || !other.iml? other.idea_testng_configuration_created = true ipr.add_testng_configuration(p.name.to_s, :module => other.iml.name, :jvm_args => BuildrPlus::Testng.default_testng_args(other,p).join(' ')) end end # Need to use definitions as projects have yet to be when resolving # container project which is typically the root project if BuildrPlus::Roles.project_with_role?(:server) server_project = project(BuildrPlus::Roles.project_with_role(:server).name) model_project = BuildrPlus::Roles.project_with_role?(:model) ? project(BuildrPlus::Roles.project_with_role(:model).name) : nil shared_project = BuildrPlus::Roles.project_with_role?(:shared) ? project(BuildrPlus::Roles.project_with_role(:shared).name) : nil dependencies = [server_project, model_project, shared_project].compact # Spotbugs+jetbrains libs added otherwise CDI scanning slows down due to massive number of ClassNotFoundExceptions dependencies << BuildrPlus::Deps.spotbugs_provided dependencies << BuildrPlus::Deps.jetbrains_annotations dependencies << BuildrPlus::Deps.server_compile_deps war_module_names = [server_project.iml.name] jpa_module_names = [] jpa_module_names << model_project.iml.name if model_project ejb_module_names = [server_project.iml.name] ejb_module_names << model_project.iml.name if model_project exploded_war_name = "#{project.iml.id}-exploded" ipr.add_exploded_war_artifact(project, :name => exploded_war_name, :dependencies => dependencies, :war_module_names => war_module_names, :jpa_module_names => jpa_module_names, :ejb_module_names => ejb_module_names) war_name = "#{project.iml.id}-archive" ipr.add_war_artifact(project, :name => war_name, :dependencies => dependencies, :war_module_names => war_module_names, :jpa_module_names => jpa_module_names, :ejb_module_names => ejb_module_names) context_root = BuildrPlus::Glassfish.context_root || project.iml.id if BuildrPlus::Glassfish.support_remote_configuration? ipr.add_glassfish_remote_configuration(project, :server_name => 'GlassFish 5.2020.3', :artifacts => { war_name => context_root }, :packaged => BuildrPlus::Glassfish.remote_only_packaged_apps.dup.merge(BuildrPlus::Glassfish.packaged_apps)) end unless BuildrPlus::Redfish.local_domain_update_only? local_packaged_apps = BuildrPlus::Glassfish.non_remote_only_packaged_apps.dup.merge(BuildrPlus::Glassfish.packaged_apps) local_packaged_apps['greenmail'] = BuildrPlus::Libs.greenmail_server if BuildrPlus::FeatureManager.activated?(:mail) ipr.add_glassfish_configuration(project, :server_name => 'GlassFish 5.2020.3', :exploded => {exploded_war_name => context_root}, :packaged => local_packaged_apps) if BuildrPlus::Glassfish.support_app_only_configuration? only_packaged_apps = BuildrPlus::Glassfish.only_only_packaged_apps.dup ipr.add_glassfish_configuration(project, :configuration_name => "#{Reality::Naming.pascal_case(project.name)} Only - GlassFish 5.2020.3", :server_name => 'GlassFish 5.2020.3', :exploded => {exploded_war_name => context_root}, :packaged => only_packaged_apps) end end if BuildrPlus::FeatureManager.activated?(:db) iml.excluded_directories << project._('dataSources') iml.excluded_directories << project._('.ideaDataSources') end iml.excluded_directories << project._(:target, :generated, :gwt) if BuildrPlus::FeatureManager.activated?(:gwt) iml.excluded_directories << project._('tmp') iml.excluded_directories << project._('.shelf') BuildrPlus::Roles.buildr_projects_with_role(:user_experience).each do |p| gwt_modules = p.determine_top_level_gwt_modules('Dev') gwt_modules.each do |gwt_module| local_module = gwt_module.gsub(/.*\.([^.]+)$/, '\1') path = local_module.gsub(/^#{Reality::Naming.pascal_case(project.name)}/, '') if 'Dev' == path path = '' else server_project = project(BuildrPlus::Roles.project_with_role(:server).name) %w(html jsp).each do |extension| candidate = "#{Reality::Naming.underscore(local_module)}.#{extension}" path = candidate if File.exist?(server_project._(:source, :main, :webapp_local, candidate)) end end ipr.add_gwt_configuration(p, :gwt_module => gwt_module, :start_javascript_debugger => false, :open_in_browser => false, :vm_parameters => '-Xmx3G', :shell_parameters => "-codeServerPort #{BuildrPlus::Gwt.code_server_port} -bindAddress 0.0.0.0 -deploy #{_(:target, :generated, :gwt, 'deploy')} -extra #{_(:target, :generated, :gwt, 'extra')} -war #{_(:target, :generated, :gwt, 'war')} -style PRETTY -XmethodNameDisplayMode FULL -noincremental -logLevel INFO -strict -nostartServer", :launch_page => "http://127.0.0.1:8080/#{p.root_project.name}/#{path}") end end end end
require 'hedgelog/scrubber' class Hedgelog class Context def initialize(scrubber, data = {}) raise ::ArgumentError, "#{self.class}: argument must be Hash got #{data.class}." unless data.is_a? Hash check_reserved_keys(data) @data = data @scrubber = scrubber end def []=(key, val) raise ::ArgumentError, "#{self.class}: The #{key} is a reserved key and cannot be used." if Hedgelog::RESERVED_KEYS.include? key.to_sym @data[key] = val end def [](key) @data[key] end def delete(key) @data.delete(key) end def clear @data = {} end def merge(hash) @data.merge(hash) end def merge!(hash_or_context) check_reserved_keys(hash_or_context) unless hash_or_context.is_a? Hedgelog::Context @data = hash_or_context.to_h.merge(@data) end def overwrite!(hash_or_context) check_reserved_keys(hash_or_context) unless hash_or_context.is_a? Hedgelog::Context @data.merge!(hash_or_context.to_h) end def scrub! @data = @scrubber.scrub(@data) self end def to_h @data end private def check_reserved_keys(hash) invalid_keys = Hedgelog::RESERVED_KEYS & hash.keys raise ::ArgumentError, "#{self.class}: The following keys are reserved and cannot be used #{invalid_keys.to_a}." if invalid_keys.length > 0 end end end Fix for ruby 1.9 require 'hedgelog/scrubber' class Hedgelog class Context def initialize(scrubber, data = {}) raise ::ArgumentError, "#{self.class}: argument must be Hash got #{data.class}." unless data.is_a? Hash check_reserved_keys(data) @data = data @scrubber = scrubber end def []=(key, val) raise ::ArgumentError, "#{self.class}: The #{key} is a reserved key and cannot be used." if Hedgelog::RESERVED_KEYS.include? key.to_sym @data[key] = val end def [](key) @data[key] end def delete(key) @data.delete(key) end def clear @data = {} end def merge(hash) @data.merge(hash) end def merge!(hash_or_context) check_reserved_keys(hash_or_context) unless hash_or_context.is_a? Hedgelog::Context hash_or_context = hash_or_context.to_h if hash_or_context.respond_to?(:to_h) @data = hash_or_context.merge(@data) end def overwrite!(hash_or_context) check_reserved_keys(hash_or_context) unless hash_or_context.is_a? Hedgelog::Context hash_or_context = hash_or_context.to_h if hash_or_context.respond_to?(:to_h) @data.merge!(hash_or_context) end def scrub! @data = @scrubber.scrub(@data) self end def to_h @data end private def check_reserved_keys(hash) invalid_keys = Hedgelog::RESERVED_KEYS & hash.keys raise ::ArgumentError, "#{self.class}: The following keys are reserved and cannot be used #{invalid_keys.to_a}." if invalid_keys.length > 0 end end end
module Bullet module Registry class Association < Base def merge( base, associations ) @registry.merge!( { base => associations } ) unique( @registry[base] ) end def similarly_associated( base, associations ) @registry.select do |key, value| key.include?( base ) and value == associations end.collect( &:first ).flatten! end end end end removes ! from flatten, was causing this procedure to return nil instead of [] - which caused a nil deref downstream. module Bullet module Registry class Association < Base def merge( base, associations ) @registry.merge!( { base => associations } ) unique( @registry[base] ) end def similarly_associated( base, associations ) @registry.select do |key, value| key.include?( base ) and value == associations end.collect( &:first ).flatten end end end end
require 'heirloom/archive/lister.rb' require 'heirloom/archive/reader.rb' require 'heirloom/archive/builder.rb' require 'heirloom/archive/updater.rb' require 'heirloom/archive/uploader.rb' require 'heirloom/archive/downloader.rb' require 'heirloom/archive/setuper.rb' require 'heirloom/archive/teardowner.rb' require 'heirloom/archive/writer.rb' require 'heirloom/archive/authorizer.rb' require 'heirloom/archive/destroyer.rb' require 'heirloom/archive/verifier.rb' require 'heirloom/archive/checker.rb' module Heirloom class Archive def initialize(args) @config = args[:config] @name = args[:name] @id = args[:id] end def authorize(accounts) authorizer.authorize :accounts => accounts, :regions => regions end def build(args) builder.build args end def count reader.count end def download(args) downloader.download args end def setup(args) setuper.setup args end def delete_buckets(args) teardowner.delete_buckets args end def delete_domain teardowner.delete_domain end def update(args) updater.update args end def upload(args) uploader.upload({ :regions => regions }.merge(args)) end def exists? reader.exists? end def buckets_exist?(args) verifier.buckets_exist? args end def domain_exists? verifier.domain_exists? end def destroy destroyer.destroy :regions => regions end def show reader.show end def list(limit=10) lister.list(limit) end def regions reader.regions end private def lister @lister ||= Lister.new :config => @config, :name => @name end def reader @reader ||= Reader.new :config => @config, :name => @name, :id => @id end def builder @builder ||= Builder.new :config => @config, :name => @name, :id => @id end def updater @updater ||= Updater.new :config => @config, :name => @name, :id => @id end def uploader @uploader ||= Uploader.new :config => @config, :name => @name, :id => @id end def downloader @downloader ||= Downloader.new :config => @config, :name => @name, :id => @id end def authorizer @authorizer ||= Authorizer.new :config => @config, :name => @name, :id => @id end def destroyer @destroyer ||= Destroyer.new :config => @config, :name => @name, :id => @id end def setuper @setuper ||= Setuper.new :config => @config, :name => @name end def teardowner @teardowner ||= Teardowner.new :config => @config, :name => @name end def verifier @verifier ||= Verifier.new :config => @config, :name => @name end end end sorting requires require 'heirloom/archive/authorizer.rb' require 'heirloom/archive/builder.rb' require 'heirloom/archive/checker.rb' require 'heirloom/archive/destroyer.rb' require 'heirloom/archive/downloader.rb' require 'heirloom/archive/lister.rb' require 'heirloom/archive/reader.rb' require 'heirloom/archive/setuper.rb' require 'heirloom/archive/teardowner.rb' require 'heirloom/archive/updater.rb' require 'heirloom/archive/uploader.rb' require 'heirloom/archive/verifier.rb' require 'heirloom/archive/writer.rb' module Heirloom class Archive def initialize(args) @config = args[:config] @name = args[:name] @id = args[:id] end def authorize(accounts) authorizer.authorize :accounts => accounts, :regions => regions end def build(args) builder.build args end def count reader.count end def download(args) downloader.download args end def setup(args) setuper.setup args end def delete_buckets(args) teardowner.delete_buckets args end def delete_domain teardowner.delete_domain end def update(args) updater.update args end def upload(args) uploader.upload({ :regions => regions }.merge(args)) end def exists? reader.exists? end def buckets_exist?(args) verifier.buckets_exist? args end def domain_exists? verifier.domain_exists? end def destroy destroyer.destroy :regions => regions end def show reader.show end def list(limit=10) lister.list(limit) end def regions reader.regions end private def lister @lister ||= Lister.new :config => @config, :name => @name end def reader @reader ||= Reader.new :config => @config, :name => @name, :id => @id end def builder @builder ||= Builder.new :config => @config, :name => @name, :id => @id end def updater @updater ||= Updater.new :config => @config, :name => @name, :id => @id end def uploader @uploader ||= Uploader.new :config => @config, :name => @name, :id => @id end def downloader @downloader ||= Downloader.new :config => @config, :name => @name, :id => @id end def authorizer @authorizer ||= Authorizer.new :config => @config, :name => @name, :id => @id end def destroyer @destroyer ||= Destroyer.new :config => @config, :name => @name, :id => @id end def setuper @setuper ||= Setuper.new :config => @config, :name => @name end def teardowner @teardowner ||= Teardowner.new :config => @config, :name => @name end def verifier @verifier ||= Verifier.new :config => @config, :name => @name end end end
# frozen_string_literal: true module Bundler class Resolver class SpecGroup include GemHelpers attr_accessor :name, :version, :source attr_accessor :ignores_bundler_dependencies def initialize(all_specs) raise ArgumentError, "cannot initialize with an empty value" unless exemplary_spec = all_specs.first @name = exemplary_spec.name @version = exemplary_spec.version @source = exemplary_spec.source @required_by = [] @activated_platforms = [] @dependencies = nil @specs = Hash.new do |specs, platform| specs[platform] = select_best_platform_match(all_specs, platform) end @ignores_bundler_dependencies = true end def to_specs @activated_platforms.map do |p| next unless s = @specs[p] lazy_spec = LazySpecification.new(name, version, s.platform, source) lazy_spec.dependencies.replace s.dependencies lazy_spec end.compact end def activate_platform!(platform) return unless for?(platform) return if @activated_platforms.include?(platform) @activated_platforms << platform end def for?(platform) spec = @specs[platform] !spec.nil? end def to_s @to_s ||= "#{name} (#{version})" end def dependencies_for_activated_platforms dependencies = @activated_platforms.map {|p| __dependencies[p] } metadata_dependencies = @activated_platforms.map do |platform| metadata_dependencies(@specs[platform], platform) end dependencies.concat(metadata_dependencies).flatten end def platforms_for_dependency_named(dependency) __dependencies.select {|_, deps| deps.map(&:name).include? dependency }.keys end def ==(other) return unless other.is_a?(SpecGroup) name == other.name && version == other.version && source == other.source end def eql?(other) name.eql?(other.name) && version.eql?(other.version) && source.eql?(other.source) end def hash to_s.hash ^ source.hash end private def __dependencies @dependencies = Hash.new do |dependencies, platform| dependencies[platform] = [] if spec = @specs[platform] spec.dependencies.each do |dep| next if dep.type == :development next if @ignores_bundler_dependencies && dep.name == "bundler".freeze dependencies[platform] << DepProxy.new(dep, platform) end end dependencies[platform] end end def metadata_dependencies(spec, platform) return [] unless spec # Only allow endpoint specifications since they won't hit the network to # fetch the full gemspec when calling required_ruby_version return [] if !spec.is_a?(EndpointSpecification) && !spec.is_a?(Gem::Specification) dependencies = [] if !spec.required_ruby_version.nil? && !spec.required_ruby_version.none? dependencies << DepProxy.new(Gem::Dependency.new("ruby\0", spec.required_ruby_version), platform) end if !spec.required_rubygems_version.nil? && !spec.required_rubygems_version.none? dependencies << DepProxy.new(Gem::Dependency.new("rubygems\0", spec.required_rubygems_version), platform) end dependencies end end end end [SpecGroup] Remove unused ivar # frozen_string_literal: true module Bundler class Resolver class SpecGroup include GemHelpers attr_accessor :name, :version, :source attr_accessor :ignores_bundler_dependencies def initialize(all_specs) raise ArgumentError, "cannot initialize with an empty value" unless exemplary_spec = all_specs.first @name = exemplary_spec.name @version = exemplary_spec.version @source = exemplary_spec.source @activated_platforms = [] @dependencies = nil @specs = Hash.new do |specs, platform| specs[platform] = select_best_platform_match(all_specs, platform) end @ignores_bundler_dependencies = true end def to_specs @activated_platforms.map do |p| next unless s = @specs[p] lazy_spec = LazySpecification.new(name, version, s.platform, source) lazy_spec.dependencies.replace s.dependencies lazy_spec end.compact end def activate_platform!(platform) return unless for?(platform) return if @activated_platforms.include?(platform) @activated_platforms << platform end def for?(platform) spec = @specs[platform] !spec.nil? end def to_s @to_s ||= "#{name} (#{version})" end def dependencies_for_activated_platforms dependencies = @activated_platforms.map {|p| __dependencies[p] } metadata_dependencies = @activated_platforms.map do |platform| metadata_dependencies(@specs[platform], platform) end dependencies.concat(metadata_dependencies).flatten end def platforms_for_dependency_named(dependency) __dependencies.select {|_, deps| deps.map(&:name).include? dependency }.keys end def ==(other) return unless other.is_a?(SpecGroup) name == other.name && version == other.version && source == other.source end def eql?(other) name.eql?(other.name) && version.eql?(other.version) && source.eql?(other.source) end def hash to_s.hash ^ source.hash end private def __dependencies @dependencies = Hash.new do |dependencies, platform| dependencies[platform] = [] if spec = @specs[platform] spec.dependencies.each do |dep| next if dep.type == :development next if @ignores_bundler_dependencies && dep.name == "bundler".freeze dependencies[platform] << DepProxy.new(dep, platform) end end dependencies[platform] end end def metadata_dependencies(spec, platform) return [] unless spec # Only allow endpoint specifications since they won't hit the network to # fetch the full gemspec when calling required_ruby_version return [] if !spec.is_a?(EndpointSpecification) && !spec.is_a?(Gem::Specification) dependencies = [] if !spec.required_ruby_version.nil? && !spec.required_ruby_version.none? dependencies << DepProxy.new(Gem::Dependency.new("ruby\0", spec.required_ruby_version), platform) end if !spec.required_rubygems_version.nil? && !spec.required_rubygems_version.none? dependencies << DepProxy.new(Gem::Dependency.new("rubygems\0", spec.required_rubygems_version), platform) end dependencies end end end end
class Heroku::Analytics extend Heroku::Helpers def self.record(command) return if skip_analytics commands = json_decode(File.read(path)) || [] rescue [] commands << {command: command, timestamp: Time.now.to_i, version: Heroku::VERSION, platform: RUBY_PLATFORM, language: "ruby/#{RUBY_VERSION}"} File.open(path, 'w') { |f| f.write(json_encode(commands)) } rescue end def self.submit return if skip_analytics commands = json_decode(File.read(path)) return if commands.count < 10 # only submit if we have 10 entries to send fork do payload = { user: user, commands: commands, } Excon.post('https://cli-analytics.heroku.com/record', body: JSON.dump(payload)) File.truncate(path, 0) end rescue end private def self.skip_analytics return true if ['1', 'true'].include?(ENV['HEROKU_SKIP_ANALYTICS']) skip = Heroku::Config[:skip_analytics] if skip == nil return false unless $stdin.isatty # user has not specified whether or not they want to submit usage information # prompt them to ask, but if they wait more than 20 seconds just assume they # want to skip analytics require 'timeout' stderr_print "Would you like to submit Heroku CLI usage information to better improve the CLI user experience?\n[y/N] " input = begin Timeout::timeout(20) do ask.downcase end rescue stderr_puts 'n' end Heroku::Config[:skip_analytics] = !['y', 'yes'].include?(input) Heroku::Config.save! return Heroku::Config[:skip_analytics] end skip end def self.path File.join(Heroku::Helpers.home_directory, ".heroku", "analytics.json") end def self.user credentials = Heroku::Auth.read_credentials credentials[0] if credentials end end skip analytics if not a tty class Heroku::Analytics extend Heroku::Helpers def self.record(command) return if skip_analytics commands = json_decode(File.read(path)) || [] rescue [] commands << {command: command, timestamp: Time.now.to_i, version: Heroku::VERSION, platform: RUBY_PLATFORM, language: "ruby/#{RUBY_VERSION}"} File.open(path, 'w') { |f| f.write(json_encode(commands)) } rescue end def self.submit return if skip_analytics commands = json_decode(File.read(path)) return if commands.count < 10 # only submit if we have 10 entries to send fork do payload = { user: user, commands: commands, } Excon.post('https://cli-analytics.heroku.com/record', body: JSON.dump(payload)) File.truncate(path, 0) end rescue end private def self.skip_analytics return true if ['1', 'true'].include?(ENV['HEROKU_SKIP_ANALYTICS']) skip = Heroku::Config[:skip_analytics] if skip == nil return true unless $stdin.isatty # user has not specified whether or not they want to submit usage information # prompt them to ask, but if they wait more than 20 seconds just assume they # want to skip analytics require 'timeout' stderr_print "Would you like to submit Heroku CLI usage information to better improve the CLI user experience?\n[y/N] " input = begin Timeout::timeout(20) do ask.downcase end rescue stderr_puts 'n' end Heroku::Config[:skip_analytics] = !['y', 'yes'].include?(input) Heroku::Config.save! return Heroku::Config[:skip_analytics] end skip end def self.path File.join(Heroku::Helpers.home_directory, ".heroku", "analytics.json") end def self.user credentials = Heroku::Auth.read_credentials credentials[0] if credentials end end
module Caboodle class FlickrAPI < Weary::Base def initialize(opts={}) self.defaults = {:api_key => Site.flickr_api_key} end declare "photosets" do |r| r.url = "http://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=#{Site.flickr_api_key}&user_id=#{Site.flickr_user_id}" r.via = :get end declare "photoset" do |r| r.url = "http://api.flickr.com/services/rest/" r.with = [:api_key, :photoset_id] r.requires = [:api_key, :photoset_id,:method] r.via = :get end def self.photoset_info(id) Caboodle.mash(new.photoset({:photoset_id=>id,:method=>"flickr.photosets.getInfo"})).rsp.photoset end def self.photoset_photos(id) Caboodle.mash(new.photoset({:photoset_id=>id,:method=>"flickr.photosets.getPhotos"})).rsp.photoset.photo end def self.photosets Caboodle.mash(new.photosets).rsp.photosets.photoset end end class Flickr < Caboodle::Kit set :views, File.join(File.dirname(__FILE__), "views") set :public, File.join(File.dirname(__FILE__), "public") def home @photosets = FlickrAPI.photosets rescue [] @title = "Photography" haml :photography end get "/photography" do home end get "/photography/:set_id" do |set_id| @photosets = FlickrAPI.photosets rescue [] @set_id = set_id @photoset = Caboodle::FlickrAPI.photoset_info(@set_id) rescue nil @title = "Photography: #{@photoset.title if @photoset.respond_to?(:title)}" haml :photography end required [:flickr_username, :flickr_user_id, :flickr_api_key] menu "Photography", "/photography" end end automatically work out the flickr user id using YQL module Caboodle class FlickrAPI < Weary::Base def initialize(opts={}) self.defaults = {:api_key => Site.flickr_api_key} end declare "photosets" do |r| r.url = "http://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=#{Site.flickr_api_key}&user_id=#{FlickrAPI.flickr_user_id}" r.via = :get end declare "photoset" do |r| r.url = "http://api.flickr.com/services/rest/" r.with = [:api_key, :photoset_id] r.requires = [:api_key, :photoset_id,:method] r.via = :get end def self.photoset_info(id) Caboodle.mash(new.photoset({:photoset_id=>id,:method=>"flickr.photosets.getInfo"})).rsp.photoset end def self.photoset_photos(id) Caboodle.mash(new.photoset({:photoset_id=>id,:method=>"flickr.photosets.getPhotos"})).rsp.photoset.photo end def self.photosets Caboodle.mash(new.photosets).rsp.photosets.photoset end def self.flickr_user_id return Site.flickr_user_id unless Site.flickr_user_id.blank? url = "http://query.yahooapis.com/v1/public/yql?q=use%20%22http%3A%2F%2Fisithackday.com%2Fapi%2Fflickr.whois.xml%22%20as%20flickr.whois%3Bselect%20*%20from%20flickr.whois%20where%20owner%3D%22#{Site.flickr_username}%22&format=xml" doc = Nokogiri::XML.parse(open(url)) val = doc.css("owner").first.attributes["nsid"].value Site.flickr_user_id = val Caboodle::Kit.dump_config Site.flickr_user_id end end class Flickr < Caboodle::Kit set :views, File.join(File.dirname(__FILE__), "views") set :public, File.join(File.dirname(__FILE__), "public") def home @photosets = FlickrAPI.photosets rescue [] @title = "Photography" haml :photography end get "/photography" do home end get "/photography/:set_id" do |set_id| @photosets = FlickrAPI.photosets rescue [] @set_id = set_id @photoset = Caboodle::FlickrAPI.photoset_info(@set_id) rescue nil @title = "Photography: #{@photoset.title if @photoset.respond_to?(:title)}" haml :photography end required [:flickr_username, :flickr_api_key] menu "Photography", "/photography" end end
module Hubstats VERSION = "0.10.0" end Version Bump module Hubstats VERSION = "0.11.0" end
module Capistrano module ChefEye VERSION = '0.2.4' end end Finish 0.2.5 module Capistrano module ChefEye VERSION = '0.2.5' end end
Script for generating geometry tiles. require 'pg' if ARGV.size != 2 puts "Usage: generate_tiles.rb <zoom level> <limit> [offset]" exit end ZOOM_LEVEL = ARGV[0] LIMIT = ARGV[1] OFFSET = ARGV[2] || 100 $config = { 'host' => 'localhost', 'port' => 5432, 'dbname' => 'osmdb', 'user' => 'ppawel', 'password' => 'aa' } @conn = PGconn.open(:host => $config['host'], :port => $config['port'], :dbname => $config['dbname'], :user => $config['user'], :password => $config['password']) @conn.query("SELECT id FROM changesets ORDER BY created_at DESC LIMIT #{LIMIT}").each do |row| changeset_id = row['id'].to_i puts "Generating tiles for changeset #{changeset_id} at zoom level #{ZOOM_LEVEL}..." tile_count = @conn.query("SELECT OWL_GenerateChangesetTiles(#{changeset_id}, #{ZOOM_LEVEL})").getvalue(0, 0) puts "Done, tile count: #{tile_count}" end
module Capistrano module Puppeteer module Puppet def self.extended(configuration) configuration.load do unless exists? :puppet_path set(:puppet_path) { '/srv/puppet' } unless exists? :puppet_path end namespace :puppet do task :update do fast = ENV['fast'] || ENV['FAST'] || '' fast = fast =~ /true|TRUE|yes|YES/ unless fast system 'git push' run "#{sudo} chown -R `id -un` #{puppet_path}; fi" run "#{sudo} chgrp -R adm #{puppet_path}" run "#{sudo} chmod -R g+rw #{puppet_path}" run "cd #{puppet_path} && git pull --quiet" run "cd #{puppet_path} && if [ -f Gemfile ]; then bundle install --deployment --without=development --quiet ; fi" # TODO Support other methods besides henson run "cd #{puppet_path} && if [ -f Puppetfile ]; then bundle exec henson; fi" end end desc <<-DESC Perform a puppet run. Pass options to puppt using OPTIONS puppet:go options="--noop" DESC task :go do update options = ENV['options'] || ENV['OPTIONS'] || '' apply = ENV['apply'] || ENV['APPLY'] || '' apply = apply =~ /true|TRUE|yes|YES/ p apply puppet_options = ['--noop'] if options puppet_options += options.split(' ') end puppet_options.delete('--noop') if apply options = puppet_options.join(' ') run "cd #{puppet_path} && #{sudo} puppet apply --config puppet.conf --verbose #{options} manifests/site.pp" end end end end end end end if Capistrano::Configuration.instance Capistrano::Configuration.instance.extend Capistrano::Puppeteer::Puppet end dd binstubs for root ruby installs module Capistrano module Puppeteer module Puppet def self.extended(configuration) configuration.load do unless exists? :puppet_path set(:puppet_path) { '/srv/puppet' } unless exists? :puppet_path end namespace :puppet do task :update do fast = ENV['fast'] || ENV['FAST'] || '' fast = fast =~ /true|TRUE|yes|YES/ unless fast system 'git push' run "#{sudo} chown -R `id -un` #{puppet_path}; fi" run "#{sudo} chgrp -R adm #{puppet_path}" run "#{sudo} chmod -R g+rw #{puppet_path}" run "cd #{puppet_path} && git pull --quiet" run "cd #{puppet_path} && if [ -f Gemfile ]; then bundle install --deployment --without=development --binstubs --quiet ; fi" # TODO Support other methods besides henson run "cd #{puppet_path} && if [ -f Puppetfile ]; then bundle exec bin/henson; fi" end end desc <<-DESC Perform a puppet run. Pass options to puppt using OPTIONS puppet:go options="--noop" DESC task :go do update options = ENV['options'] || ENV['OPTIONS'] || '' apply = ENV['apply'] || ENV['APPLY'] || '' apply = apply =~ /true|TRUE|yes|YES/ p apply puppet_options = ['--noop'] if options puppet_options += options.split(' ') end puppet_options.delete('--noop') if apply options = puppet_options.join(' ') run "cd #{puppet_path} && #{sudo} puppet apply --config puppet.conf --verbose #{options} manifests/site.pp" end end end end end end end if Capistrano::Configuration.instance Capistrano::Configuration.instance.extend Capistrano::Puppeteer::Puppet end
module I18nCsv VERSION = "0.1.5" end Updated version accordingly to the latest change module I18nCsv VERSION = "0.1.6" end
namespace :load do task :defaults do set :unicorn_pid, -> { File.join(current_path, "tmp", "pids", "unicorn.pid") } set :unicorn_config_path, -> { File.join(current_path, "config", "unicorn", "#{fetch(:rails_env)}.rb") } set :unicorn_restart_sleep_time, 3 set :unicorn_roles, -> { :app } set :unicorn_options, -> { "" } set :unicorn_rack_env, -> { fetch(:rails_env) == "development" ? "development" : "deployment" } set :unicorn_bundle_gemfile, -> { File.join(current_path, "Gemfile") } end end namespace :unicorn do desc "Start Unicorn" task :start do on roles(fetch(:unicorn_roles)) do within current_path do if test("[ -e #{fetch(:unicorn_pid)} ] && kill -0 #{pid}") info "unicorn is running..." else with rails_env: fetch(:rails_env), bundle_gemfile: fetch(:unicorn_bundle_gemfile) do execute :bundle, "exec unicorn", "-c", fetch(:unicorn_config_path), "-E", fetch(:unicorn_rack_env), "-D", fetch(:unicorn_options) end end end end end desc "Stop Unicorn (QUIT)" task :stop do on roles(fetch(:unicorn_roles)) do within current_path do if test("[ -e #{fetch(:unicorn_pid)} ]") if test("kill -0 #{pid}") info "stopping unicorn..." execute :kill, "-s QUIT", pid else info "cleaning up dead unicorn pid..." execute :rm, fetch(:unicorn_pid) end else info "unicorn is not running..." end end end end desc "Reload Unicorn (HUP); use this when preload_app: false" task :reload do invoke "unicorn:start" on roles(fetch(:unicorn_roles)) do within current_path do info "reloading..." execute :kill, "-s HUP", pid end end end desc "Restart Unicorn (USR2 + QUIT); use this when preload_app: true" task :restart do invoke "unicorn:start" on roles(fetch(:unicorn_roles)) do within current_path do info "unicorn restarting..." execute :kill, "-s USR2", pid execute :sleep, fetch(:unicorn_restart_sleep_time) if test("[ -e #{fetch(:unicorn_pid)}.oldbin ]") execute :kill, "-s QUIT", pid_oldbin end end end end desc "Add a worker (TTIN)" task :add_worker do on roles(fetch(:unicorn_roles)) do within current_path do info "adding worker" execute :kill, "-s TTIN", pid end end end desc "Remove a worker (TTOU)" task :remove_worker do on roles(fetch(:unicorn_roles)) do within current_path do info "removing worker" execute :kill, "-s TTOU", pid end end end end def pid "`cat #{fetch(:unicorn_pid)}`" end def pid_oldbin "`cat #{fetch(:unicorn_pid)}.oldbin`" end rails_env bug fixed namespace :load do task :defaults do set :rails_env, fetch(:stage) set :unicorn_pid, -> { File.join(current_path, "tmp", "pids", "unicorn.pid") } set :unicorn_config_path, -> { File.join(current_path, "config", "unicorn", "#{fetch(:rails_env)}.rb") } set :unicorn_restart_sleep_time, 3 set :unicorn_roles, -> { :app } set :unicorn_options, -> { "" } set :unicorn_rack_env, -> { fetch(:rails_env) == "development" ? "development" : "deployment" } set :unicorn_bundle_gemfile, -> { File.join(current_path, "Gemfile") } end end namespace :unicorn do desc "Start Unicorn" task :start do on roles(fetch(:unicorn_roles)) do within current_path do if test("[ -e #{fetch(:unicorn_pid)} ] && kill -0 #{pid}") info "unicorn is running..." else with rails_env: fetch(:rails_env), bundle_gemfile: fetch(:unicorn_bundle_gemfile) do execute :bundle, "exec unicorn", "-c", fetch(:unicorn_config_path), "-E", fetch(:unicorn_rack_env), "-D", fetch(:unicorn_options) end end end end end desc "Stop Unicorn (QUIT)" task :stop do on roles(fetch(:unicorn_roles)) do within current_path do if test("[ -e #{fetch(:unicorn_pid)} ]") if test("kill -0 #{pid}") info "stopping unicorn..." execute :kill, "-s QUIT", pid else info "cleaning up dead unicorn pid..." execute :rm, fetch(:unicorn_pid) end else info "unicorn is not running..." end end end end desc "Reload Unicorn (HUP); use this when preload_app: false" task :reload do invoke "unicorn:start" on roles(fetch(:unicorn_roles)) do within current_path do info "reloading..." execute :kill, "-s HUP", pid end end end desc "Restart Unicorn (USR2 + QUIT); use this when preload_app: true" task :restart do invoke "unicorn:start" on roles(fetch(:unicorn_roles)) do within current_path do info "unicorn restarting..." execute :kill, "-s USR2", pid execute :sleep, fetch(:unicorn_restart_sleep_time) if test("[ -e #{fetch(:unicorn_pid)}.oldbin ]") execute :kill, "-s QUIT", pid_oldbin end end end end desc "Add a worker (TTIN)" task :add_worker do on roles(fetch(:unicorn_roles)) do within current_path do info "adding worker" execute :kill, "-s TTIN", pid end end end desc "Remove a worker (TTOU)" task :remove_worker do on roles(fetch(:unicorn_roles)) do within current_path do info "removing worker" execute :kill, "-s TTOU", pid end end end end def pid "`cat #{fetch(:unicorn_pid)}`" end def pid_oldbin "`cat #{fetch(:unicorn_pid)}.oldbin`" end
require "i18n_screwdriver/version" require "i18n_screwdriver/translation" require "i18n_screwdriver/translation_helper" require "i18n_screwdriver/rails" module I18nScrewdriver Error = Class.new(StandardError) def self.filename_for_locale(locale) File.join("config", "locales", "application.#{locale}.yml") end def self.generate_key(source) if source.is_a? Symbol ":#{source}" else source = source.strip (source =~ /^:[a-z][a-z0-9_]*$/) ? source : Digest::MD5.hexdigest(source) end end def self.file_with_translations_exists?(locale) File.exists?(filename_for_locale(locale)) end def self.load_translations(locale) path = filename_for_locale(locale) raise Error, "File #{path} not found!" unless File.exists?(path) sanitize_hash(YAML.load_file(path)[locale]) end def self.write_translations(locale, translations) File.open(filename_for_locale(locale), "w") do |file| file.puts "# use rake task i18n:update to generate this file" file.puts file.puts({locale => in_utf8(translations)}.to_yaml(:line_width => -1)) file.puts end end def self.grab_texts_to_be_translated(string) [].tap do |texts| texts.concat(string.scan(/_\((?<!\\)"(.*?)(?<!\\)"\)/).map{ |v| unescape_string(v[0]) }) texts.concat(string.scan(/_\((?<!\\)'(.*?)(?<!\\)'\)/).map{ |v| unescape_string(v[0]) }) end end def self.grab_symbols_to_be_translated(string) string.scan(/_\((:[a-z][a-z0-9_]*)\)/).flatten end def self.grab_js_texts_to_be_translated(string) [].tap do |texts| texts.concat(string.scan(/\bI18n\.screw\(?\s*(?<!\\)"(.*?)(?<!\\)"/).map{ |v| unescape_string(v[0]) }) texts.concat(string.scan(/\bI18n\.screw\(?\s*(?<!\\)'(.*?)(?<!\\)'/).map{ |v| unescape_string(v[0]) }) texts.concat(string.scan(/\bI18n\.screw\(?\s*(?<!\\)`(.*?)(?<!\\)`/).map{ |v| unescape_string(v[0]) }) end end def self.in_utf8(hash) {}.tap do |result| hash.sort.each do |k, v| result[k.encode('UTF-8')] = (v || "").encode('UTF-8') end end end def self.unescape_string(string) "".tap do |result| in_backslash = false string.each_char do |char| if in_backslash case char when 'r' result << "\r" when 'n' result << "\n" when 't' result << "\t" when '"', "'", '\\' result << char else result << '\\' result << char end in_backslash = false else case char when '\\' in_backslash = true else result << char end end end end end def self.gather_translations texts = [] symbols = [] Dir.glob("**/*.{haml,erb,slim,rb}").each do |file| next unless File.file?(file) input = File.read(file) texts.concat(grab_texts_to_be_translated(input)) symbols.concat(grab_symbols_to_be_translated(input)) end Dir.glob("**/*.{js,coffee,hamlc,ejs,erb}").each do |file| next unless File.file?(file) input = File.read(file) texts.concat(grab_js_texts_to_be_translated(input)) end translations = Hash[texts.uniq.map{ |text| [generate_key(text), extract_text(text)] }] translations.merge(Hash[symbols.uniq.map{ |symbol| [generate_key(symbol), ""] }]) end def self.default_locale @default_locale ||= begin raise Error, "Please set I18.default_locale" unless I18n.default_locale.present? I18n.default_locale.to_s end end def self.available_locales @available_locales ||= begin raise Error, "Please set I18.available_locales" unless I18n.available_locales.count > 0 I18n.available_locales.map(&:to_s) end end def self.update_translations_file(locale, translations) existing_translations = file_with_translations_exists?(locale) ? load_translations(locale) : {} existing_translations.select!{ |k| translations.has_key?(k) } translations.each do |k, v| next if existing_translations[k] existing_translations[k] = (default_locale == locale) ? v : nil end write_translations(locale, existing_translations) end def self.sanitize_hash(hash) {}.tap do |new_hash| hash.each{ |k, v| new_hash[k.to_s] = v.to_s } end end def self.translate(string, options = {}) I18n.translate!(generate_key(string), options) rescue I18n::MissingTranslationData I18n.translate(string, options) end def self.extract_text(string) namespace, text = string.split("|", 2) text ? text : namespace end end Use "early-return" syntax instead of conditional require "i18n_screwdriver/version" require "i18n_screwdriver/translation" require "i18n_screwdriver/translation_helper" require "i18n_screwdriver/rails" module I18nScrewdriver Error = Class.new(StandardError) def self.filename_for_locale(locale) File.join("config", "locales", "application.#{locale}.yml") end def self.generate_key(source) return ":#{source}" if source.is_a? Symbol source = source.strip (source =~ /^:[a-z][a-z0-9_]*$/) ? source : Digest::MD5.hexdigest(source) end def self.file_with_translations_exists?(locale) File.exists?(filename_for_locale(locale)) end def self.load_translations(locale) path = filename_for_locale(locale) raise Error, "File #{path} not found!" unless File.exists?(path) sanitize_hash(YAML.load_file(path)[locale]) end def self.write_translations(locale, translations) File.open(filename_for_locale(locale), "w") do |file| file.puts "# use rake task i18n:update to generate this file" file.puts file.puts({locale => in_utf8(translations)}.to_yaml(:line_width => -1)) file.puts end end def self.grab_texts_to_be_translated(string) [].tap do |texts| texts.concat(string.scan(/_\((?<!\\)"(.*?)(?<!\\)"\)/).map{ |v| unescape_string(v[0]) }) texts.concat(string.scan(/_\((?<!\\)'(.*?)(?<!\\)'\)/).map{ |v| unescape_string(v[0]) }) end end def self.grab_symbols_to_be_translated(string) string.scan(/_\((:[a-z][a-z0-9_]*)\)/).flatten end def self.grab_js_texts_to_be_translated(string) [].tap do |texts| texts.concat(string.scan(/\bI18n\.screw\(?\s*(?<!\\)"(.*?)(?<!\\)"/).map{ |v| unescape_string(v[0]) }) texts.concat(string.scan(/\bI18n\.screw\(?\s*(?<!\\)'(.*?)(?<!\\)'/).map{ |v| unescape_string(v[0]) }) texts.concat(string.scan(/\bI18n\.screw\(?\s*(?<!\\)`(.*?)(?<!\\)`/).map{ |v| unescape_string(v[0]) }) end end def self.in_utf8(hash) {}.tap do |result| hash.sort.each do |k, v| result[k.encode('UTF-8')] = (v || "").encode('UTF-8') end end end def self.unescape_string(string) "".tap do |result| in_backslash = false string.each_char do |char| if in_backslash case char when 'r' result << "\r" when 'n' result << "\n" when 't' result << "\t" when '"', "'", '\\' result << char else result << '\\' result << char end in_backslash = false else case char when '\\' in_backslash = true else result << char end end end end end def self.gather_translations texts = [] symbols = [] Dir.glob("**/*.{haml,erb,slim,rb}").each do |file| next unless File.file?(file) input = File.read(file) texts.concat(grab_texts_to_be_translated(input)) symbols.concat(grab_symbols_to_be_translated(input)) end Dir.glob("**/*.{js,coffee,hamlc,ejs,erb}").each do |file| next unless File.file?(file) input = File.read(file) texts.concat(grab_js_texts_to_be_translated(input)) end translations = Hash[texts.uniq.map{ |text| [generate_key(text), extract_text(text)] }] translations.merge(Hash[symbols.uniq.map{ |symbol| [generate_key(symbol), ""] }]) end def self.default_locale @default_locale ||= begin raise Error, "Please set I18.default_locale" unless I18n.default_locale.present? I18n.default_locale.to_s end end def self.available_locales @available_locales ||= begin raise Error, "Please set I18.available_locales" unless I18n.available_locales.count > 0 I18n.available_locales.map(&:to_s) end end def self.update_translations_file(locale, translations) existing_translations = file_with_translations_exists?(locale) ? load_translations(locale) : {} existing_translations.select!{ |k| translations.has_key?(k) } translations.each do |k, v| next if existing_translations[k] existing_translations[k] = (default_locale == locale) ? v : nil end write_translations(locale, existing_translations) end def self.sanitize_hash(hash) {}.tap do |new_hash| hash.each{ |k, v| new_hash[k.to_s] = v.to_s } end end def self.translate(string, options = {}) I18n.translate!(generate_key(string), options) rescue I18n::MissingTranslationData I18n.translate(string, options) end def self.extract_text(string) namespace, text = string.split("|", 2) text ? text : namespace end end
module CelluloidBenchmark VERSION = "0.1.15" end Rev version for fundamental change: us X-Runtime header to measure server repsonse time more reliably. module CelluloidBenchmark VERSION = "0.2.0" end
# # Author:: Adam Jacob (<adam@opscode.com>) # Copyright:: Copyright (c) 2008 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/win32/wmi' class Chef class Platform class << self def windows? if RUBY_PLATFORM =~ /mswin|mingw|windows/ true else false end end def windows_server_2003? return false unless windows? require 'wmi-lite/wmi' # CHEF-4888: Work around ruby #2618, expected to be fixed in Ruby 2.1.0 # https://github.com/ruby/ruby/commit/588504b20f5cc880ad51827b93e571e32446e5db # https://github.com/ruby/ruby/commit/27ed294c7134c0de582007af3c915a635a6506cd WIN32OLE.ole_initialize wmi = WmiLite::Wmi.new host = wmi.first_of('Win32_OperatingSystem') is_server_2003 = (host['version'] && host['version'].start_with?("5.2")) WIN32OLE.ole_uninitialize is_server_2003 end end end end Move Windows-only deps to Windows only code path # # Author:: Adam Jacob (<adam@opscode.com>) # Copyright:: Copyright (c) 2008 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class Chef class Platform class << self def windows? if RUBY_PLATFORM =~ /mswin|mingw|windows/ true else false end end def windows_server_2003? return false unless windows? require 'wmi-lite/wmi' require 'chef/win32/wmi' # CHEF-4888: Work around ruby #2618, expected to be fixed in Ruby 2.1.0 # https://github.com/ruby/ruby/commit/588504b20f5cc880ad51827b93e571e32446e5db # https://github.com/ruby/ruby/commit/27ed294c7134c0de582007af3c915a635a6506cd WIN32OLE.ole_initialize wmi = WmiLite::Wmi.new host = wmi.first_of('Win32_OperatingSystem') is_server_2003 = (host['version'] && host['version'].start_with?("5.2")) WIN32OLE.ole_uninitialize is_server_2003 end end end end
module IceCube VERSION = '0.15.0' end Bump version to 0.16.0 Mostly motivated by introduction of new validation errors. module IceCube VERSION = '0.16.0' end
# # Author:: Hugo Fichter # Author:: Lamont Granquist (<lamont@getchef.com>) # Author:: Joshua Timberman (<joshua@getchef.com>) # Copyright:: Copyright (c) 2009-2014 Opscode, Inc # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/provider/mount' require 'chef/log' require 'chef/mixin/shell_out' class Chef class Provider class Mount class Solaris < Chef::Provider::Mount include Chef::Mixin::ShellOut extend Forwardable def_delegator :@new_resource, :device, :device def_delegator :@new_resource, :dump, :dump def_delegator :@new_resource, :fstype, :fstype def_delegator :@new_resource, :mount_point, :mount_point def_delegator :@new_resource, :options, :options def_delegator :@new_resource, :pass, :pass def initialize(new_resource, run_context) if new_resource.device_type == :device Chef::Log.error("Mount resource can only be of of device_type ':device' on Solaris") end super end def load_current_resource self.current_resource = Chef::Resource::Mount.new(new_resource.name) current_resource.mount_point(mount_point) current_resource.device(device) current_resource.mounted(mounted?) current_resource.enabled(enabled?) end def define_resource_requirements requirements.assert(:mount, :remount) do |a| a.assertion { !device_should_exist? || ::File.exists?(device) } a.failure_message(Chef::Exceptions::Mount, "Device #{device} does not exist") a.whyrun("Assuming device #{device} would have been created") end requirements.assert(:mount, :remount) do |a| a.assertion { ::File.exists?(mount_point) } a.failure_message(Chef::Exceptions::Mount, "Mount point #{mount_point} does not exist") a.whyrun("Assuming mount point #{mount_point} would have been created") end end protected def mount_fs actual_options = unless options.nil? options(options.delete("noauto")) end command = "mount -F #{fstype}" command << " -o #{actual_options.join(',')}" unless actual_options.nil? || actual_options.empty? command << " #{device} #{mount_point}" shell_out!(command) end def umount_fs shell_out!("umount #{mount_point}") end def remount_fs shell_out!("mount -o remount #{mount_point}") end def enable_fs if !mount_options_unchanged? # Options changed: disable first, then re-enable. disable_fs if current_resource.enabled end auto = options.nil? || ! options.include?("noauto") actual_options = unless options.nil? options.delete("noauto") options end autostr = auto ? 'yes' : 'no' passstr = pass == 0 ? "-" : pass optstr = (actual_options.nil? || actual_options.empty?) ? "-" : actual_options.join(',') Tempfile.open("vfstab", "etc") do |f| f.write(IO.read("/etc/vfstab")) f.puts("#{device}\t-\t#{mount_point}\t#{fstype}\t#{passstr}\t#{autostr}\t#{optstr}") f.close FileUtils.mv f.path, "/etc/vfstab" end end def disable_fs contents = [] found = false ::File.readlines("/etc/vfstab").reverse_each do |line| if !found && line =~ /^#{device_vfstab_regex}\s+[-\/\w]+\s+#{Regexp.escape(mount_point)}/ found = true Chef::Log.debug("#{new_resource} is removed from vfstab") next end contents << line end Tempfile.open("vfstab", "etc") do |f| f.write(contents.reverse) f.close FileUtils.mv f.path, "/etc/vfstab" end end def mount_options_unchanged? current_resource.fstype == fstype and current_resource.options == options and current_resource.dump == dump and current_resource.pass == pass end private def enabled? # Check to see if there is a entry in /etc/vfstab. Last entry for a volume wins. enabled = false ::File.foreach("/etc/vfstab") do |line| case line when /^[#\s]/ next # solaris /etc/vfstab format: # device device mount FS fsck mount mount # to mount to fsck point type pass at boot options when /^#{device_vfstab_regex}\s+[-\/\w]+\s+#{Regexp.escape(mount_point)}\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ enabled = true current_resource.fstype($1) # Store the 'mount at boot' column from vfstab as the 'noauto' option # in current_resource.options (linux style) no_auto_option = ($3 == "yes") options = $4 if no_auto_option if options.nil? || options.empty? options = "noauto" else options += ",noauto" end end current_resource.options(options) if $2 == "-" pass = 0 else pass = $2.to_i end current_resource.pass(pass) Chef::Log.debug("Found mount #{device} to #{mount_point} in /etc/vfstab") next when /^[-\/\w]+\s+[-\/\w]+\s+#{Regexp.escape(mount_point)}\s+/ enabled = false Chef::Log.debug("Found conflicting mount point #{mount_point} in /etc/vfstab") end end enabled end def mounted? shell_out!("mount").stdout.each_line do |line| # on solaris, 'mount' prints "<mount point> on <device> ...' case line when /^#{Regexp.escape(mount_point)}\s+on\s+#{device_mount_regex}/ Chef::Log.debug("Special device #{device} is mounted as #{mount_point}") return true when /^#{Regexp.escape(mount_point)}\son\s([\/\w])+\s+/ Chef::Log.debug("Special device #{$~[1]} is mounted as #{mount_point}") end end return false end def device_should_exist? device !~ /:/ && device !~ /\/\// && fstype != "tmpfs" && fstype != 'fuse' end def device_mount_regex ::File.symlink?(device) ? "(?:#{Regexp.escape(device)})|(?:#{Regexp.escape(::File.readlink(device))})" : Regexp.escape(device) end def device_vfstab_regex device_mount_regex end end end end end add VFSTAB constant # # Author:: Hugo Fichter # Author:: Lamont Granquist (<lamont@getchef.com>) # Author:: Joshua Timberman (<joshua@getchef.com>) # Copyright:: Copyright (c) 2009-2014 Opscode, Inc # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/provider/mount' require 'chef/log' require 'chef/mixin/shell_out' class Chef class Provider class Mount class Solaris < Chef::Provider::Mount include Chef::Mixin::ShellOut extend Forwardable VFSTAB = "/etc/vfstab".freeze def_delegator :@new_resource, :device, :device def_delegator :@new_resource, :dump, :dump def_delegator :@new_resource, :fstype, :fstype def_delegator :@new_resource, :mount_point, :mount_point def_delegator :@new_resource, :options, :options def_delegator :@new_resource, :pass, :pass def initialize(new_resource, run_context) if new_resource.device_type == :device Chef::Log.error("Mount resource can only be of of device_type ':device' on Solaris") end super end def load_current_resource self.current_resource = Chef::Resource::Mount.new(new_resource.name) current_resource.mount_point(mount_point) current_resource.device(device) current_resource.mounted(mounted?) current_resource.enabled(enabled?) end def define_resource_requirements requirements.assert(:mount, :remount) do |a| a.assertion { !device_should_exist? || ::File.exists?(device) } a.failure_message(Chef::Exceptions::Mount, "Device #{device} does not exist") a.whyrun("Assuming device #{device} would have been created") end requirements.assert(:mount, :remount) do |a| a.assertion { ::File.exists?(mount_point) } a.failure_message(Chef::Exceptions::Mount, "Mount point #{mount_point} does not exist") a.whyrun("Assuming mount point #{mount_point} would have been created") end end protected def mount_fs actual_options = unless options.nil? options(options.delete("noauto")) end command = "mount -F #{fstype}" command << " -o #{actual_options.join(',')}" unless actual_options.nil? || actual_options.empty? command << " #{device} #{mount_point}" shell_out!(command) end def umount_fs shell_out!("umount #{mount_point}") end def remount_fs shell_out!("mount -o remount #{mount_point}") end def enable_fs if !mount_options_unchanged? # Options changed: disable first, then re-enable. disable_fs if current_resource.enabled end auto = options.nil? || ! options.include?("noauto") actual_options = unless options.nil? options.delete("noauto") options end autostr = auto ? 'yes' : 'no' passstr = pass == 0 ? "-" : pass optstr = (actual_options.nil? || actual_options.empty?) ? "-" : actual_options.join(',') Tempfile.open("vfstab", "etc") do |f| f.write(IO.read(VFSTAB)) f.puts("#{device}\t-\t#{mount_point}\t#{fstype}\t#{passstr}\t#{autostr}\t#{optstr}") f.close FileUtils.mv f.path, VFSTAB end end def disable_fs contents = [] found = false ::File.readlines(VFSTAB).reverse_each do |line| if !found && line =~ /^#{device_vfstab_regex}\s+[-\/\w]+\s+#{Regexp.escape(mount_point)}/ found = true Chef::Log.debug("#{new_resource} is removed from vfstab") next end contents << line end Tempfile.open("vfstab", "etc") do |f| f.write(contents.reverse) f.close FileUtils.mv f.path, VFSTAB end end def mount_options_unchanged? current_resource.fstype == fstype and current_resource.options == options and current_resource.dump == dump and current_resource.pass == pass end private def enabled? # Check to see if there is a entry in /etc/vfstab. Last entry for a volume wins. enabled = false ::File.foreach(VFSTAB) do |line| case line when /^[#\s]/ next # solaris /etc/vfstab format: # device device mount FS fsck mount mount # to mount to fsck point type pass at boot options when /^#{device_vfstab_regex}\s+[-\/\w]+\s+#{Regexp.escape(mount_point)}\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ enabled = true current_resource.fstype($1) # Store the 'mount at boot' column from vfstab as the 'noauto' option # in current_resource.options (linux style) no_auto_option = ($3 == "yes") options = $4 if no_auto_option if options.nil? || options.empty? options = "noauto" else options += ",noauto" end end current_resource.options(options) if $2 == "-" pass = 0 else pass = $2.to_i end current_resource.pass(pass) Chef::Log.debug("Found mount #{device} to #{mount_point} in #{VFSTAB}") next when /^[-\/\w]+\s+[-\/\w]+\s+#{Regexp.escape(mount_point)}\s+/ enabled = false Chef::Log.debug("Found conflicting mount point #{mount_point} in #{VFSTAB}") end end enabled end def mounted? shell_out!("mount").stdout.each_line do |line| # on solaris, 'mount' prints "<mount point> on <device> ...' case line when /^#{Regexp.escape(mount_point)}\s+on\s+#{device_mount_regex}/ Chef::Log.debug("Special device #{device} is mounted as #{mount_point}") return true when /^#{Regexp.escape(mount_point)}\son\s([\/\w])+\s+/ Chef::Log.debug("Special device #{$~[1]} is mounted as #{mount_point}") end end return false end def device_should_exist? device !~ /:/ && device !~ /\/\// && fstype != "tmpfs" && fstype != 'fuse' end def device_mount_regex ::File.symlink?(device) ? "(?:#{Regexp.escape(device)})|(?:#{Regexp.escape(::File.readlink(device))})" : Regexp.escape(device) end def device_vfstab_regex device_mount_regex end end end end end
require "addressable/uri" require 'cgi' module Identity class Account < Sinatra::Base register ErrorHandling register HerokuCookie register Sinatra::Namespace include Helpers::API include Helpers::Auth include Helpers::Log configure do set :views, "#{Config.root}/views" end before do @cookie = Cookie.new(env["rack.session"]) @oauth_dance_id = request.cookies["oauth_dance_id"] end namespace "/account" do # The omniauth strategy used to make a call to /account after a # successful authentication, so proxy this through to core. # Authentication occurs via a header with a bearer token. # # Remove this as soon as we get Devcenter and Dashboard upgraded. get do return 401 if !request.env["HTTP_AUTHORIZATION"] api = HerokuAPI.new(user: nil, request_ids: request_ids, version: 2, authorization: request.env["HTTP_AUTHORIZATION"], ip: request.ip, # not necessarily V3, respond with whatever the client asks for headers: { "Accept" => request.env["HTTP_ACCEPT"] || "application/json" }) begin res = api.get(path: "/account", expects: 200) content_type(:json) res.body rescue Excon::Errors::Unauthorized return 401 end end get "/accept/:id/:token" do |id, token| redirect_to_signup_app(request.path) end # This endpoint is unreachable except if a user manually hits it by # manipulating their browser during the signup process. get "/accept/ok" do redirect_to_signup_app(request.path) end # This endpoint is NOT protected against CSRF, because the signup app needs it # to verify and log the user in. post "/accept/ok" do begin api = HerokuAPI.new(ip: request.ip, request_ids: request_ids, version: 2) res = api.post(path: "/invitation2/save", expects: 200, body: URI.encode_www_form({ "id" => params[:id], "token" => params[:token], "user[password]" => params[:password], "user[password_confirmation]" => params[:password_confirmation], "user[receive_newsletter]" => params[:receive_newsletter], })) json = MultiJson.decode(res.body) # log the user in right away perform_oauth_dance(json["email"], params[:password], nil) @redirect_uri = if @cookie.authorize_params # if we know that we're in the middle of an authorization attempt, # continue it authorize(@cookie.authorize_params) # users who signed up from a particular source may have a specialized # redirect location; otherwise go to Dashboard else redirect_to_signup_app(request.path) end # given client_id wasn't found (API throws a 400 status) rescue Excon::Errors::BadRequest flash[:error] = "Unknown OAuth client." redirect to("/login") # we couldn't track the user's session meaning that it's likely been # destroyed or expired, redirect to login rescue Excon::Errors::NotFound redirect to("/login") # refresh token dance was unsuccessful rescue Excon::Errors::Unauthorized redirect to("/login") # client not yet authorized; show the user a confirmation dialog rescue Identity::Errors::UnauthorizedClient => e @client = e.client @scope = @cookie && @cookie.authorize_params["scope"] || nil slim :"clients/authorize", layout: :"layouts/purple" # some problem occurred with the signup rescue Excon::Errors::UnprocessableEntity => e flash[:error] = decode_error(e.response.body) redirect to("/account/accept/#{params[:id]}/#{params[:token]}") end end get "/email/confirm/:token" do |token| begin # confirming an e-mail change requires authentication raise Identity::Errors::LoginRequired unless @cookie.access_token api = HerokuAPI.new( user: nil, pass: @cookie.access_token, ip: request.ip, request_ids: request_ids, version: 3) api.patch( path: "/users/~", expects: 200, body: URI.encode_www_form(email_change_token: params[:token])) redirect to(Config.dashboard_url) # user tried to access the change e-mail request under the wrong # account rescue Excon::Errors::Forbidden flash[:error] = "This link can't be used with your current login." redirect to("/login") rescue Excon::Errors::NotFound, Excon::Errors::UnprocessableEntity slim :"account/email/not_found", layout: :"layouts/purple" # it seems that the user's access token is no longer valid, refresh rescue Excon::Errors::Unauthorized begin perform_oauth_refresh_dance redirect to(request.path_info) # refresh dance unsuccessful rescue Excon::Errors::Unauthorized redirect to("/logout") end rescue Identity::Errors::LoginRequired @cookie.redirect_url = request.env["PATH_INFO"] redirect to("/login") end end get "/password/reset" do slim :"account/password/reset", layout: :"layouts/purple" end post "/password/reset" do begin api = HerokuAPI.new(ip: request.ip, request_ids: request_ids, version: 2) res = api.post(path: "/auth/reset_password", expects: 200, body: URI.encode_www_form({ email: params[:email] })) json = MultiJson.decode(res.body) flash.now[:notice] = json["message"] slim :"account/password/reset", layout: :"layouts/purple" rescue Excon::Errors::NotFound, Excon::Errors::UnprocessableEntity => e flash[:error] = decode_error(e.response.body) redirect to("/account/password/reset") end end get "/password/reset/:token" do |token| begin api = HerokuAPI.new(ip: request.ip, request_ids: request_ids, version: 2) res = api.get(path: "/auth/finish_reset_password/#{token}", expects: 200) @user = MultiJson.decode(res.body) # Persist the user in the flash in case we need to render an error # from the post. flash[:user] = @user slim :"account/password/finish_reset", layout: :"layouts/purple" rescue Excon::Errors::NotFound => e slim :"account/password/not_found", layout: :"layouts/purple" end end post "/password/reset/:token" do |token| begin api = HerokuAPI.new(ip: request.ip, request_ids: request_ids, version: 2) body = URI.encode_www_form({ :password => params[:password], :password_confirmation => params[:password_confirmation], }) api.post(path: "/auth/finish_reset_password/#{token}", expects: 200, body: body) flash[:success] = "Your password has been changed." redirect to("/login") rescue Excon::Errors::NotFound => e slim :"account/password/not_found", layout: :"layouts/purple" rescue Excon::Errors::Forbidden, Excon::Errors::UnprocessableEntity => e Identity.log(password_reset_error: true, error_body: e.response.body, error_code: e.response.status) @user = flash[:user] flash[:error] = decode_error(e.response.body) redirect to("/account/password/reset/#{token}") end end get "/two-factor/recovery" do @sms_number = fetch_sms_number slim :"account/two-factor/recovery", layout: :"layouts/purple" end post "/two-factor/recovery/sms" do options = { ip: request.ip, request_ids: request_ids, user: @cookie.email, pass: @cookie.password, version: "3", } begin api = HerokuAPI.new(options) res = api.post(path: "/users/~/sms-number/actions/recover", expects: 201) rescue Excon::Errors::UnprocessableEntity => e flash[:error] = decode_error(e.response.body) redirect to("/login/two-factor") end redirect to("/account/two-factor/recovery/sms") end get "/two-factor/recovery/sms" do @sms_number = fetch_sms_number slim :"account/two-factor/recovery_sms", layout: :"layouts/purple" end end get "/signup" do redirect_to_signup_app("") end get "/signup/:slug" do |slug| redirect_to_signup_app("/#{params[:slug]}") end private def generate_referral_slug(original_slug) referral = nil secret = nil secret = ENV['REFERRAL_SECRET'] if ENV.has_key? 'REFERRAL_SECRET' token = request.cookies["ref"] uri = Addressable::URI.new if token && secret begin verifier = Fernet.verifier(secret, token) referral = CGI.escape(verifier.data["referrer"]) rescue Exception => e Identity.log(:referral_slug_error => true, :exception => e.class.name, :message => e.message) end end uri.query_values = { :utm_campaign => request.cookies["utm_campaign"], :utm_source => request.cookies["utm_source"], :utm_medium => request.cookies["utm_medium"], :referral => referral, } # no tracking code, just return the original slug if uri.query_values.all? { |k, v| v.nil? } return original_slug else return "#{original_slug}?#{uri.query}" end end # Redirects to the signup app adding a special param def redirect_to_signup_app(next_path) current_params = CGI.parse(URI.parse(request.fullpath).query.to_s) append_params = { from: 'id' } if redirect_url = @cookie.post_signup_url append_params["redirect-url"] = redirect_url end next_params = URI.encode_www_form(current_params.merge(append_params)) redirect to("#{Config.signup_url}#{next_path}?#{next_params}") end end end use json encoder require "addressable/uri" require 'cgi' module Identity class Account < Sinatra::Base register ErrorHandling register HerokuCookie register Sinatra::Namespace include Helpers::API include Helpers::Auth include Helpers::Log configure do set :views, "#{Config.root}/views" end before do @cookie = Cookie.new(env["rack.session"]) @oauth_dance_id = request.cookies["oauth_dance_id"] end namespace "/account" do # The omniauth strategy used to make a call to /account after a # successful authentication, so proxy this through to core. # Authentication occurs via a header with a bearer token. # # Remove this as soon as we get Devcenter and Dashboard upgraded. get do return 401 if !request.env["HTTP_AUTHORIZATION"] api = HerokuAPI.new(user: nil, request_ids: request_ids, version: 2, authorization: request.env["HTTP_AUTHORIZATION"], ip: request.ip, # not necessarily V3, respond with whatever the client asks for headers: { "Accept" => request.env["HTTP_ACCEPT"] || "application/json" }) begin res = api.get(path: "/account", expects: 200) content_type(:json) res.body rescue Excon::Errors::Unauthorized return 401 end end get "/accept/:id/:token" do |id, token| redirect_to_signup_app(request.path) end # This endpoint is unreachable except if a user manually hits it by # manipulating their browser during the signup process. get "/accept/ok" do redirect_to_signup_app(request.path) end # This endpoint is NOT protected against CSRF, because the signup app needs it # to verify and log the user in. post "/accept/ok" do begin api = HerokuAPI.new(ip: request.ip, request_ids: request_ids, version: 2) res = api.post(path: "/invitation2/save", expects: 200, body: URI.encode_www_form({ "id" => params[:id], "token" => params[:token], "user[password]" => params[:password], "user[password_confirmation]" => params[:password_confirmation], "user[receive_newsletter]" => params[:receive_newsletter], })) json = MultiJson.decode(res.body) # log the user in right away perform_oauth_dance(json["email"], params[:password], nil) @redirect_uri = if @cookie.authorize_params # if we know that we're in the middle of an authorization attempt, # continue it authorize(@cookie.authorize_params) # users who signed up from a particular source may have a specialized # redirect location; otherwise go to Dashboard else redirect_to_signup_app(request.path) end # given client_id wasn't found (API throws a 400 status) rescue Excon::Errors::BadRequest flash[:error] = "Unknown OAuth client." redirect to("/login") # we couldn't track the user's session meaning that it's likely been # destroyed or expired, redirect to login rescue Excon::Errors::NotFound redirect to("/login") # refresh token dance was unsuccessful rescue Excon::Errors::Unauthorized redirect to("/login") # client not yet authorized; show the user a confirmation dialog rescue Identity::Errors::UnauthorizedClient => e @client = e.client @scope = @cookie && @cookie.authorize_params["scope"] || nil slim :"clients/authorize", layout: :"layouts/purple" # some problem occurred with the signup rescue Excon::Errors::UnprocessableEntity => e flash[:error] = decode_error(e.response.body) redirect to("/account/accept/#{params[:id]}/#{params[:token]}") end end get "/email/confirm/:token" do |token| begin # confirming an e-mail change requires authentication raise Identity::Errors::LoginRequired unless @cookie.access_token api = HerokuAPI.new( user: nil, pass: @cookie.access_token, ip: request.ip, request_ids: request_ids, version: 3) api.patch( path: "/users/~", expects: 200, body: MultiJson.encode(email_change_token: params[:token])) redirect to(Config.dashboard_url) # user tried to access the change e-mail request under the wrong # account rescue Excon::Errors::Forbidden flash[:error] = "This link can't be used with your current login." redirect to("/login") rescue Excon::Errors::NotFound, Excon::Errors::UnprocessableEntity slim :"account/email/not_found", layout: :"layouts/purple" # it seems that the user's access token is no longer valid, refresh rescue Excon::Errors::Unauthorized begin perform_oauth_refresh_dance redirect to(request.path_info) # refresh dance unsuccessful rescue Excon::Errors::Unauthorized redirect to("/logout") end rescue Identity::Errors::LoginRequired @cookie.redirect_url = request.env["PATH_INFO"] redirect to("/login") end end get "/password/reset" do slim :"account/password/reset", layout: :"layouts/purple" end post "/password/reset" do begin api = HerokuAPI.new(ip: request.ip, request_ids: request_ids, version: 2) res = api.post(path: "/auth/reset_password", expects: 200, body: URI.encode_www_form({ email: params[:email] })) json = MultiJson.decode(res.body) flash.now[:notice] = json["message"] slim :"account/password/reset", layout: :"layouts/purple" rescue Excon::Errors::NotFound, Excon::Errors::UnprocessableEntity => e flash[:error] = decode_error(e.response.body) redirect to("/account/password/reset") end end get "/password/reset/:token" do |token| begin api = HerokuAPI.new(ip: request.ip, request_ids: request_ids, version: 2) res = api.get(path: "/auth/finish_reset_password/#{token}", expects: 200) @user = MultiJson.decode(res.body) # Persist the user in the flash in case we need to render an error # from the post. flash[:user] = @user slim :"account/password/finish_reset", layout: :"layouts/purple" rescue Excon::Errors::NotFound => e slim :"account/password/not_found", layout: :"layouts/purple" end end post "/password/reset/:token" do |token| begin api = HerokuAPI.new(ip: request.ip, request_ids: request_ids, version: 2) body = URI.encode_www_form({ :password => params[:password], :password_confirmation => params[:password_confirmation], }) api.post(path: "/auth/finish_reset_password/#{token}", expects: 200, body: body) flash[:success] = "Your password has been changed." redirect to("/login") rescue Excon::Errors::NotFound => e slim :"account/password/not_found", layout: :"layouts/purple" rescue Excon::Errors::Forbidden, Excon::Errors::UnprocessableEntity => e Identity.log(password_reset_error: true, error_body: e.response.body, error_code: e.response.status) @user = flash[:user] flash[:error] = decode_error(e.response.body) redirect to("/account/password/reset/#{token}") end end get "/two-factor/recovery" do @sms_number = fetch_sms_number slim :"account/two-factor/recovery", layout: :"layouts/purple" end post "/two-factor/recovery/sms" do options = { ip: request.ip, request_ids: request_ids, user: @cookie.email, pass: @cookie.password, version: "3", } begin api = HerokuAPI.new(options) res = api.post(path: "/users/~/sms-number/actions/recover", expects: 201) rescue Excon::Errors::UnprocessableEntity => e flash[:error] = decode_error(e.response.body) redirect to("/login/two-factor") end redirect to("/account/two-factor/recovery/sms") end get "/two-factor/recovery/sms" do @sms_number = fetch_sms_number slim :"account/two-factor/recovery_sms", layout: :"layouts/purple" end end get "/signup" do redirect_to_signup_app("") end get "/signup/:slug" do |slug| redirect_to_signup_app("/#{params[:slug]}") end private def generate_referral_slug(original_slug) referral = nil secret = nil secret = ENV['REFERRAL_SECRET'] if ENV.has_key? 'REFERRAL_SECRET' token = request.cookies["ref"] uri = Addressable::URI.new if token && secret begin verifier = Fernet.verifier(secret, token) referral = CGI.escape(verifier.data["referrer"]) rescue Exception => e Identity.log(:referral_slug_error => true, :exception => e.class.name, :message => e.message) end end uri.query_values = { :utm_campaign => request.cookies["utm_campaign"], :utm_source => request.cookies["utm_source"], :utm_medium => request.cookies["utm_medium"], :referral => referral, } # no tracking code, just return the original slug if uri.query_values.all? { |k, v| v.nil? } return original_slug else return "#{original_slug}?#{uri.query}" end end # Redirects to the signup app adding a special param def redirect_to_signup_app(next_path) current_params = CGI.parse(URI.parse(request.fullpath).query.to_s) append_params = { from: 'id' } if redirect_url = @cookie.post_signup_url append_params["redirect-url"] = redirect_url end next_params = URI.encode_www_form(current_params.merge(append_params)) redirect to("#{Config.signup_url}#{next_path}?#{next_params}") end end end
module Cigale::Publisher def translate_checkstyle_publisher (xml, pdef) xml.fixme end end checkstyle publisher module Cigale::Publisher def translate_checkstyle_publisher (xml, pdef) xml.healthy pdef["healthy"] xml.unHealthy pdef["unHealthy"] || pdef["unhealthy"] xml.thresholdLimit pdef["healthThreshold"] || pdef["health-threshold"] || "low" xml.pluginName "[CHECKSTYLE] " xml.defaultEncoding pdef["defaultEncoding"] || pdef["default-encoding"] xml.canRunOnFailed boolp(pdef["canRunOnFailed"] || pdef["can-run-on-failed"], false) xml.useStableBuildAsReference boolp(pdef["useStableBuildAsReference"] || pdef["use-stable-build-as-reference"], false) xml.useDeltaValues boolp(pdef["useDeltaValues"] || pdef["use-delta-values"], false) thresholds = pdef["thresholds"] || {} uthresh = thresholds["unstable"] || {} fthresh = thresholds["failed"] || {} xml.thresholds do xml.unstableTotalAll uthresh["totalAll"] || uthresh["total-all"] xml.unstableTotalHigh uthresh["totalHigh"] || uthresh["total-high"] xml.unstableTotalNormal uthresh["totalNormal"] || uthresh["total-normal"] xml.unstableTotalLow uthresh["totalLow"] || uthresh["total-low"] una = (uthresh["newAll"] || uthresh["new-all"]) and xml.unstableNewAll una unh = (uthresh["newHigh"] || uthresh["new-high"]) and xml.unstableNewHigh unh unn = (uthresh["newNormal"] || uthresh["new-normal"]) and xml.unstableNewNormal unn unl = (uthresh["newLow"] || uthresh["new-low"]) and xml.unstableNewLow unl xml.failedTotalAll fthresh["totalAll"] || fthresh["total-all"] xml.failedTotalHigh fthresh["totalHigh"] || fthresh["total-high"] xml.failedTotalNormal fthresh["totalNormal"] || fthresh["total-normal"] xml.failedTotalLow fthresh["totalLow"] || fthresh["total-low"] fna = (fthresh["newAll"] || fthresh["new-all"]) and xml.failedNewAll fna fnh = (fthresh["newHigh"] || fthresh["new-high"]) and xml.failedNewHigh fnh fnn = (fthresh["newNormal"] || fthresh["new-normal"]) and xml.failedNewNormal fnn fnl = (fthresh["newLow"] || fthresh["new-low"]) and xml.failedNewLow fnl end xml.shouldDetectModules boolp(pdef["shouldDetectModules"] || pdef["should-detect-modules"], false) xml.dontComputeNew boolp(pdef["dontComputeNew"] || pdef["dont-compute-new"], true) xml.doNotResolveRelativePaths boolp(pdef["doNotResolveRelativePaths"] || pdef["do-not-resolve-relative-paths"], false) xml.pattern pdef["pattern"] end end
require 'cinch' require 'cinch/plugins/game_bot' require 'rebellion_g54/game' require 'rebellion_g54/role' module Cinch; module Plugins; class RebellionG54 < GameBot include Cinch::Plugin xmatch(/choices/i, method: :choices, group: :rebellion_g54) xmatch(/me\s*$/i, method: :whoami, group: :rebellion_g54) xmatch(/whoami/i, method: :whoami, group: :rebellion_g54) xmatch(/table(?:\s+(##?\w+))?/i, method: :table, group: :rebellion_g54) xmatch(/status/i, method: :status, group: :rebellion_g54) xmatch(/help(?: (.+))?/i, method: :help, group: :rebellion_g54) xmatch(/rules/i, method: :rules, group: :rebellion_g54) xmatch(/settings(?:\s+(##?\w+))?$/i, method: :get_settings, group: :rebellion_g54) xmatch(/settings(?:\s+(##?\w+))? (.+)$/i, method: :set_settings, group: :rebellion_g54) xmatch(/roles\s+list/i, method: :list_possible_roles, group: :rebellion_g54) xmatch(/roles(?:\s+(##?\w+))?$/i, method: :get_roles, group: :rebellion_g54) xmatch(/roles(?:\s+(##?\w+))?\s+random(?:\s+(.+))?/i, method: :random_roles, group: :rebellion_g54) xmatch(/roles(?:\s+(##?\w+))? (.+)$/i, method: :set_roles, group: :rebellion_g54) xmatch(/peek(?:\s+(##?\w+))?/i, method: :peek, group: :rebellion_g54) xmatch(/(\S+)(?:\s+(.*))?/, method: :rebellion_g54, group: :rebellion_g54) common_commands class ChannelOutputter def initialize(bot, game, c) @bot = bot @game = game @chan = c end def player_died(user) @bot.player_died(user, @chan) end def new_cards(user) @bot.tell_cards(@game, user: user) end def puts(msg) @chan.send(msg) end end #-------------------------------------------------------------------------------- # Implementing classes should override these #-------------------------------------------------------------------------------- def game_class ::RebellionG54::Game end def do_start_game(m, game, options) success, error = game.start_game unless success m.reply(error, true) return end Channel(game.channel_name).send("Welcome to game #{game.id}, with roles #{game.roles}") order = game.users.map { |u| dehighlight_nick(u.nick) }.join(' ') Channel(game.channel_name).send("Player order is #{order}") # Tell everyone of their initial stuff game.each_player.each { |player| tell_cards(game, player: player, game_start: true) } game.output_streams << ChannelOutputter.new(self, game, Channel(game.channel_name)) announce_decision(game) end def do_reset_game(game) chan = Channel(game.channel_name) info = table_info(game, show_secrets: true) chan.send(info) end def do_replace_user(game, replaced_user, replacing_user) tell_cards(game, replacing_user) if game.started? end def bg3po_invite_command(channel_name) # Nah, I don't want to do bg3po end #-------------------------------------------------------------------------------- # Other player management #-------------------------------------------------------------------------------- def player_died(user, channel) # Can't use remove_user_from_game because remove would throw an exception. # Instead, just do the same thing it does... channel.devoice(user) # I'm astounded that I can access my parent's @variable @user_games.delete(user) end def tell_cards(game, user: nil, player: nil, game_start: false) player ||= game.find_player(user) user ||= player.user turn = game_start ? 'starting hand' : "Turn #{game.turn_number}" user.send("Game #{game.id} #{turn}: #{player_info(player, show_secrets: true)}") end #-------------------------------------------------------------------------------- # Game #-------------------------------------------------------------------------------- def announce_decision(game) Channel(game.channel_name).send(decision_info(game, show_choices: true)) game.choice_names.keys.each { |p| explanations = format_choice_explanations(game, p) User(p).send(explanations.map { |e| "[#{e}]" }.join(' ')) } end def rebellion_g54(m, command, args = '') game = self.game_of(m) return unless game && game.started? && game.has_player?(m.user) success, error = game.take_choice(m.user, command, args || '') if success if game.winner chan = Channel(game.channel_name) chan.send("Congratulations! #{game.winner.name} is the winner!!!") info = table_info(game, show_secrets: true) chan.send(info) self.start_new_game(game) else announce_decision(game) end else m.user.send(error) end end def choices(m) game = self.game_of(m) return unless game && game.started? && game.has_player?(m.user) explanations = format_choice_explanations(game, m.user) if explanations.empty? m.user.send("You don't need to make any choices right now.") else m.user.send(explanations.map { |e| "[#{e}]" }.join(' ')) end end def whoami(m) game = self.game_of(m) return unless game && game.started? && game.has_player?(m.user) tell_cards(game, user: m.user) end def table(m, channel_name = nil) game = self.game_of(m, channel_name, ['see a game', '!table']) return unless game && game.started? info = table_info(game) m.reply(info) end def status(m) game = self.game_of(m) return unless game if !game.started? if game.size == 0 m.reply('No game in progress. Join and start one!') else m.reply("A game is forming. #{game.size} players have joined: #{game.users.map(&:name).join(', ')}") end return end m.reply(decision_info(game)) end def peek(m, channel_name = nil) return unless self.is_mod?(m.user) game = self.game_of(m, channel_name, ['peek', '!peek']) return unless game && game.started? if game.has_player?(m.user) m.user.send('Cheater!!!') return end info = table_info(game, show_secrets: true) m.user.send(info) end #-------------------------------------------------------------------------------- # Help for player/table info #-------------------------------------------------------------------------------- def format_choice_explanations(game, user) explanations = game.choice_explanations(user) explanations.to_a.map { |label, info| info[:available] ? "#{label}: #{info[:description]}": "#{label} (unavailable): #{info[:why_unavailable]}" } end def decision_info(game, show_choices: false) desc = game.decision_description players = game.choice_names.keys choices = show_choices ? " to pick between #{game.choice_names.values.flatten.uniq.join(', ')}" : '' "Game #{game.id} Turn #{game.turn_number} - #{desc} - Waiting on #{players.join(', ')}#{choices}" end def table_info(game, show_secrets: false) role_tokens = game.role_tokens roles = game.roles.map { |r| tokens = role_tokens[r] || [] tokens_str = (tokens.empty? ? '' : " (#{tokens.map { |t| t.to_s.capitalize }.join(', ')})") "#{::RebellionG54::Role.to_s(r)}#{tokens_str}" }.join(', ') player_tokens = game.player_tokens "Game #{game.id} Turn #{game.turn_number} - #{roles}\n" + game.each_player.map { |player| "#{player.user.name}: #{player_info(player, show_secrets: show_secrets, tokens: player_tokens[player.user])}" }.concat(game.each_dead_player.map { |player| "#{player.user.name}: #{player_info(player, show_secrets: show_secrets)}" }).join("\n") end def player_info(player, show_secrets: false, tokens: []) cards = [] cards.concat(player.each_live_card.map { |c| "(#{show_secrets ? ::RebellionG54::Role.to_s(c.role) : '########'})" }) cards.concat(player.each_side_card.map { |c, r| "<#{show_secrets ? ::RebellionG54::Role.to_s(c.role) : "??#{::RebellionG54::Role.to_s(r)}??"}>" }) cards.concat(player.each_revealed_card.map { |c| "[#{::RebellionG54::Role.to_s(c.role)}]" }) token_str = tokens.empty? ? '' : " - #{tokens.map { |t| t.to_s.capitalize }.join(', ')}" "#{cards.join(' ')} - #{player.influence > 0 ? "Coins: #{player.coins}" : 'ELIMINATED'}#{token_str}" end #-------------------------------------------------------------------------------- # Settings #-------------------------------------------------------------------------------- def list_possible_roles(m) m.reply(::RebellionG54::Role::ALL.keys.map(&:to_s)) end def get_settings(m, channel_name = nil) game = self.game_of(m, channel_name, ['see settings', '!settings']) return unless game m.reply("Game #{game.id} - Synchronous challenges: #{game.synchronous_challenges}") end def set_settings(m, channel_name = nil, spec = '') game = self.game_of(m, channel_name, ['change settings', '!settings']) return unless game && !game.started? unknown = [] spec.split.each { |s| if s[0] == '+' desire = true elsif s[0] == '-' desire = false else unknown << s end case s[1..-1] when 'sync' game.synchronous_challenges = desire else unknown << s[1..-1] end } m.reply("These settings are unknown: #{unknown}") unless unknown.empty? m.reply("Game #{game.id} - Synchronous challenges: #{game.synchronous_challenges}") end def get_roles(m, channel_name = nil) game = self.game_of(m, channel_name, ['see roles', '!roles']) return unless game m.reply("Game #{game.id} #{game.started? ? '' : "proposed #{game.roles.size} "}roles: #{game.roles}") end class Chooser attr_reader :roles def initialize @roles = [] @advanced_only = false @basic_only = false end def advanced_only! @basic_only = false @advanced_only = true end def basic_only! @basic_only = true @advanced_only = false end def pick(desired_group) matching_chars = ::RebellionG54::Role::ALL.to_a.reject { |role, _| @roles.include?(role) } matching_chars.select! { |_, (group, _)| group == desired_group } if desired_group != :all matching_chars.select! { |_, (_, advanced)| advanced } if @advanced_only matching_chars.select! { |_, (_, advanced)| !advanced } if @basic_only @roles << matching_chars.map { |role, _| role }.sample unless matching_chars.empty? @advanced_only = false @basic_only = false end end def random_roles(m, channel_name = nil, spec = '') game = self.game_of(m, channel_name, ['change roles', '!roles']) return unless game && !game.started? if !spec || spec.strip.empty? m.reply('C = communications, $ = finance, F = force, S = special interests, A = all. Prepend + for only advanced, - for only basic.') m.reply('Perhaps -C-$-F-S-S or C$FSS or +C+$+F+S+S are good choices, but the sky is the limit...') return end chooser = Chooser.new spec.each_char { |c| case c.downcase when '+'; chooser.advanced_only! when '-'; chooser.basic_only! when 'c'; chooser.pick(:communications) when '$'; chooser.pick(:finance) when 'f'; chooser.pick(:force) when 's'; chooser.pick(:special_interests) when 'a'; chooser.pick(:all) end } game.roles = chooser.roles m.reply("Game #{game.id} now has #{game.roles.size} roles: #{game.roles}") end def set_roles(m, channel_name = nil, spec = '') game = self.game_of(m, channel_name, ['change roles', '!roles']) return unless game && !game.started? return if !spec || spec.strip.empty? roles = game.roles unknown = [] spec.split.each { |s| if s[0] == '+' rest = s[1..-1].downcase matching_role = ::RebellionG54::Role::ALL.keys.find { |role| role.to_s == rest } if matching_role roles << matching_role else unknown << rest end elsif s[0] == '-' rest = s[1..-1].downcase roles.reject! { |role| role.to_s == rest } end } m.reply("These roles are unknown: #{unknown}") unless unknown.empty? game.roles = roles.uniq m.reply("Game #{game.id} now has #{game.roles.size} roles: #{game.roles}") end #-------------------------------------------------------------------------------- # General #-------------------------------------------------------------------------------- def help(m, page = '') page ||= '' case page.strip.downcase when '2' m.reply('Roles: roles (view current), roles list (list all supported), roles random, roles +add -remove') m.reply("Game commands: table (everyone's cards and coins), status (whose turn is it?)") m.reply('Game commands: me (your characters), choices (your current choices)') when '3' m.reply('One challenger at a time: settings +sync. Everyone challenges at once: settings -sync') m.reply('Getting people to play: invite, subscribe, unsubscribe') m.reply('To get PRIVMSG: notice off. To get NOTICE: notice on') else m.reply("General help: All commands can be issued by '!command' or '#{m.bot.nick}: command' or PMing 'command'") m.reply('General commands: join, leave, start, who') m.reply('Game-related commands: help 2. Preferences: help 3') end end def rules(m) m.reply('https://www.boardgamegeek.com/thread/1369434 and https://boardgamegeek.com/filepage/107678') end end; end; end Split args and splat them into take_choice require 'cinch' require 'cinch/plugins/game_bot' require 'rebellion_g54/game' require 'rebellion_g54/role' module Cinch; module Plugins; class RebellionG54 < GameBot include Cinch::Plugin xmatch(/choices/i, method: :choices, group: :rebellion_g54) xmatch(/me\s*$/i, method: :whoami, group: :rebellion_g54) xmatch(/whoami/i, method: :whoami, group: :rebellion_g54) xmatch(/table(?:\s+(##?\w+))?/i, method: :table, group: :rebellion_g54) xmatch(/status/i, method: :status, group: :rebellion_g54) xmatch(/help(?: (.+))?/i, method: :help, group: :rebellion_g54) xmatch(/rules/i, method: :rules, group: :rebellion_g54) xmatch(/settings(?:\s+(##?\w+))?$/i, method: :get_settings, group: :rebellion_g54) xmatch(/settings(?:\s+(##?\w+))? (.+)$/i, method: :set_settings, group: :rebellion_g54) xmatch(/roles\s+list/i, method: :list_possible_roles, group: :rebellion_g54) xmatch(/roles(?:\s+(##?\w+))?$/i, method: :get_roles, group: :rebellion_g54) xmatch(/roles(?:\s+(##?\w+))?\s+random(?:\s+(.+))?/i, method: :random_roles, group: :rebellion_g54) xmatch(/roles(?:\s+(##?\w+))? (.+)$/i, method: :set_roles, group: :rebellion_g54) xmatch(/peek(?:\s+(##?\w+))?/i, method: :peek, group: :rebellion_g54) xmatch(/(\S+)(?:\s+(.*))?/, method: :rebellion_g54, group: :rebellion_g54) common_commands class ChannelOutputter def initialize(bot, game, c) @bot = bot @game = game @chan = c end def player_died(user) @bot.player_died(user, @chan) end def new_cards(user) @bot.tell_cards(@game, user: user) end def puts(msg) @chan.send(msg) end end #-------------------------------------------------------------------------------- # Implementing classes should override these #-------------------------------------------------------------------------------- def game_class ::RebellionG54::Game end def do_start_game(m, game, options) success, error = game.start_game unless success m.reply(error, true) return end Channel(game.channel_name).send("Welcome to game #{game.id}, with roles #{game.roles}") order = game.users.map { |u| dehighlight_nick(u.nick) }.join(' ') Channel(game.channel_name).send("Player order is #{order}") # Tell everyone of their initial stuff game.each_player.each { |player| tell_cards(game, player: player, game_start: true) } game.output_streams << ChannelOutputter.new(self, game, Channel(game.channel_name)) announce_decision(game) end def do_reset_game(game) chan = Channel(game.channel_name) info = table_info(game, show_secrets: true) chan.send(info) end def do_replace_user(game, replaced_user, replacing_user) tell_cards(game, replacing_user) if game.started? end def bg3po_invite_command(channel_name) # Nah, I don't want to do bg3po end #-------------------------------------------------------------------------------- # Other player management #-------------------------------------------------------------------------------- def player_died(user, channel) # Can't use remove_user_from_game because remove would throw an exception. # Instead, just do the same thing it does... channel.devoice(user) # I'm astounded that I can access my parent's @variable @user_games.delete(user) end def tell_cards(game, user: nil, player: nil, game_start: false) player ||= game.find_player(user) user ||= player.user turn = game_start ? 'starting hand' : "Turn #{game.turn_number}" user.send("Game #{game.id} #{turn}: #{player_info(player, show_secrets: true)}") end #-------------------------------------------------------------------------------- # Game #-------------------------------------------------------------------------------- def announce_decision(game) Channel(game.channel_name).send(decision_info(game, show_choices: true)) game.choice_names.keys.each { |p| explanations = format_choice_explanations(game, p) User(p).send(explanations.map { |e| "[#{e}]" }.join(' ')) } end def rebellion_g54(m, command, args = '') game = self.game_of(m) return unless game && game.started? && game.has_player?(m.user) args = args ? args.split : [] success, error = game.take_choice(m.user, command, *args) if success if game.winner chan = Channel(game.channel_name) chan.send("Congratulations! #{game.winner.name} is the winner!!!") info = table_info(game, show_secrets: true) chan.send(info) self.start_new_game(game) else announce_decision(game) end else m.user.send(error) end end def choices(m) game = self.game_of(m) return unless game && game.started? && game.has_player?(m.user) explanations = format_choice_explanations(game, m.user) if explanations.empty? m.user.send("You don't need to make any choices right now.") else m.user.send(explanations.map { |e| "[#{e}]" }.join(' ')) end end def whoami(m) game = self.game_of(m) return unless game && game.started? && game.has_player?(m.user) tell_cards(game, user: m.user) end def table(m, channel_name = nil) game = self.game_of(m, channel_name, ['see a game', '!table']) return unless game && game.started? info = table_info(game) m.reply(info) end def status(m) game = self.game_of(m) return unless game if !game.started? if game.size == 0 m.reply('No game in progress. Join and start one!') else m.reply("A game is forming. #{game.size} players have joined: #{game.users.map(&:name).join(', ')}") end return end m.reply(decision_info(game)) end def peek(m, channel_name = nil) return unless self.is_mod?(m.user) game = self.game_of(m, channel_name, ['peek', '!peek']) return unless game && game.started? if game.has_player?(m.user) m.user.send('Cheater!!!') return end info = table_info(game, show_secrets: true) m.user.send(info) end #-------------------------------------------------------------------------------- # Help for player/table info #-------------------------------------------------------------------------------- def format_choice_explanations(game, user) explanations = game.choice_explanations(user) explanations.to_a.map { |label, info| info[:available] ? "#{label}: #{info[:description]}": "#{label} (unavailable): #{info[:why_unavailable]}" } end def decision_info(game, show_choices: false) desc = game.decision_description players = game.choice_names.keys choices = show_choices ? " to pick between #{game.choice_names.values.flatten.uniq.join(', ')}" : '' "Game #{game.id} Turn #{game.turn_number} - #{desc} - Waiting on #{players.join(', ')}#{choices}" end def table_info(game, show_secrets: false) role_tokens = game.role_tokens roles = game.roles.map { |r| tokens = role_tokens[r] || [] tokens_str = (tokens.empty? ? '' : " (#{tokens.map { |t| t.to_s.capitalize }.join(', ')})") "#{::RebellionG54::Role.to_s(r)}#{tokens_str}" }.join(', ') player_tokens = game.player_tokens "Game #{game.id} Turn #{game.turn_number} - #{roles}\n" + game.each_player.map { |player| "#{player.user.name}: #{player_info(player, show_secrets: show_secrets, tokens: player_tokens[player.user])}" }.concat(game.each_dead_player.map { |player| "#{player.user.name}: #{player_info(player, show_secrets: show_secrets)}" }).join("\n") end def player_info(player, show_secrets: false, tokens: []) cards = [] cards.concat(player.each_live_card.map { |c| "(#{show_secrets ? ::RebellionG54::Role.to_s(c.role) : '########'})" }) cards.concat(player.each_side_card.map { |c, r| "<#{show_secrets ? ::RebellionG54::Role.to_s(c.role) : "??#{::RebellionG54::Role.to_s(r)}??"}>" }) cards.concat(player.each_revealed_card.map { |c| "[#{::RebellionG54::Role.to_s(c.role)}]" }) token_str = tokens.empty? ? '' : " - #{tokens.map { |t| t.to_s.capitalize }.join(', ')}" "#{cards.join(' ')} - #{player.influence > 0 ? "Coins: #{player.coins}" : 'ELIMINATED'}#{token_str}" end #-------------------------------------------------------------------------------- # Settings #-------------------------------------------------------------------------------- def list_possible_roles(m) m.reply(::RebellionG54::Role::ALL.keys.map(&:to_s)) end def get_settings(m, channel_name = nil) game = self.game_of(m, channel_name, ['see settings', '!settings']) return unless game m.reply("Game #{game.id} - Synchronous challenges: #{game.synchronous_challenges}") end def set_settings(m, channel_name = nil, spec = '') game = self.game_of(m, channel_name, ['change settings', '!settings']) return unless game && !game.started? unknown = [] spec.split.each { |s| if s[0] == '+' desire = true elsif s[0] == '-' desire = false else unknown << s end case s[1..-1] when 'sync' game.synchronous_challenges = desire else unknown << s[1..-1] end } m.reply("These settings are unknown: #{unknown}") unless unknown.empty? m.reply("Game #{game.id} - Synchronous challenges: #{game.synchronous_challenges}") end def get_roles(m, channel_name = nil) game = self.game_of(m, channel_name, ['see roles', '!roles']) return unless game m.reply("Game #{game.id} #{game.started? ? '' : "proposed #{game.roles.size} "}roles: #{game.roles}") end class Chooser attr_reader :roles def initialize @roles = [] @advanced_only = false @basic_only = false end def advanced_only! @basic_only = false @advanced_only = true end def basic_only! @basic_only = true @advanced_only = false end def pick(desired_group) matching_chars = ::RebellionG54::Role::ALL.to_a.reject { |role, _| @roles.include?(role) } matching_chars.select! { |_, (group, _)| group == desired_group } if desired_group != :all matching_chars.select! { |_, (_, advanced)| advanced } if @advanced_only matching_chars.select! { |_, (_, advanced)| !advanced } if @basic_only @roles << matching_chars.map { |role, _| role }.sample unless matching_chars.empty? @advanced_only = false @basic_only = false end end def random_roles(m, channel_name = nil, spec = '') game = self.game_of(m, channel_name, ['change roles', '!roles']) return unless game && !game.started? if !spec || spec.strip.empty? m.reply('C = communications, $ = finance, F = force, S = special interests, A = all. Prepend + for only advanced, - for only basic.') m.reply('Perhaps -C-$-F-S-S or C$FSS or +C+$+F+S+S are good choices, but the sky is the limit...') return end chooser = Chooser.new spec.each_char { |c| case c.downcase when '+'; chooser.advanced_only! when '-'; chooser.basic_only! when 'c'; chooser.pick(:communications) when '$'; chooser.pick(:finance) when 'f'; chooser.pick(:force) when 's'; chooser.pick(:special_interests) when 'a'; chooser.pick(:all) end } game.roles = chooser.roles m.reply("Game #{game.id} now has #{game.roles.size} roles: #{game.roles}") end def set_roles(m, channel_name = nil, spec = '') game = self.game_of(m, channel_name, ['change roles', '!roles']) return unless game && !game.started? return if !spec || spec.strip.empty? roles = game.roles unknown = [] spec.split.each { |s| if s[0] == '+' rest = s[1..-1].downcase matching_role = ::RebellionG54::Role::ALL.keys.find { |role| role.to_s == rest } if matching_role roles << matching_role else unknown << rest end elsif s[0] == '-' rest = s[1..-1].downcase roles.reject! { |role| role.to_s == rest } end } m.reply("These roles are unknown: #{unknown}") unless unknown.empty? game.roles = roles.uniq m.reply("Game #{game.id} now has #{game.roles.size} roles: #{game.roles}") end #-------------------------------------------------------------------------------- # General #-------------------------------------------------------------------------------- def help(m, page = '') page ||= '' case page.strip.downcase when '2' m.reply('Roles: roles (view current), roles list (list all supported), roles random, roles +add -remove') m.reply("Game commands: table (everyone's cards and coins), status (whose turn is it?)") m.reply('Game commands: me (your characters), choices (your current choices)') when '3' m.reply('One challenger at a time: settings +sync. Everyone challenges at once: settings -sync') m.reply('Getting people to play: invite, subscribe, unsubscribe') m.reply('To get PRIVMSG: notice off. To get NOTICE: notice on') else m.reply("General help: All commands can be issued by '!command' or '#{m.bot.nick}: command' or PMing 'command'") m.reply('General commands: join, leave, start, who') m.reply('Game-related commands: help 2. Preferences: help 3') end end def rules(m) m.reply('https://www.boardgamegeek.com/thread/1369434 and https://boardgamegeek.com/filepage/107678') end end; end; end
module CloudfilesCli class Transactions attr_reader :config def initialize(config) @config = config end def connection @cf ||= Fog::Storage.new(config.hash.merge(:provider => 'Rackspace')) end def upload(container_name, localfile, remotefile) container = connection.directories.get(container_name) object = container.files.create( :key => remotefile, :body => File.open(localfile) ) end def download(container_name, remotefile, localfile) container = connection.directories.get(container_name) object = container.files.get(remotefile) IO.binwrite(localfile, object.body) end end end Better error message when file is missing module CloudfilesCli class Transactions attr_reader :config def initialize(config) @config = config end def connection @cf ||= Fog::Storage.new(config.hash.merge(:provider => 'Rackspace')) end def upload(container_name, localfile, remotefile) container = connection.directories.get(container_name) object = container.files.create( :key => remotefile, :body => File.open(localfile) ) end def download(container_name, remotefile, localfile) container = connection.directories.get(container_name) object = container.files.get(remotefile) if object.nil? STDERR.puts "File #{remotefile} not found on cloudfiles" exit 1 else IO.binwrite(localfile, object.body) end end end end
require 'fourflusher' CONFIGURATION = "Release" PLATFORMS = { 'iphonesimulator' => 'iOS', 'appletvsimulator' => 'tvOS', 'watchsimulator' => 'watchOS' } def build_for_iosish_platform(sandbox, build_dir, target, device, simulator) deployment_target = target.platform_deployment_target target_label = target.cocoapods_target_label xcodebuild(sandbox, target_label, device, deployment_target) xcodebuild(sandbox, target_label, simulator, deployment_target) spec_names = target.specs.map { |spec| [spec.root.name, spec.root.module_name] }.uniq spec_names.each do |root_name, module_name| executable_path = "#{build_dir}/#{root_name}" device_lib = "#{build_dir}/#{CONFIGURATION}-#{device}/#{root_name}/#{module_name}.framework/#{module_name}" device_framework_lib = File.dirname(device_lib) simulator_lib = "#{build_dir}/#{CONFIGURATION}-#{simulator}/#{root_name}/#{module_name}.framework/#{module_name}" next unless File.file?(device_lib) && File.file?(simulator_lib) lipo_log = `lipo -create -output #{executable_path} #{device_lib} #{simulator_lib}` puts lipo_log unless File.exist?(executable_path) FileUtils.mv executable_path, device_lib FileUtils.mv device_framework_lib, build_dir FileUtils.rm simulator_lib if File.file?(simulator_lib) FileUtils.rm device_lib if File.file?(device_lib) end end def xcodebuild(sandbox, target, sdk='macosx', deployment_target=nil) args = %W(-project #{sandbox.project_path.realdirpath} -scheme #{target} -configuration #{CONFIGURATION} -sdk #{sdk}) platform = PLATFORMS[sdk] args += Fourflusher::SimControl.new.destination(:oldest, platform, deployment_target) unless platform.nil? Pod::Executable.execute_command 'xcodebuild', args, true end Pod::HooksManager.register('cocoapods-rome', :post_install) do |installer_context| sandbox_root = Pathname(installer_context.sandbox_root) sandbox = Pod::Sandbox.new(sandbox_root) build_dir = sandbox_root.parent + 'build' destination = sandbox_root.parent + 'Rome' Pod::UI.puts 'Building frameworks' build_dir.rmtree if build_dir.directory? targets = installer_context.umbrella_targets.select { |t| t.specs.any? } targets.each do |target| case target.platform_name when :ios then build_for_iosish_platform(sandbox, build_dir, target, 'iphoneos', 'iphonesimulator') when :osx then xcodebuild(sandbox, target.cocoapods_target_label) when :tvos then build_for_iosish_platform(sandbox, build_dir, target, 'appletvos', 'appletvsimulator') when :watchos then build_for_iosish_platform(sandbox, build_dir, target, 'watchos', 'watchsimulator') else raise "Unknown platform '#{target.platform_name}'" end end raise Pod::Informative, 'The build directory was not found in the expected location.' unless build_dir.directory? # Make sure the device target overwrites anything in the simulator build, otherwise iTunesConnect # can get upset about Info.plist containing references to the simulator SDK frameworks = Pathname.glob("build/*/*/*.framework").reject { |f| f.to_s =~ /Pods.*\.framework/ } frameworks += Pathname.glob("build/*.framework").reject { |f| f.to_s =~ /Pods.*\.framework/ } Pod::UI.puts "Built #{frameworks.count} #{'frameworks'.pluralize(frameworks.count)}" destination.rmtree if destination.directory? installer_context.umbrella_targets.each do |umbrella| umbrella.specs.each do |spec| consumer = spec.consumer(umbrella.platform_name) file_accessor = Pod::Sandbox::FileAccessor.new(sandbox.pod_dir(spec.root.name), consumer) frameworks += file_accessor.vendored_libraries frameworks += file_accessor.vendored_frameworks end end frameworks.uniq! Pod::UI.puts "Copying #{frameworks.count} #{'frameworks'.pluralize(frameworks.count)} " \ "to `#{destination.relative_path_from Pathname.pwd}`" frameworks.each do |framework| FileUtils.mkdir_p destination FileUtils.cp_r framework, destination, :remove_destination => true end build_dir.rmtree if build_dir.directory? end Add pre compile handler require 'fourflusher' CONFIGURATION = "Release" PLATFORMS = { 'iphonesimulator' => 'iOS', 'appletvsimulator' => 'tvOS', 'watchsimulator' => 'watchOS' } def build_for_iosish_platform(sandbox, build_dir, target, device, simulator) deployment_target = target.platform_deployment_target target_label = target.cocoapods_target_label xcodebuild(sandbox, target_label, device, deployment_target) xcodebuild(sandbox, target_label, simulator, deployment_target) spec_names = target.specs.map { |spec| [spec.root.name, spec.root.module_name] }.uniq spec_names.each do |root_name, module_name| executable_path = "#{build_dir}/#{root_name}" device_lib = "#{build_dir}/#{CONFIGURATION}-#{device}/#{root_name}/#{module_name}.framework/#{module_name}" device_framework_lib = File.dirname(device_lib) simulator_lib = "#{build_dir}/#{CONFIGURATION}-#{simulator}/#{root_name}/#{module_name}.framework/#{module_name}" next unless File.file?(device_lib) && File.file?(simulator_lib) lipo_log = `lipo -create -output #{executable_path} #{device_lib} #{simulator_lib}` puts lipo_log unless File.exist?(executable_path) FileUtils.mv executable_path, device_lib FileUtils.mv device_framework_lib, build_dir FileUtils.rm simulator_lib if File.file?(simulator_lib) FileUtils.rm device_lib if File.file?(device_lib) end end def xcodebuild(sandbox, target, sdk='macosx', deployment_target=nil) args = %W(-project #{sandbox.project_path.realdirpath} -scheme #{target} -configuration #{CONFIGURATION} -sdk #{sdk}) platform = PLATFORMS[sdk] args += Fourflusher::SimControl.new.destination(:oldest, platform, deployment_target) unless platform.nil? Pod::Executable.execute_command 'xcodebuild', args, true end Pod::HooksManager.register('cocoapods-rome', :post_install) do |installer_context, user_options| if user_options["pre_compile"] user_options["pre_compile"].call(installer_context) end sandbox_root = Pathname(installer_context.sandbox_root) sandbox = Pod::Sandbox.new(sandbox_root) build_dir = sandbox_root.parent + 'build' destination = sandbox_root.parent + 'Rome' Pod::UI.puts 'Building frameworks' build_dir.rmtree if build_dir.directory? targets = installer_context.umbrella_targets.select { |t| t.specs.any? } targets.each do |target| case target.platform_name when :ios then build_for_iosish_platform(sandbox, build_dir, target, 'iphoneos', 'iphonesimulator') when :osx then xcodebuild(sandbox, target.cocoapods_target_label) when :tvos then build_for_iosish_platform(sandbox, build_dir, target, 'appletvos', 'appletvsimulator') when :watchos then build_for_iosish_platform(sandbox, build_dir, target, 'watchos', 'watchsimulator') else raise "Unknown platform '#{target.platform_name}'" end end raise Pod::Informative, 'The build directory was not found in the expected location.' unless build_dir.directory? # Make sure the device target overwrites anything in the simulator build, otherwise iTunesConnect # can get upset about Info.plist containing references to the simulator SDK frameworks = Pathname.glob("build/*/*/*.framework").reject { |f| f.to_s =~ /Pods.*\.framework/ } frameworks += Pathname.glob("build/*.framework").reject { |f| f.to_s =~ /Pods.*\.framework/ } Pod::UI.puts "Built #{frameworks.count} #{'frameworks'.pluralize(frameworks.count)}" destination.rmtree if destination.directory? installer_context.umbrella_targets.each do |umbrella| umbrella.specs.each do |spec| consumer = spec.consumer(umbrella.platform_name) file_accessor = Pod::Sandbox::FileAccessor.new(sandbox.pod_dir(spec.root.name), consumer) frameworks += file_accessor.vendored_libraries frameworks += file_accessor.vendored_frameworks end end frameworks.uniq! Pod::UI.puts "Copying #{frameworks.count} #{'frameworks'.pluralize(frameworks.count)} " \ "to `#{destination.relative_path_from Pathname.pwd}`" frameworks.each do |framework| FileUtils.mkdir_p destination FileUtils.cp_r framework, destination, :remove_destination => true end build_dir.rmtree if build_dir.directory? end
#-- ############################################################################### # # # jekyll-rendering -- Jekyll plugin to provide alternative rendering engines # # # # Copyright (C) 2010 University of Cologne, # # Albertus-Magnus-Platz, # # 50923 Cologne, Germany # # # # Authors: # # Jens Wille <jens.wille@uni-koeln.de> # # # # jekyll-rendering is free software; you can redistribute it and/or modify it # # under the terms of the GNU General Public License as published by the Free # # Software Foundation; either version 3 of the License, or (at your option) # # any later version. # # # # jekyll-rendering 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 General Public License for # # more details. # # # # You should have received a copy of the GNU General Public License along # # with jekyll-rendering. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### #++ require 'erb' require 'ostruct' module Jekyll module Rendering end module Convertible alias_method :_rendering_original_do_layout, :do_layout # Overwrites the original method to use the configured rendering engine. def do_layout(payload, layouts) info = { :filters => [Jekyll::Filters], :registers => { :site => site } } payload['pygments_prefix'] = converter.pygments_prefix payload['pygments_suffix'] = converter.pygments_suffix # render and transform content (this becomes the final content of the object) self.content = engine.render(payload, content, info) transform # output keeps track of what will finally be written self.output = content # recursively render layouts layout = self while layout = layouts[layout.data['layout']] payload = payload.deep_merge('content' => output, 'page' => layout.data) self.output = engine.render(payload, content, info, layout.content) end end # call-seq: # engine => aClass # # Returns the Engine class according to the configuration setting for # +engine+ (see subclasses of Engine::Base). Defaults to Engine::Liquid. def engine @engine ||= Engine[site.config['engine'] ||= 'liquid'] end end module Engine # call-seq: # Engine[engine] => aClass # # Returns the subclass whose name corresponds to +engine+. def self.[](engine) const_get(engine.capitalize) end class Base # call-seq: # Engine::Base.render(*args) # # Renders the output. Defers to engine's render method. def self.render(payload, content, info, layout = nil) new(payload, content, info).render(layout || content) end attr_reader :payload, :info attr_accessor :content def initialize(payload, content = nil, info = {}) @payload, @content, @info = payload, content, info end # call-seq: # render # # Renders the output. Must be implemented by subclass. def render raise NotImplementedError end end class Liquid < Base # call-seq: # engine.render # engine.render(content) # # Renders the +content+ using ::Liquid::Template::parse and then # calling ::Liquid::Template#render with +payload+ and +info+. def render(content = content) ::Liquid::Template.parse(content).render(payload, info) end end class Erb < Base attr_reader :site, :page def initialize(*args) super [Helpers, *info[:filters]].each { |mod| extend mod } %w[site page paginator].each { |key| value = payload[key] or next instance_variable_set("@#{key}", OpenStruct.new(value)) } end # call-seq: # engine.render => aString # engine.render(content) => aString # engine.render(content, binding) => aString # # Renders the +content+ as ERB template. Uses optional +binding+ # if provided. def render(content = content, binding = binding) ::ERB.new(content).result(binding) end module Helpers # call-seq: # include_file file => aString # include_file file, binding => aString # # Includes file +file+ from <tt>_includes</tt> directory rendered # as ERB template. Uses optional +binding+ if provided. def include_file(file, binding = binding) Dir.chdir(File.join(site.source, '_includes')) { @choices ||= Dir['**/*'].reject { |x| File.symlink?(x) } if @choices.include?(file = file.strip) render(File.read(file), binding) else "Included file '#{file}' not found in _includes directory" end } end # call-seq: # highlight text => aString # highlight text, lang => aString # # Highlights +text+ according to +lang+ (defaults to Ruby). def highlight(text, lang = :ruby) if site.pygments render_pygments(text, lang) else render_codehighlighter(text, lang) end end protected def render_pygments(text, lang) output = add_code_tags(Albino.new(text, lang).to_s, lang) "#{payload['pygments_prefix']}#{output}#{payload['pygments_suffix']}" end def render_codehighlighter(text, lang) #The div is required because RDiscount blows ass <<-HTML <div> <pre> <code class="#{lang}">#{h(text).strip}</code> </pre> </div> HTML end def add_code_tags(code, lang) # Add nested <code> tags to code blocks code.sub(%r{<pre>}, %Q{<pre><code class="#{lang}">}). sub(%r{</pre>}, %q{</code></pre>}) end end end end class Page def index? basename == @site.config['paginate_file'].sub('.html', '') end end # Provide an engine-agnostic name for the hash representation. [Post, Page, Pager].each { |klass| klass.send(:alias_method, :to_hash, :to_liquid) } end Revert "[FIX] Enable custom permalinks with an alternative paginate_file." Wrong Repo O_o This reverts commit 5f68efad3de0b1f541b32c9b6135cfff385609c2. #-- ############################################################################### # # # jekyll-rendering -- Jekyll plugin to provide alternative rendering engines # # # # Copyright (C) 2010 University of Cologne, # # Albertus-Magnus-Platz, # # 50923 Cologne, Germany # # # # Authors: # # Jens Wille <jens.wille@uni-koeln.de> # # # # jekyll-rendering is free software; you can redistribute it and/or modify it # # under the terms of the GNU General Public License as published by the Free # # Software Foundation; either version 3 of the License, or (at your option) # # any later version. # # # # jekyll-rendering 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 General Public License for # # more details. # # # # You should have received a copy of the GNU General Public License along # # with jekyll-rendering. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### #++ require 'erb' require 'ostruct' module Jekyll module Rendering end module Convertible alias_method :_rendering_original_do_layout, :do_layout # Overwrites the original method to use the configured rendering engine. def do_layout(payload, layouts) info = { :filters => [Jekyll::Filters], :registers => { :site => site } } payload['pygments_prefix'] = converter.pygments_prefix payload['pygments_suffix'] = converter.pygments_suffix # render and transform content (this becomes the final content of the object) self.content = engine.render(payload, content, info) transform # output keeps track of what will finally be written self.output = content # recursively render layouts layout = self while layout = layouts[layout.data['layout']] payload = payload.deep_merge('content' => output, 'page' => layout.data) self.output = engine.render(payload, content, info, layout.content) end end # call-seq: # engine => aClass # # Returns the Engine class according to the configuration setting for # +engine+ (see subclasses of Engine::Base). Defaults to Engine::Liquid. def engine @engine ||= Engine[site.config['engine'] ||= 'liquid'] end end module Engine # call-seq: # Engine[engine] => aClass # # Returns the subclass whose name corresponds to +engine+. def self.[](engine) const_get(engine.capitalize) end class Base # call-seq: # Engine::Base.render(*args) # # Renders the output. Defers to engine's render method. def self.render(payload, content, info, layout = nil) new(payload, content, info).render(layout || content) end attr_reader :payload, :info attr_accessor :content def initialize(payload, content = nil, info = {}) @payload, @content, @info = payload, content, info end # call-seq: # render # # Renders the output. Must be implemented by subclass. def render raise NotImplementedError end end class Liquid < Base # call-seq: # engine.render # engine.render(content) # # Renders the +content+ using ::Liquid::Template::parse and then # calling ::Liquid::Template#render with +payload+ and +info+. def render(content = content) ::Liquid::Template.parse(content).render(payload, info) end end class Erb < Base attr_reader :site, :page def initialize(*args) super [Helpers, *info[:filters]].each { |mod| extend mod } %w[site page paginator].each { |key| value = payload[key] or next instance_variable_set("@#{key}", OpenStruct.new(value)) } end # call-seq: # engine.render => aString # engine.render(content) => aString # engine.render(content, binding) => aString # # Renders the +content+ as ERB template. Uses optional +binding+ # if provided. def render(content = content, binding = binding) ::ERB.new(content).result(binding) end module Helpers # call-seq: # include_file file => aString # include_file file, binding => aString # # Includes file +file+ from <tt>_includes</tt> directory rendered # as ERB template. Uses optional +binding+ if provided. def include_file(file, binding = binding) Dir.chdir(File.join(site.source, '_includes')) { @choices ||= Dir['**/*'].reject { |x| File.symlink?(x) } if @choices.include?(file = file.strip) render(File.read(file), binding) else "Included file '#{file}' not found in _includes directory" end } end # call-seq: # highlight text => aString # highlight text, lang => aString # # Highlights +text+ according to +lang+ (defaults to Ruby). def highlight(text, lang = :ruby) if site.pygments render_pygments(text, lang) else render_codehighlighter(text, lang) end end protected def render_pygments(text, lang) output = add_code_tags(Albino.new(text, lang).to_s, lang) "#{payload['pygments_prefix']}#{output}#{payload['pygments_suffix']}" end def render_codehighlighter(text, lang) #The div is required because RDiscount blows ass <<-HTML <div> <pre> <code class="#{lang}">#{h(text).strip}</code> </pre> </div> HTML end def add_code_tags(code, lang) # Add nested <code> tags to code blocks code.sub(%r{<pre>}, %Q{<pre><code class="#{lang}">}). sub(%r{</pre>}, %q{</code></pre>}) end end end end # Provide an engine-agnostic name for the hash representation. [Post, Page, Pager].each { |klass| klass.send(:alias_method, :to_hash, :to_liquid) } end
# A comment class CodeRunner # declare the constant end # = CodeRunner Overview # # CodeRunner is a class designed to make the running an analysis of large simulations and easy task. An instance of this class is instantiated for a given root folder. The runner, as it is known, knows about every simulation in this folder, each of which has a unique id and a unique subfolder. # # The heart of the runner is the variable run_list. This is a hash of IDs and runs. A run is an instance of a class which inherits from CodeRunner::Run, and which is customised to be able to handle the input variables, and the output data, from the given simulation code. This is achieved by a module which contains a child class of CodeRunner::Run, which is provided independently of CodeRunner. # # CodeRunner has methods to sort these runs, filter them according to quite complex conditions, print out the status of these runs, submit new runs, plot graphs using data from these runs, cancel running jobs, delete unwanted runs, and so on. # # = CodeRunner Interfaces # # CodeRunner has two different interfaces: # # 1. Instance methods # 2. Class methods # # == Instance Methods # # The instance methods provide a classic Ruby scripting interface. A runner is instantiated from the CodeRunner class, and passed a root folder, and possibly some default options. Instance methods can then be called individually. This is what should be used for complex and non-standard tasks. # # == Class methods # # The class methods are what are used by the command line interface. They define a standard set of tasks, each of which can be customised by a set of options known as command options, or <i>copts</i> for short. # # There is a one-to-one correspondence between the long form of the commandline commands, and the class methods that handle those commands, and between the command line flags, and the options that are passed to the class methods. So for example: # # $ coderunner submit -p '{time: 23.4, resolution: 256}' -n 32x4 -W 600 # # Becomes # # CodeRunner.submit(p: '{time: 23.4, resolution: 256}', n: "32x4", W: 600) # # remembering that braces are not needed around a hash if it is the final parameter. # # These methods are what should be used to automate a large number of standard tasks, which would be a pain to run from the command line. class CodeRunner class CRMild < StandardError # more of a dead end than an error. Should never be allowed to halt execution def initialize(mess="") mess += "\n\n#{self.class} created in directory #{Dir.pwd}" super(mess) end end class CRError < StandardError # usually can be handled def initialize(mess="") mess += "\n\n#{self.class} created in directory #{Dir.pwd}" super(mess) end end class CRFatal < StandardError # should never be rescued - must always terminate execution def initialize(mess="") mess += "\n\n#{self.class} created in directory #{Dir.pwd}" super(mess) end end # Parameters important to the submission of a run, which can be set by command line flags. The runner values provide the default values for the submit function, but can be overidden in that function. All the runner does with them is set them as properties of the run to be submitted. It is the run itself for which the options are relevant. SUBMIT_OPTIONS = [:nprocs, :wall_mins, :sys, :project, :comment, :executable] # A hash containing the defaults for most runner options. They are overridden by any options provided during initialisation. They are mostly set at the command line (in practice, the command line flags are read into the command options, which set these defaults in the function CodeRunner.process_command_options which calls CodeRunner.set_runner_defaults). However, if Code Runner is being scripted, these defaults must be set manually or else the options they specify must be provided when initialising a runner. DEFAULT_RUNNER_OPTIONS = ([:conditions, :code, :executable, :sort, :debug, :script_folder, :recalc_all, :multiple_processes, :heuristic_analysis, :test_submission, :reprocess_all, :use_large_cache, :use_large_cache_but_recheck_incomplete, :use_phantom, :no_run, :server, :version, :parameters] + SUBMIT_OPTIONS).inject({}){|hash, option| hash[option] = nil; hash} # Options that apply across the CodeRunner class CLASS_OPTIONS = [:multiple_processes].inject({}){|hash, option| class_accessor option set(option, nil) hash[option] = nil; hash } DEFAULT_RUNNER_OPTIONS.keys.each do |variable| #define accessors for class options and instance options # class_accessor(variable) attr_accessor variable # class_variable_set(variable, nil) end # def self.default_script_info # Hash.phoenix('.code_runner_script_defaults.rb') # # eval(File.read('.code_runner_script_defaults.rb')) # end # # def self.add_to_default_script_info(hash) # Hash.phoenix('.code_runner_script_defaults.rb') do |defaults| # hash.each{|key,value| defaults[key] = value} # end # end DEFAULT_RUNNER_OPTIONS[:use_phantom] = :real DEFAULT_RUNNER_OPTIONS[:script_folder] = SCRIPT_FOLDER #File.dirname(File.expand_path(__FILE__)) # These are properties of the run class that must be defined. For more details see CodeRunner::Run. NECESSARY_RUN_CLASS_PROPERTIES = { :code => [String], :variables => [Array], :naming_pars => [Array], :results => [Array], :run_info => [Array], :code_long => [String], :excluded_sub_folders => [Array], :modlet_required => [TrueClass, FalseClass], :uses_mpi => [TrueClass, FalseClass] } # These are methods that the run class must implement. They should be defined in a code module. NECESSARY_RUN_CODE_METHODS = [ :process_directory_code_specific, :print_out_line, :parameter_string, :generate_input_file, :parameter_transition, :executable_location, :executable_name ] # These are methods that the run class must implement. They should be defined in a system module. NECESSARY_RUN_SYSTEM_METHODS = [ :queue_status, :run_command, :execute, :error_file, :output_file, :cancel_job ] # These are the only permitted values for the run instance variable <tt>@status</tt>. PERMITTED_STATI = [:Unknown, :Complete, :Incomplete, :NotStarted, :Failed, :Queueing, :Running, :Held] include Log # Log.log_file = nil # Dir.pwd + "/.cr_logfile.txt" # puts Log.log_file, 'hello' Log.clean_up attr_accessor :run_list, :phantom_run_list, :combined_run_list, :ids, :phantom_ids, :combined_ids, :current_status, :run_class, :requests, :current_request, :root_folder, :print_out_size, :cache, :modlet, :code, :executable, :defaults_file attr_reader :max_id, :maxes, :cmaxes, :mins, :cmins, :start_id # Instantiate a new runner. The root folder contains a set of simulations, each of which has a unique ID. There is a one-to-one correspondence between a runner and a root folder: no two runners should ever be given the same root folder in the same script (there are safeguards to prevent this causing much trouble, but it should still be avoided on philosophical grounds), and no runner should be given a folder which has more than one set of simulations within it (as these simulations will contain duplicate IDs). # # # Options is a hash whose keys may be any of the keys of the constant <tt>DEFAULT_RUNNER_OPTIONS</tt>. I.e. to see what options can be passed: # # p CodeRunner::DEFAULT_RUNNER_OPTIONS.keys def initialize(root_folder, options={}) logf :initialize raise CRFatal.new("System not defined") unless SYS root_folder.sub!(/~/, ENV['HOME']) @root_folder = root_folder read_defaults options.each do |key,value| key = LONG_TO_SHORT.key(key) if LONG_TO_SHORT.key(key) set(key, value) if value end # ep options log 'modlet in initialize', @modlet @version= options[:version] # ep 'ex', @executable @run_class = setup_run_class(@code, modlet: @modlet, version: @version, executable: @executable) @cache = {} @n_checks = 0 @print_out_size = 0 @run_list = {}; @ids = [] set_max_id(0) @phantom_run_list = {}; @phantom_ids = [] @phantom_id = -1 @combined_run_list = {}; @combined_ids = [] @current_request = nil @requests = [] @pids= [] @maxes = {}; @mins = {} @cmaxes = {}; @cmins = {} end # Read the default values of runner options from the constant hash <tt>CodeRunner::DEFAULT_RUNNER_OPTIONS</tt>. This hash usually contains options set from the command line, but it can have its values edited manually in a script. # # Also calls read_folder_defaults. def read_defaults DEFAULT_RUNNER_OPTIONS.each{|key,value| set(key, value)} #ep DEFAULT_RUNNER_OPTIONS, @multiple_processes read_folder_defaults end # Increase the value of <tt>@max_id</tt> by 1. def increment_max_id @max_id +=1 end # Return an array of runs (run_list.values) def runs run_list.values end # Set the max_id. If the number given is lower than start_id, start_id is used. Use with extreme caution... if you set max_id to be lower than the highest run id, you may end up with duplicate ids. def set_max_id(number) # :doc: # ep 'MAXES', @max_id, number, @start_id, 'END' @max_id = @start_id ? [@start_id, number].max : number end private :set_max_id # The defaults that are saved in the root folder FOLDER_DEFAULTS = [:code, :modlet, :executable, :defaults_file, :project] # Read any default options contained in the file <tt>.code_runner_script_defaults.rb</tt> in the root folder. def read_folder_defaults # p @root_folder + '/.code_runner_script_defaults.rb' if ENV['CODE_RUNNER_READONLY_DEFAULTS'] hash = eval(File.read(@root_folder + '/.code_runner_script_defaults.rb')) FOLDER_DEFAULTS.each do |var| set(var, hash[var]) if hash[var] end else Hash.phoenix(@root_folder + '/.code_runner_script_defaults.rb') do |hash| # ep hash FOLDER_DEFAULTS.each do |var| # p send(var), hash[var] hash[var] = (send(var) or hash[var]) hash[:code_runner_version] ||= CodeRunner::CODE_RUNNER_VERSION.to_s set(var, hash[var]) end @start_id = hash[:start_id] if hash[:start_id] # ep "start_id: #@start_id" hash end end raise "No default information exists for this folder. If you are running CodeRunner from the commmand line please run again with the -C <code> and -X <executable> (and -m <modlet>, if required) flag (you only need to specify these flags once in each folder). Else, please specify :code and :executable (and :modlet if required) as options in CodeRunner.new(folder, options)" unless @code and @executable end # Here we redefine the inspect function p to raise an error if anything is written to standard out # while in server mode. This is because the server mode uses standard out to communicate # and writing to standard out can break it. All messages, debug information and so on, should always # be written to standard error. def p(*args) if @server raise "Writing to stdout in server mode will break things!" else super(*args) end end # Here we redefine the function puts to raise an error if anything is written to standard out # while in server mode. This is because the server mode uses standard out to communicate # and writing to standard out can break it. All messages, debug information and so on, should always # be written to standard error. def puts(*args) if @server raise "Writing to stdout in server mode will break things!" else super(*args) end end # Here we redefine the function print to raise an error if anything is written to standard out # while in server mode. This is because the server mode uses standard out to communicate # and writing to standard out can break it. All messages, debug information and so on, should always # be written to standard error. def print(*args) if @server raise "Writing to stdout in server mode will break things!" else super(*args) end end def self.server_dump(obj) "code_runner_server_dump_start_E#{Marshal.dump(obj)}code_runner_server_dump_end_E" end def server_dump(obj) self.class.server_dump(obj) end def set_start_id(id) raise "start_id #{id} lower than max_id #@max_id" if @max_id and id < @max_id Hash.phoenix(@root_folder + '/.code_runner_script_defaults.rb') do |hash| @start_id = hash[:start_id] = id hash end end # See CodeRunner.get_run_class_name def get_run_class_name(code, modlet) self.class.get_run_class_name(code, modlet) end # See CodeRunner.setup_run_class def setup_run_class(code, options) options[:runner] ||= self self.class.setup_run_class(code, options) end def self.old_get_run_class_name(code, modlet) # :nodoc: return modlet ? "#{code.capitalize}#{modlet.capitalize.sub(/\.rb$/, '').sub(/_(\w)/){"#$1".capitalize}}Run" : "#{code.capitalize}Run" end # Return the name of the run class according to the standard CodeRunner naming scheme. If the code name is 'a_code_name', with no modlet, the run class name will be <tt>ACodeName</tt>. If on the other hand there is a modlet called 'modlet_name', the class name will be <tt>ACodeName::ModletName</tt>. def self.get_run_class_name(code, modlet=nil) return modlet ? "#{code.capitalize}::#{modlet.capitalize.sub(/\.rb$/, '').variable_to_class_name}" : "#{code.capitalize}" end def self.repair_marshal_run_class_not_found_error(err) code, modlet = err.message.scan(/CodeRunner\:\:([A-Z][a-z0-9_]+)(?:::([A-Z]\w+))?/)[0] #ep 'merror', err, code, modlet; gets code.gsub!(/([a-z0-9])([A-Z])/, '\1_\2') (modlet.gsub!(/([a-z0-9])([A-Z])/, '\1_\2'); modlet.downcase) if modlet setup_run_class(code.downcase, modlet: modlet) end SETUP_RUN_CLASSES =[] # Create, set up and check the validity of the custom class which deals with a particular simulation code. This class will be defined in a custom module in the folder <tt>code_modules/code_name</tt>, where <tt>'code_name'</tt> is the name of the code. The only option is <tt>modlet:</tt>. # # If the custom class has already been set up, this method just returns the class. def self.setup_run_class(code, options={}) # logf(:setup_code) # log(:code, code) modlet = options[:modlet] version = options[:version] # log('modlet in setup_run_class', modlet) eputs "Loading modules for #{code}, #{modlet.inspect}..." # modlet = modlet.sub(/\.rb$/, '') if modlet raise CRFatal.new("Code must contain only lowercase letters, digits, and underscore, and must begin with a letter or underscore; it is '#{code}'") unless code =~ /\A[a-z_][a-z_\d]*\Z/ raise CRFatal.new("Input_file_module must contain only lowercase letters, digits, and underscore, and must begin with a letter or underscore; it is '#{modlet}'") if modlet and not modlet =~ /\A[a-z_][a-z_\d]*\Z/ run_class_name = get_run_class_name(code, modlet) # p run_class_name FileUtils.makedirs(ENV['HOME'] + "/.coderunner/#{code}crmod/") return const_get(run_class_name) if constants.include? (run_class_name).to_sym unless options[:force] SETUP_RUN_CLASSES.push run_class_name.downcase #Create the run_class, a special dynamically created class which knows how to process runs of the given code on the current system. #run.rb contains the basic methods of the class # puts run_class_name; gets # run_class = add_a_child_class(run_class_name, "") # run_class.class_eval(%[ # @@code=#{code.inspect}; @@version=#{version.inspect} # @@modlet=#{modlet.inspect} #modlet should be nil if not @@modlet_required # SYS = #{SYS.inspect} # include Log # Log.logi(:code_just_after_runfile, @@code) # ] # ) code_module_name = SCRIPT_FOLDER+ "/code_modules/#{code}/#{code}.rb" code_module_name = "#{code}crmod" require code_module_name # ep get_run_class_name(code, nil) run_class = const_get(get_run_class_name(code, nil)) run_class.instance_variable_set(:@code, code) raise "#{run_class} must inherit from CodeRunner::Run: its ancestors are: #{run_class.ancestors}" unless run_class.ancestors.include? Run if options[:runner] run_class.runner = options[:runner] run_class.instance_variable_set(:@runner, options[:runner]) end #Add methods appropriate to the current system system_module_name = SCRIPT_FOLDER+ "/system_modules/#{SYS}.rb" require system_module_name run_class.send(:include, const_get(SYS.variable_to_class_name)) # run_class.class_eval(File.read(system_module_name), system_module_name) #Some codes require an modlet; the flag modlet_required is specified in the code module if run_class.rcp.modlet_required raise CRFatal.new("Modlet necessary and none given") unless modlet end #If a modlet is specified (modlets can also be optional) if modlet # Log.logi(:modlet, modlet) #if ( modlet_location = "#{SCRIPT_FOLDER}/code_modules/#{code}/default_modlets"; #file_name = "#{modlet_location}/#{modlet}.rb"; #FileTest.exist? file_name #) #elsif ( modlet_location = "#{SCRIPT_FOLDER}/code_modules/#{code}/my_modlets"; #file_name = "#{modlet_location}/#{modlet}.rb"; #FileTest.exist? file_name #) #else #raise CRFatal.new("Could not find modlet file: #{modlet}.rb") #end #require file_name # ep run_class.constants # ep run_class_names modlet_file = "#{code}crmod/#{modlet}.rb" #ep ['requiring modlet file'] require modlet_file run_class = recursive_const_get(run_class_name) run_class.instance_variable_set(:@modlet, modlet) end run_class.check_and_update # log("random element of variables", run_class.variables.random) # logi("run_class.variables[0] in setup_code", run_class.variables[0]) # ep 'finished' return run_class end # Traverse the directory tree below the root folder, detecting and analysing all runs within that folder. Although runs submitted by CodeRunner will all be in one folder in the root folder, it is not necessary for the runs to be organised like that. This is because CodeRunner can also be used to analyse runs which it did not submit. # # All subfolders of the root_folder will be analysed, except for ones specified in the run class property <tt>excluded_sub_folders</tt>, or those containing the hidden file '.CODE_RUNNER_IGNORE_THIS_DIRECTORY' def traverse_directories # :doc: string = "" #ep 'traversing', Dir.pwd if FileTest.exist?("code_runner_info.rb") or FileTest.exist?("CODE_RUNNER_INPUTS") or FileTest.exist?("README") or @heuristic_analysis and (Dir.entries(Dir.pwd).find{|file| not [".","..","data.txt"].include? file and File.file? file} and not Dir.entries(Dir.pwd).include? '.CODE_RUNNER_IGNORE_THIS_DIRECTORY') #i.e. if there are some files in this directory (not just directories) eprint '.' if @write_status_dots begin raise CRMild.new("must recalc all") if @recalc_all or @reprocess_all #must recalculate the run results, not load them if @@recalc_all run = @run_class.load(Dir.pwd, self) #NB this doesn't always return an object of class run_class - since the run may actually be from a different code raise CRMild.new("not complete: must recalc") unless run.status == :Complete or run.status == :Failed raise CRMild.new("Not the right directory, must recalc") unless run.directory == Dir.pwd rescue ArgumentError, CRMild => err if err.class == ArgumentError unless err.message =~ /marshal data too short/ #puts err #puts err.backtrace raise err end end log(err) # puts err.class begin #interrupted = false; #old_trap2 = trap(2){} #old_trap2 = trap(2){eputs "Interrupt acknowledged...#{Dir.pwd} finishing folder analyis. Interrupt again to override (may cause file corruption)."; interrupted = true} run = @run_class.new(self).process_directory #NB this doesn't always return an object of class run_class - since the run may actually be from a different code #trap(2, old_trap2) #(eputs "Calling old interrupt #{Dir.pwd}"; Process.kill(2, 0)) if interrupted rescue => err log(err) unless @heuristic_analysis and (err.class == CRMild or err.class == CRError) # puts Dir.pwd logd eputs Dir.pwd eputs err.class eputs err # eputs err.backtrace eputs "----Only allowed to fail processing a directory if a heuristic analysis is being run" raise err end # puts err.class run = nil # puts @requests end end check = false if run # puts run.id, @run_list[run.id]; gets # raise CRFatal.new("\n\n-----Duplicate run ids: #{run.directory} and #{@run_list[run.id].directory}----") if @run_list[run.id] if @run_list[run.id] check = true raise <<EOF Duplicate run ids: New: #{run.run_name} #{run.status} in #{run.directory} Old: #{@run_list[run.id].run_name} #{@run_list[run.id].status} in #{@run_list[run.id].directory} EOF choice = Feedback.get_choice("Which do you want to keep, new or old? (The other folder will be deleted. Press Ctrl+C to cancel and sort the problem out manually)", ["New", "Old"]) case choice when /New/ raise "Aborting... this function has not been fully tested" FileUtils.rm_r(@run_list[run.id].directory) when /Old/ raise "Aborting... this function has not been fully tested" FileUtils.rm_r(run.directory) run = nil end end end if run (puts "you shouldn't see this if you chose old"; gets) if check run.save @run_list[run.id] = run @ids.push run.id @ids = @ids.uniq.sort @max_id = @max_id>run.id ? @max_id : run.id end if @heuristic_analysis Dir.foreach(Dir.pwd)do |directory| next if [".",".."].include? directory or File.file? directory or directory =~ /\.rb/ or @run_class.rcp.excluded_sub_folders.include? directory # begin Dir.chdir(directory) do traverse_directories end # rescue Errno::ENOENT # log Dir.entries # puts directory + " was not a directory" # end end end else Dir.foreach(Dir.pwd)do |directory| next if [".",".."].include? directory or File.file? directory or directory =~ /\.rb/ or @run_class.rcp.excluded_sub_folders.include? directory # begin Dir.chdir(directory) do traverse_directories end # rescue Errno::ENOENT # log Dir.entries # puts directory + " was not a directory" # end end end end private :traverse_directories # Write out a simple datafile containing all the inputs and outputs listed in the run class property <tt>readout_string</tt>. What is actually written out can be customised by redefining the method <tt>data_string</tt> in the run class, or changing <tt>readout_string</tt> or both. def write_data(filename = "data.txt") logf(:write_data) generate_combined_ids File.open(filename, "w") do |file| @combined_ids.each do |id| run = @combined_run_list[id] if run.status =~ /Complete/ data_string = run.data_string raise CRFatal.new("data_string did not return a string") unless data_string.class == String file.puts data_string end end end end # Sort the runs according to the variable <tt>@sort</tt> which can be either whitespace separated string or an array of strings. In the former case, the string is split to form an array of strings, using the separator <tt>/\s+/</tt>. For example, if # # @sort == ['height', '-weight', 'colour'] # # Then the runs will be sorted according to first height, then (descending) weight, then colour. What actually happens is that the variable <tt>@ids</tt> is sorted, rather than <tt>@run_list</tt>. For this to work, height, weight and colour must be either variables or results or instance methods of the run class. # # Type can be either '' or 'phantom', in which case the variable sorted will be either <tt>@ids</tt> or <tt>@phantom_ids</tt> respectively. def sort_runs(type = @use_phantom.to_s.sub(/real/, '')) logf(:sort_runs) log(:type, type) #ep 'sort', @sort #sort_list = @sort ? (@sort.class == String ? eval(@sort) : @sort) : [] run_list_name = [type.to_s, 'run_list'].join('_').gsub(/^_/, '') ids_name = [type.to_s, 'ids'].join('_').gsub(/^_/, '') log run_list_name set(ids_name, send(ids_name).sort_by do |id| run = send(run_list_name)[id] sortkey = run.instance_eval((@sort or '[]')) #ep 'sortkey', sortkey sortkey #sort_list.map{|str| run.instance_eval(str)} end) end # Print out a summary of all the runs in the root folder, formatted in nice pretty colours. Since this is often called in a loop, if called twice without any arguments it will erase the first printout. To stop this happening set rewind to 0. If the command is being issued not in a terminal, so that CodeRunner cannot determine the size of the terminal, the second argument must be passed as an array of [rows, columns]. def print_out(rewind = nil, options={}) # terminal_size = [rows, cols] rewind ||= @print_out_size terminal_size = options[:terminal_size] logf(:print_out) # raise CRFatal.new("terminal size must be given if this is called any where except inside a terminal (for example if yo u've called this as a subprocess)") unless terminal_size or $stdout.tty? terminal_size ||= Terminal.terminal_size #lots of gritty terminal jargon in here. Edit at your peril! unless ENV['CODE_RUNNER_NO_COLOUR']=='true' or ENV['CODE_RUNNER_NO_COLOR']=='true' dc= Terminal::WHITE # .default_colour green= Terminal::LIGHT_GREEN cyan = Terminal::CYAN bblck = Terminal::BACKGROUND_BLACK else dc= ""# Terminal::WHITE # .default_colour green= "" # Terminal::LIGHT_GREEN cyan = "" #Terminal::CYAN bblck = "" #Terminal::BACKGROUND_BLACK end cln = Terminal::CLEAR_LINE # print "\033[#{rewind}A" deco = '-'*terminal_size[1] Terminal.erewind(rewind) eputs "\n#{cln}\n#{cln}\n#{bblck}#{dc}#{deco}\n#{@run_class.rcp.code_long} Status:#{cln}\n#{deco}" i = 0; j=0 # i is no. of actual terminal lines; j is number of results lines # Group the lines by major sort key #@split = @sort && @sort.split(/\s+/).size > 1 ? @sort.split(/\s+/)[0].to_sym : nil @split_point = nil generate_combined_ids @combined_ids.each do |id| begin # puts id, :hello; gets @run = @combined_run_list[id] if filter # puts @run[:id], @id; gets #@new_split_point = @split ? @run.send(@split) : nil #if @split_point && @split_point != @new_split_point then eputs sprintf(" #{cln}", ""); i+=1 end #@split_point = @new_split_point eprint j%2==0 ? j%4==0 ? cyan : green : dc line = options[:with_comments] ? @run.comment_line : @run.print_out_line.chomp eprint line eputs cln # puts (line.size / Terminal.terminal_size[1]).class # puts (line.size / Terminal.terminal_size[1]) i+=((line.sub(/\w*$/, '').size-1) / terminal_size[1]).ceiling j+=1 end # raise "monkeys" rescue => err eputs err eputs err.backtrace eputs "---------------------\nUnable to print out line for this job:" eputs "run_name: #{@run.run_name}" eputs "status: #{@run.status}\n-----------------------" Terminal.reset return # raise CRFatal.new end end @print_out_size = i+7# + (@run_list.keys.find{|id| not [:Complete, :Failed].include? @run_list[id].status } ? 0 : 1) eprint dc, deco; Terminal.reset; eputs # puts # puts # puts dc # "\033[1;37m" # print 'rewind size is', rewind end # def filtered_run_list # logf :filtered_run_list # unless @use_phantom == :phantom # return @run_list.find_all{|id, run| filter(run)} # else # log 'using phantom' # return @phantom_run_list.find_all{|id, run| filter(run)} # end # end # Return a list of ids, filtered according to conditions. See CodeRunner#filter def filtered_ids(conditions=@conditions) generate_combined_ids # ep @combined_run_list.keys # sort_runs return @combined_ids.find_all{|id| filter(@combined_run_list[id], conditions)} end # Return true if # run.instance_eval(conditions) == true # and false if # run.instance_eval(conditions) == false. # performing some checks on the validity of the variable <tt>conditions</tt>. For people who are new to Ruby instance_eval means 'evaluate in the context of the run'. Generally <tt>conditions</tt> will be something like 'status == :Complete and height == 4.5 and not width == 20', where height and width might be some input parameters or results from the diminishing. def filter(run=@run, conditions=@conditions) logf(:filter) @run = run # to_instance_variables(directory) return true unless conditions # p conditions, @run.id, @run.is_phantom conditions = conditions.dup raise CRFatal.new(" ----------------------------- Conditions contain a single = sign: #{conditions} -----------------------------") if conditions =~ /[^!=<>]=[^=~<>]/ log conditions begin fil = @run.instance_eval(conditions) rescue => err eputs run.directory eputs conditions raise err end return fil end # Similar to CodeRunner#write_data, except that the readout is written to stdout, and formatted a bit. Will probably be rarely used. def readout logf(:readout) generate_combined_ids @split = @sort && @sort.split(/\s+/).size > 1 ? @sort.split(/\s+/)[0].to_sym : nil @split_point = nil string = @combined_ids.inject("") do |s, id| run = @combined_run_list[id] if run.status =~ /Complete/ and filter(run) @new_split_point = @split ? run.send(@split) : nil splitter = (@split_point and @split_point != @new_split_point) ? "\n\n" : "" @split_point = @new_split_point splitter = "" # comment to put split points back in # puts s.class, splitter.class, data_string(directory) data_string = run.data_string raise CRFatal.new("data_string did not return a string") unless data_string.class == String s + splitter + data_string else s end end # puts @max.inspect return string end # ? Probably can get rid of this one def readout_cols(*var_list) # :nodoc: logf :readout_cols ans = [[]] * var_list.size generate_combined_ids filtered_ids.each do |id| run = combined_run_list[id] var_list.each_with_index do |var, index| ans[index].push run.send(var) end end ans end # List every file in the root folder. def get_all_root_folder_contents # :nodoc: @root_folder_contents =[] Find.find(@root_folder){|file| @root_folder_contents.push file} end #Update the information about all the runs stored in the variable <tt>@run_list</tt>. By default, this is done by calling CodeRunner#traverse_directories. If, on the other hand, <tt>@use_large_cache</tt> is set to true, this is done by reading the temporary cache maintained in ".CODE_RUNNER_TEMP_RUN_LIST_CACHE" in the root folder. This is much quicker. If in addition <tt>@use_large_cache_but_recheck_incomplete</tt> is set to true, all runs whose status is not either :Complete or :Failed will be rechecked. def update(write_status_dots=true, use_large_cache=@use_large_cache, use_large_cache_but_recheck_incomplete=@use_large_cache_but_recheck_incomplete) @use_large_cache = use_large_cache logf(:update) @write_status_dots = write_status_dots @run_list={} @ids=[] @phantom_run_list = {} @phantom_ids = [] @run_store =[] # @multiple_processes_directories = [] set_max_id 0 @run_class.update_status(self) if @use_large_cache and not @recalc_all and not @reprocess_all log("using large cache") begin begin eputs 'Loading large cache...' if @write_status_dots Dir.chdir(@root_folder) do @run_list = Marshal.load(File.read(".CODE_RUNNER_TEMP_RUN_LIST_CACHE")) end @run_list.values.each{|run| run.runner = self} rescue ArgumentError => err eputs err raise err unless err.message =~ /undefined class/ #NB all code_names have to contain only lowercase letters: # modlet, code = err.message.scan(/CodeRunner\:\:([A-Z][\w+])?([A-Z]\w+)Run/)[0] code, modlet = err.message.scan(/CodeRunner\:\:([A-Z][a-z0-9_]+)(?:::([A-Z]\w+))?/)[0] # ep code.downcase, modlet modlet.downcase! if modlet setup_run_class(code.downcase, modlet: modlet) retry end # ep @run_list @ids = @run_list.keys @run_list.each{|id, run| run.runner = self } #eputs "Setting max id..." set_max_id(@ids.max || 0) #eputs "max_id = #@max_id" # puts @max_id; gets # @use_large_cache = false @ids.sort! redone_count = 0 # puts "hello" # ep @use_large_cache_but_recheck_incomplete; exit recheck_incomplete_runs if use_large_cache_but_recheck_incomplete # sort_runs eprint "Updating runs..." if @write_status_dots # get_all_root_folder_contents # puts @run_list.values[0].directory, File.expand_path(@root_folder).esc_regex fix_directories = (run_list.size > 0 and not @run_list.values[0].directory =~ File.expand_path(@root_folder).esc_regex) # eputs 'fdirectories', fix_directories # exit eputs "Fixing Directories..." if fix_directories @run_list.each do |id, run| eprint '.' if @write_status_dots run.directory = File.join(@root_folder, run.relative_directory) if fix_directories # run.directory = "#@root_folder/#{run.relative_directory}" # unless @root_folder_contents.include? run.directory# File.directory? run.directory and run.directory =~ File.expand_path(@root_folder).esc_regex # if @root_folder_contents.include?(rel = File.join(@root_folder, run.relative_directory)) # run.directory = rel # else # raise CRFatal.new("Directory #{run.directory} not found") # end # end # eputs @use_phantom #run.generate_phantom_runs #if @use_phantom.to_s =~ /phantom/i run.phantom_runs.each{|r| add_phantom_run(r)} if run.phantom_runs end eputs if @write_status_dots save_large_cache if fix_directories # puts redone_count return self rescue Errno::ENOENT, ArgumentError, TypeError => err if err.class == ArgumentError and not err.message =~ /marshal data too short/ or err.class == TypeError and not err.message =~ /incompatible marshal file format/ eputs err eputs err.backtrace raise CRFatal.new end eputs err, "Rereading run data" # @use_large_cache = false end end log("not using large cache") @run_list={} @ids=[] @phantom_run_list = {} @phantom_ids = [] @run_store =[] # @multiple_processes_directories = [] set_max_id 0 log("traversing directories") eprint 'Analysing runs..' if @write_status_dots #interrupted = false; #old_trap2 = trap(2){} #trap(2){eputs "Interrupt acknowledged... reloading saved cache. Interrupt again to override (may cause file corruption)."; trap(2, old_trap2); update(true, true, false); Process.kill(2,0)} Dir.chdir(@root_folder){traverse_directories} @max_id ||= 0 eputs # puts 'before request', @ids, @requests; respond_to_requests # @n_checks += 1 # exit if ($nruns > 0 && @n_checks > $nruns) sort_runs @recalc_all = false # pp @run_list save_large_cache #@run_list.each{|id, run| run.generate_phantom_runs} #trap(2, old_trap2) #Process.kill(2, 0) if interrupted return self end # Dump all the instance variables of the runner to stdout as Marshalled binary data. This is used for RemoteCodeRunner server functions. def marshalled_variables #ep 'marsh1' instance_vars = {} instance_variables.each do |var| instance_vars[var] = instance_variable_get(var) end instance_vars[:@run_list].values.each{|run| run.runner=nil} #Kernel.puts server_dump(instance_vars) instance_vars[:@cache]={} instance_vars[:@phantom_run_list].values.each{|run| run.runner = nil} #ep 'marsh2' #eputs instance_vars.pretty_inspect #instance_vars.each do |var, val| #ep var #eputs server_dump(val) #end instance_vars end # Write the variable <tt>@run_list</tt>, which contains all information currently known about the simulations in the root folder, as Marshalled binary data in the file ".CODE_RUNNER_TEMP_RUN_LIST_CACHE". This cache will be used later by CodeRunner#update. def save_large_cache # pp self # ep @run_list # pp @run_list.values.map{|run| run.instance_variables.map{|var| [var, run.instance_variable_get(var).class]}} generate_combined_ids @combined_run_list.each{|id, run| run.runner = nil} File.open(@root_folder + "/.CODE_RUNNER_TEMP_RUN_LIST_CACHE", 'w'){|file| file.puts Marshal.dump @run_list} @combined_run_list.each{|id, run| run.runner = self} end # Self-explanatory! Call CodeRunner::Run#process_directory for every run whose status is not either :Complete or :Failed. (Note, for historical reasons traverse_directories is called rather than CodeRunner::Run#process_directory directly but the effect is nearly the same). def recheck_incomplete_runs logf :recheck_incomplete_runs @run_class.update_status(self) redone_count = 0 run_list, @run_list = @run_list, {}; @ids = []; run_list.each do |id, run| # print id if run.status == :Complete or run.status == :Failed # print ".", id, "___" @run_list[id] = run @ids.push id else # print id, "%%%"; redone_count+=1 Dir.chdir(run.directory){traverse_directories} end end @ids.sort! # @ids = @run_list.keys set_max_id(@ids.max || 0) sort_runs respond_to_requests save_large_cache end # Self-explanatory! Call CodeRunner::Run#process_directory for every run for which CodeRunner#filter(run) is true. (Note, for historical reasons traverse_directories is called rather than CodeRunner::Run#process_directory directly but the effect is nearly the same). def recheck_filtered_runs(write_status_dots=false) @write_status_dots = write_status_dots logf :recheck_filtered_runs @run_class.update_status(self) @run_list.each do |id, run| if filter(run) and not (run.status == :Complete or run.status == :Failed) # eputs run.directory Dir.chdir(run.directory){run.process_directory} # eputs run.status # ep run end end save_large_cache # run_list, @run_list = @run_list, {}; @ids = []; @max_id = 0 # run_list.each do |id, run| # if not filter(run) or run.status == :Complete # @run_list[id] = run # @ids.push id # else # Dir.chdir(run.directory){traverse_directories} # end # end # @ids.sort! # @ids = @run_list.keys set_max_id(@ids.max || 0) sort_runs respond_to_requests save_large_cache end # One of the features of CodeRunner is two way communication between a runner and its runs. The runs can request actions from the runner directly by calling its instance methods, but often the runs want something to happen after the runner has processed every run in the directory. For example if a run wanted to check if it was resolved, it would need to know about all the other runs so it could compare itself with them. In this case it would place an instance method that it wanted to call in the variable <tt>@requests</tt> in the runner. The runner would then call that instance method on every run after it had finished processing all the runs. # # In summary, this method is called after every time the runner has checked through the directory. When it is called, it looks in the variable <tt>@requests</tt> which contains symbols representing methods. It calls each symbol as an instance method of every run in turn. So if <tt>@requests</tt> was <tt>[:check_converged]</tt> it would call <tt>run.check_converged</tt> for every run. def respond_to_requests logf(:respond_to_requests) logi(:@requests, @requests) log('@phantom_run_list.class', @phantom_run_list.class) while @requests[0] old_requests = @requests.uniq @requests = [] old_requests.each do |request| @current_request = request if request == :traverse_directories # a special case @ids = [] @run_list = {} @phantom_run_list = {} @phantom_ids = [] Dir.chdir(@root_folder){traverse_directories} else filtered_ids.each do |id| run = @run_list[id] Dir.chdir(run.directory){run.instance_eval(request.to_s); run.save; run.write_results} end end end end end # Start a simulation: submit the run that is passed. What happens is as follows: # # 1. Modify the run according to options. # 2. Check if any other processes are submitting runs in the same root folder. In this case there will be a file called 'submitting' in the folder. If there is such a file wait until it is gone. # 3. Check if a run with identical parameters has been submitted before. In which case skip submitting the run unless options[:skip] == false. # 4. Call <tt>run.submit</tt> # #Options can be any one of <tt>CodeRunner::SUBMIT_OPTIONS</tt>. The options passed here will override values stored as instance variables of the runner with the same name, which will override these values if they are set in the runs itself. For example if # run.nprocs == '32x4' # runner.nprocs == nil # options[:nprocs] == nil # the number of processes will be 32x4. On the other hand if # run.nprocs == '32x4' # runner.nprocs == '24x4' # options[:nprocs] == '48x4' # the number of processes will be 48x4. def submit(runs, options={}) eputs "System " + SYS eputs "No. Procs " + @nprocs.inspect runs = [runs] unless runs.class == Array #can pass a single run to submit outruns = runs.dup skip = true unless options[:skip] == false SUBMIT_OPTIONS.each do |option| set(option, options[option]) if options.keys.include? option end logf(:submit) Dir.chdir(@root_folder) do @skip=skip mess = false while FileTest.exist?("submitting") (eputs " Waiting for another process to finish submitting. If you know that no other CodeRunner processes are submitting in this folder (#@root_folder) then delete the file 'submitting' and try again"; mess = true) unless mess sleep rand end # old_trap = trap(0) old_trap0 = trap(0){eputs "Aborted Submit!"; File.delete("#@root_folder/submitting"); exit!} old_trap2 = trap(2){eputs "Aborted Submit!"; File.delete("#@root_folder/submitting") if FileTest.exist? "#@root_folder/submitting"; trap(2, "DEFAULT"); trap(0, "DEFAULT"); Process.kill(2, 0)} # File.open("submitting", "w"){|file| file.puts ""} FileUtils.touch("submitting") unless options[:no_update_before_submit] @use_large_cache, ulc = false, @use_large_cache; update; @use_large_cache = ulc end generate_combined_ids(:real) # old_job_nos = queue_status.scan(/^\s*(\d+)/).map{|match| match[0].to_i} script = "" if options[:job_chain] runs.each_with_index do |run, index| similar = similar_runs([], run) if @skip and similar[0] and not (options[:replace_existing] or options[:rerun]) eputs "Found similar run: #{@run_list[similar[0]].run_name}" eputs "Skipping submission..." runs[index] = nil next end unless options[:replace_existing] or options[:rerun] @max_id+=1 run.id = @max_id else if options[:replace_existing] FileUtils.rm_r run.directory elsif options[:rerun] ################# For backwards compatibility SUBMIT_OPTIONS.each do |opt| run.set(opt, send(opt)) unless run.send(opt) end ########################################### FileUtils.rm "#{run.directory}/code_runner_results.rb" FileUtils.rm "#{run.directory}/.code_runner_run_data" end @run_list.delete(run.id) @ids.delete run.id generate_combined_ids end begin unless options[:job_chain] run.prepare_submission unless options[:rerun] next if @test_submission Dir.chdir(run.directory) do old_job_nos = queue_status.scan(/^\s*(\d+)/).map{|match| match[0].to_i} ######################### The big tomale! run.job_no = run.execute # Start the simulation and get the job_number ######################### run.job_no = get_new_job_no(old_job_nos) unless run.job_no.kind_of? Integer # (if the execute command does not return the job number, look for it manually) # eputs 'run.job_no', run.job_no run.output_file = nil # reset the output file run.output_file # Sets the output_file on first call run.error_file = nil # reset the output file run.error_file # Sets the error_file on first call run.write_info eputs "Submitted run: #{run.run_name}" end else run.prepare_submission unless options[:rerun] script << "cd #{run.directory}\n" script << "#{run.run_command}\n" next if @test_submission end rescue => err File.delete("submitting") raise(err) end end # runs.each runs.compact! if options[:job_chain] and not @test_submission and runs.size > 0 FileUtils.makedirs('job_chain_files') @id_list = runs.map{|run| run.id} #@executable ||= runs[0].executable @submission_script = script # A hook... default is to do nothing @submission_script = @run_class.modify_job_script(self, runs, @submission_script) # To get out of job_chain_files folder @submission_script = "cd .. \n" + @submission_script old_job_nos = queue_status.scan(/^\s*(\d+)/).map{|match| match[0].to_i} ################ Submit the run Dir.chdir('job_chain_files'){job_no = execute} ################ job_no = get_new_job_no(old_job_nos) unless job_no.kind_of? Integer # (if the execute command does not return the job number, look for it manually) # eputs 'jobchain no', job_no #runs.each{|run| run.job_no = job_no} runs.each do |run| run.job_no = @job_no = job_no run.output_file = run.relative_directory.split("/").map{|d| ".."}.join("/") + "/job_chain_files/" + output_file run.error_file = run.relative_directory.split("/").map{|d| ".."}.join("/") + "/job_chain_files/" + error_file run.write_info eputs "Submitted run: #{run.run_name}" end end @write_status_dots, wsd = false, @write_status_dots @run_class.update_status(self) runs.each do |run| # ep run.id, run_list.keys Dir.chdir(run.directory){traverse_directories} end @write_status_dots = wsd save_large_cache File.delete("submitting") trap(0, old_trap0) trap(2, old_trap2) end # Dir.chdir(@root_folder) # eputs #ep 'runs submitted', outruns return outruns[0].id if outruns.size == 1 #used in parameter scans end # def submit def rcp @run_class.rcp end def executable_name return 'job_chain' unless @executable File.basename(@executable) end def executable_location return '' unless @executable File.dirname(@executable) end def code_run_environment run_class.new(self).code_run_environment end def run_command #ep 'submission_script', @submission_script @submission_script end private :run_command def job_identifier "#{@id_list[0]}-#{@id_list[-1]}" end #private :job_identifier # Assuming only one new job has been created, detect its job number. def get_new_job_no(old_job_nos) # :doc: #|| "" # qstat = qstat=~/\S/ ? qstat : nil job_no = nil if self.respond_to? :queue_wait_attempts ntimes = queue_wait_attempts else ntimes = 5 end eputs 'Waiting for job to appear in the queue...' ntimes.times do |i| # job_no may not appear instantly # eputs queue_status new_job_nos = queue_status.scan(/^\s*(\d+)/).map{|match| match[0].to_i} job_no = (new_job_nos-old_job_nos).sort[0] # eputs "job_no", job_no break if job_no sleep 0.2 qstat = queue_status if i == ntimes eputs 'Timeout... perhaps increase queue_wait_attempts in the system module?' end end job_no ||= -1 # some functions don't work if job_no couldn't be found, but most are ok end private :get_new_job_no # def submit # # # logi(:job_nos, job_nos) # ################## # # ################## # # eputs info_file # @sys = SYS # # end # # # else # File.delete("submitting") # raise CRFatal.new("queue_status did not return a string; submission cancelled. Suggest editing system_modules/#{SYS}.rb") # end # # end # Create a new instance of the class <tt>@run_class</tt> def new_run logf(:new_run) @run_class.new(self) end @@wait = true #Do you wait for the previous run to have completed when using simple scan? # Submit a series of runs according to scan_string. scan_string specifies a number of scans separated by hashes. Each scan has a number which is the ID of the run to start from followed by a colon. After the colon the user can write some code which modifies the original run. For example: # # simple_scan('23: @height *= 2; @weight *=1.1') # # will submit a series of runs, where each successive run has height twice the last one, and weight 1.1 times the last one, where we assume that height and weight are input parameters. # # Options are the same as CodeRunner#submit def simple_scan(scan_string, options={}) scans = scan_string.split('#') ppipe = PPipe.new(scans.size + 1, true, controller_refresh: 0.5, redirect: false) pipe_numbers = ppipe.fork(scans.size - 1) #p @run_class.naming_pars instructions = (scans[(ppipe.mpn > 0 ? ppipe.mpn - 1 : 0)]) id = instructions.scan(/^\d+\:/)[0].to_i instructions = instructions.sub(/^\d+\:/, '') @run= id > 0 ? @run_list[id] : (run = @run_class.new(self); run.update_submission_parameters((options[:parameters] or '{}')); run) @run_class.rcp.variables.each do |par| #p par, @run_class.naming_pars @run.naming_pars.push par if scan_string =~ Regexp.new(Regexp.escape(par.to_s)) end @run.naming_pars.uniq! # @run.naming_pars +== @run_class.naming_pars catch(:finished) do loop do #submit loop ppipe.synchronize(:submit) do @running = submit(@run, nprocs: options[:nprocs], version: @run_class.rcp.version) @conditions = "id == #@running" #print_out #ep 'Running run', @running end loop do # check finished loop dir = @run_list[@running].directory @run_list.delete(@running) @run_class.update_status(self) Dir.chdir(dir) do traverse_directories end unless @@wait and (@run_list[@running].status == :Incomplete or @run_list[@running].status == :NotStarted or @run_list[@running].status == :Queueing) @run.parameter_transition(@run_list[@running]) @old_run = @run_list[@running] break end #p @running ppipe.i_send(:running, @running, tp: 0) if ppipe.is_root arr = (pipe_numbers + [0]).inject([]) do |arr, pn| arr.push ppipe.w_recv(:running, fp: pn) end #p arr @conditions = "#{arr.inspect}.include? id" print_out end sleep 3 end @run.instance_eval(instructions) end end (ppipe.die; exit) unless ppipe.is_root ppipe.finish end # nprocs = options[:nprocs] # # version = options[:version] # skip = true unless options[:skip] == false # logf(:submit) # Dir.chdir(@root_folder) do # run.nprocs =nprocs; # A parameter scan array is a list of parameter_scans: # [parameter_scan, parameter_scan, ...] # A parameter_scan is a list of variable scans: # [variable_scan, variable_scan, ...] # # A variable_scan consists of a name, and a list of values; # # ['width', [0.3, 0.5, 0.6]] # # A parameter scan will scan through every possible combination of variable values, varying the final variable fastest. # # In between each run it will call the hook function parameter_transition. This allows you to adjust the input variables of the next run based on the results of the previous. # e.g. # parameter_scan_array = [ # [ # ['width', [0.3, 0.5, 0.6]], ['height', [0.5, 4.3]] # ], # [ # ['width', [7.2, 0.6]], ['height', [3.6, 12.6, 12.9, 0.26]] # ] # ] # # This will run two simultaneous parameter scans: one with 3x2 = 6 runs; one with 2x4 = 8 runs, a total of 14 runs # # Any variables not specified in the parameter scan will be given their default values. def parameter_scan(parameter_scan, parameters, options={}) skip = true unless options[:skip] == false # version= (options[:version] or "") nprocs = options[:nprocs] logf(:parameter_scan) raise CRFatal.new("Wrong directory: parameter scan being conducted in #{Dir.pwd} instead of my root folder: #{@root_folder}") unless Dir.pwd == File.expand_path(@root_folder) @skip = skip puts parameter_scan.inspect @nprocs = nprocs; @skip=skip; log '@run_class', @run_class @run = @run_class.new(self) @run.update_submission_parameters(parameters) # @running_scans = {}; @gammas = {} beginning = "catch(:finished) do \n" end_string = "\nend" parameter_scan.each do |variable_scan| beginning += %[ #{variable_scan[1].inspect}.each do |value|\n\t@run.#{variable_scan[0]} = value\n] @run_class.rcp.naming_pars.push variable_scan[0].to_sym; @run_class.rcp.naming_pars.uniq! end_string += %[\nend] end middle = <<EOF @@psppipe.synchronize(:pssubmit){@running = submit(@run, nprocs: @nprocs, version: @version, skip: @skip); update}; loop do # @@mutex.synchronize{} @run_class.update_status(self) # puts run_class.current_status Dir.chdir(@run_list[@running].directory){@run_list.delete(@running); traverse_directories} # ep @run_list[@running].status, @run_list[@running].id, @run_list[@running].job_no, queue_status unless @run_list[@running].status == :Incomplete or @run_list[@running].status == :NotStarted @run.parameter_transition(@run_list[@running]) break end sleep 3 # Thread.pass # puts Thread.current.to_s + " is looping, @run_list[@running].status = " + @run_list[@running].status.to_s + " @running = " + @running.to_s + " @run_list[@running].job_no = " + @run_list[@running].job_no.to_s end EOF command = beginning + middle + end_string puts command instance_eval(command, 'parameter_scan_code') # puts Thread.current.object_id # puts Thread.current.to_s; print " is finished" # @@psppipe.i_send(:finished, true, tp: 0) end # Find runs whose input parameters are all the same as those for <tt>run</tt>, with the exception of those listed in <tt>exclude_variables</tt> def similar_runs(exclude_variables=[], run=@run) #all runs for which variables are the same as 'run', with the exception of exclude_variables logf(:similar_runs) raise CRFatal.new("generate_combined_ids must be called before this function is called") unless (@combined_run_list.size > 0 and @combined_ids.size > 0) or @ids.size ==0 command = (run.class.rcp.variables+run.class.rcp.run_info-exclude_variables - [:output_file, :error_file, :runner, :phantom_runs]).inject("@combined_ids.find_all{|id| @combined_run_list[id].class == run.class}"){ |s,v| s + %<.find_all{|id| @combined_run_list[id].#{v}.class == #{run.send(v).inspect}.class and @combined_run_list[id].#{v} == #{run.send(v).inspect}}>} #the second send call retrieves the type conversion # log command #puts command begin similar = instance_eval(command) rescue => err log command raise err end return similar end # def max_conditional(variable,sweep=nil, conditions=nil) # logf(:max_complete) # return get_max_complete(variable,sweep, complete) == @run.id # end # # def max(variable,sweep=nil, complete=nil) # logf(:max) # return get_max(variable,sweep, complete) == @run.id # end # # def get_max(variable,sweep=nil, complete=nil) # logf :get_max # sweep ||= variable # logi @run.maxes # @run.maxes[variable] ||= {} # similar = similar_runs([sweep]) # similar = similar.find_all{|id| @combined_run_list[id].status == :Complete} if complete # logi(:similar, similar, @combined_run_list[similar[0]].send(variable)) # @run.maxes[variable][sweep] ||= similar[1] ? similar.max{|id1,id2| @combined_run_list[id1].send(variable) <=> @combined_run_list[id2].send(variable)} : @run.id # # puts "got_here" # logi("@run.maxes[#{variable}][#{sweep}]", @run.maxes[variable][sweep]) # return @run.maxes[variable][sweep] # end def get_max(run, variable,sweep, complete=nil) logf :get_max generate_combined_ids sweep = [sweep] unless sweep.class == Array similar = similar_runs(sweep, run) similar = similar.find_all{|id| @combined_run_list[id].status == :Complete} if complete logi(:similar, similar, @combined_run_list[similar[0]].send(variable)) max = similar[1] ? similar.max{|id1,id2| @combined_run_list[id1].send(variable) <=> @combined_run_list[id2].send(variable)} : similar[0] # puts "got_here" return max end def get_min(run, variable,sweep, complete=nil) logf :get_min generate_combined_ids sweep = [sweep] unless sweep.class == Array similar = similar_runs(sweep, run) similar = similar.find_all{|id| @combined_run_list[id].status == :Complete} if complete logi(:similar, similar, @combined_run_list[similar[0]].send(variable)) min = similar[1] ? similar.min{|id1,id2| @combined_run_list[id1].send(variable) <=> @combined_run_list[id2].send(variable)} : similar[0] # puts "got_here" return min end # # def get_max_conditional(variable,sweep=nil, conditions=nil) # logf(:get_max_conditional) # raise CRFatal.new("generate_combined_ids must be called before this function is called") unless @combined_run_list[0] # sweep ||= variable # similar = similar_runs([sweep]).find_all{|id| filter(@combined_run_list[id], conditions)} # similar = similar.find_all{|id| @combined_run_list[id].status == :Complete} if complete # logi(:similar, similar, @combined_run_list[similar[0]].send(variable)) # id_of_max = similar[1] ? similar.max{|id1,id2| @combined_run_list[id1].send(variable) <=> @combined_run_list[id2].send(variable)} : @run.id # # puts "got_here" # return id_of_max # end # Duplicate the runner, trying to be intelligent as far as possible in duplicating instance variables. Not fully correct yet. Avoid using at the moment. def dup logf(:dup) new_one = self.class.new(@code, @root_folder, modlet: @modlet, version: @version) new_one.ids = @ids.dup; new_one.phantom_ids = @phantom_ids.dup; new_one.run_list = @run_list.dup; new_one.phantom_run_list = @phantom_run_list.dup new_one.run_class = @run_class return new_one end # Delete the folders of all runs for whom CodeRunner#filter(run) is true. This will permanently erase the runs. This is an interactive method which asks for confirmation. def destroy(options={}) ids = @ids.find_all{|id| filter @run_list[id]} unless options[:no_confirm] logf(:destroy) puts "About to delete:" ids.each{|id| eputs @run_list[id].run_name} return unless Feedback.get_boolean("You are about to DESTROY #{ids.size} jobs. There is no way back. All data will be eliminated. Please confirm the delete.") #gets eputs "Please confirm again. Press Enter to confirm, Ctrl + C to cancel" gets end ids.each{|id| FileUtils.rm_r @run_list[id].directory if @run_list[id].directory and not ["", ".", ".."].include? @run_list[id].directory @run_list.delete(id); @ids.delete(id); generate_combined_ids} set_max_id(@ids.max || 0) save_large_cache generate_combined_ids end # Cancel the job with the given ID. Options are: # :no_confirm ---> true or false, cancel without asking for confirmation if true # :delete ---> if (no_confirm and delete), delete cancelled run def cancel_job(id, options={}) @run=@run_list[id] raise "Run with id #{id} does not exist" unless @run unless options[:no_confirm] eputs "Cancelling job: #{@run.job_no}: #{@run.run_name}. \n Press enter to confirm" # puts 'asfda' gets end @run.cancel_job if options[:no_confirm] delete = options[:delete] else delete = Feedback.get_boolean("Do you want to delete the folder (#{@run.directory}) as well?") end FileUtils.rm_r(@run.directory) if delete and @run.directory and not @run.directory == "" update print_out end # Needs to be fixed. # def rename_variable(old, new) # puts "Please confirm complete renaming of #{old} to #{new}" # gets # @run_list.each do |directory| # Dir.chdir directory[:directory] do # begin # @readme = File.read("CODE_RUNNER_INPUTS") # rescue Errno::ENOENT => err # # puts err, err.class # @readme = File.read("README") # end # @readme.sub!(Regexp.new("^\s+#{old}:"), "^\s+#{new}:") # File.open("CODE_RUNNER_INPUTS_TEST", 'w'){|file| file.puts @readme} # end # end # old_recalc, @recalc_all = @recalc_all, true # update # @recalc_all = old_recalc # end def add_phantom_run(run) @phantom_run_list[@phantom_id] = run @phantom_ids.push @phantom_id #run.real_id = run.id run.id = @phantom_id @phantom_id += -1 end def generate_combined_ids(kind= nil) logf(:generate_combined_ids) # case purpose # when :print_out # @combined_ids = [] # @combined_ids += @phantom_ids if @run_class.print_out_phantom_run_list # @combined_ids += @ids if @run_class.print_out_real_run_list # when :readout # @combined_ids = [] # @combined_ids += @phantom_ids if @run_class.readout_phantom_run_list # @combined_ids += @ids if @run_class.readout_real_run_list # when :submitting # @combined_ids = @ids kind ||= @use_phantom case kind when :real @combined_ids = @ids when :phantom @combined_ids = @phantom_ids when :both @combined_ids = @ids + @phantom_ids else raise CRFatal.new("Bad use phantom variable: #{kind.inspect}") end log('@phantom_run_list.class', @phantom_run_list.class) #puts 'crlist', @phantom_run_list.keys, @run_list.keys @combined_run_list = @phantom_run_list + @run_list log(:kind, kind) # log(:combined_ids, @combined_ids) sort_runs(:combined) end def save_all save_large_cache @run_list.values.each do |run| run.save run.write_results end end def save_all_and_overwrite_info save_all @run_list.values.each do |run| run.write_info end end private :save_all_and_overwrite_info # Permanently change the id of every run in the folder by adding num to them. Num can be negative unless it makes any of the ids negative. Use if you want to combine these runs with the runs in another folder, either by creating an instance of CodeRunner::Merge, or by directly copying and pasting the run folders. def alter_ids(num, options={}) Dir.chdir(@root_folder) do return unless options[:no_confirm] or Feedback.get_boolean("This will permanently alter all the ids in the folder #@root_folder. Scripts that use those ids may be affected. Do you wish to continue?") raise ArgumentError.new("Cannot have negative ids") if @run_list.keys.min + num < 0 runs = @run_list.values fids = filtered_ids @run_list = {} runs.each do |run| old_id = run.id if fids.include? old_id run.id += num old_dir = run.relative_directory new_dir = old_dir.sub(Regexp.new("id_#{old_id}(\\D|$)")){"id_#{run.id}#$1"} # ep old_dir, new_dir FileUtils.mv(old_dir, new_dir) run.relative_directory = new_dir run.directory = File.expand_path(new_dir) end @run_list[run.id] = run end @ids = @run_list.keys set_max_id(@ids.max || 0) save_all_and_overwrite_info end end def continue_in_new_folder(folder, options={}) Dir.chdir(@root_folder) do raise "Folder already exists" if FileTest.exist?(folder) FileUtils.makedirs("#{folder}/v") #FileUtils.makedirs(folder) FileUtils.cp(".code_runner_script_defaults.rb", "#{folder}/.code_runner_script_defaults.rb") FileUtils.cp(".code-runner-irb-save-history", "#{folder}/.code-runner-irb-save-history") FileUtils.cp("#{@defaults_file}_defaults.rb", "#{folder}/#{@defaults_file}_defaults.rb") if options[:copy_ids] options[:copy_ids].each do |id| FileUtils.cp_r(@run_list[id].directory, "#{folder}/v/id_#{id}") end end end end # Create a tar archive of the root folder and all the files in it. Options are # :compression => true or false # :folder => folder in which to place the archive. # :verbose => true or false # :group => group of new files # def create_archive(options={}) verbose = options[:verbose] ? 'v' : '' very_verbose = options[:very_verbose] ? 'v' : '' comp = options[:compression] Dir.chdir(@root_folder) do temp_root = ".tmparch/#{File.basename(@root_folder)}" FileUtils.makedirs(temp_root) system "chgrp #{options[:group]} #{temp_root}" if options[:group] size=@run_list.size @run_list.values.each_with_index do |run, index| archive_name = "#{File.basename(run.directory)}.tar#{comp ? '.gz' : ''}" tar_name = archive_name.delsubstr('.gz') relative = run.directory.delete_substrings(@root_folder, File.basename(run.directory)) FileUtils.makedirs(temp_root + relative) unless FileTest.exist? temp_root + relative + archive_name eputs "Archiving #{index} out of #{size}" if options[:verbose] Dir.chdir(run.directory + '/..') do command = "tar -cW#{very_verbose}f #{tar_name} #{File.basename(run.directory)}" eputs command if options[:verbose] unless system command raise "Archiving failed" end break unless comp command = "gzip -4 -vf #{tar_name}" eputs command if options[:verbose] unless system command raise "Compression failed" end command = "gzip -t #{archive_name}" eputs command if options[:verbose] unless system command raise "Compression failed" end #exit end FileUtils.mv(relative.delsubstr('/') + archive_name, temp_root + '/' + relative + archive_name) end system "chgrp -R #{options[:group]} #{temp_root}" if options[:group] end Dir.entries.each do |file| case file when '.', '..', '.tmparch' next when /^v/ next unless File.file? file else FileUtils.cp_r(file, "#{temp_root}/#{file}") end end Dir.chdir('.tmparch') do command = "tar -cWv --remove-files -f #{File.basename(@root_folder)}.tar #{File.basename(@root_folder)}" command = "tar -cWv -f #{File.basename(@root_folder)}.tar #{File.basename(@root_folder)}" eputs command if options[:verbose] raise "Archiving Failed" unless system command end FileUtils.mv(".tmparch/#{File.basename(@root_folder)}.tar", "#{File.basename(@root_folder)}.tar") #FileUtils.rm_r(".tmparch") end end end [ "/graphs_and_films.rb", "/remote_code_runner.rb", "/merged_code_runner.rb", '/run.rb', '/heuristic_run_methods.rb', ].each do |file| file = CodeRunner::SCRIPT_FOLDER + file require file eprint '.' unless $has_put_startup_message_for_code_runner end --Added auto creation of central defaults folder # A comment class CodeRunner # declare the constant end # = CodeRunner Overview # # CodeRunner is a class designed to make the running an analysis of large simulations and easy task. An instance of this class is instantiated for a given root folder. The runner, as it is known, knows about every simulation in this folder, each of which has a unique id and a unique subfolder. # # The heart of the runner is the variable run_list. This is a hash of IDs and runs. A run is an instance of a class which inherits from CodeRunner::Run, and which is customised to be able to handle the input variables, and the output data, from the given simulation code. This is achieved by a module which contains a child class of CodeRunner::Run, which is provided independently of CodeRunner. # # CodeRunner has methods to sort these runs, filter them according to quite complex conditions, print out the status of these runs, submit new runs, plot graphs using data from these runs, cancel running jobs, delete unwanted runs, and so on. # # = CodeRunner Interfaces # # CodeRunner has two different interfaces: # # 1. Instance methods # 2. Class methods # # == Instance Methods # # The instance methods provide a classic Ruby scripting interface. A runner is instantiated from the CodeRunner class, and passed a root folder, and possibly some default options. Instance methods can then be called individually. This is what should be used for complex and non-standard tasks. # # == Class methods # # The class methods are what are used by the command line interface. They define a standard set of tasks, each of which can be customised by a set of options known as command options, or <i>copts</i> for short. # # There is a one-to-one correspondence between the long form of the commandline commands, and the class methods that handle those commands, and between the command line flags, and the options that are passed to the class methods. So for example: # # $ coderunner submit -p '{time: 23.4, resolution: 256}' -n 32x4 -W 600 # # Becomes # # CodeRunner.submit(p: '{time: 23.4, resolution: 256}', n: "32x4", W: 600) # # remembering that braces are not needed around a hash if it is the final parameter. # # These methods are what should be used to automate a large number of standard tasks, which would be a pain to run from the command line. class CodeRunner class CRMild < StandardError # more of a dead end than an error. Should never be allowed to halt execution def initialize(mess="") mess += "\n\n#{self.class} created in directory #{Dir.pwd}" super(mess) end end class CRError < StandardError # usually can be handled def initialize(mess="") mess += "\n\n#{self.class} created in directory #{Dir.pwd}" super(mess) end end class CRFatal < StandardError # should never be rescued - must always terminate execution def initialize(mess="") mess += "\n\n#{self.class} created in directory #{Dir.pwd}" super(mess) end end # Parameters important to the submission of a run, which can be set by command line flags. The runner values provide the default values for the submit function, but can be overidden in that function. All the runner does with them is set them as properties of the run to be submitted. It is the run itself for which the options are relevant. SUBMIT_OPTIONS = [:nprocs, :wall_mins, :sys, :project, :comment, :executable] # A hash containing the defaults for most runner options. They are overridden by any options provided during initialisation. They are mostly set at the command line (in practice, the command line flags are read into the command options, which set these defaults in the function CodeRunner.process_command_options which calls CodeRunner.set_runner_defaults). However, if Code Runner is being scripted, these defaults must be set manually or else the options they specify must be provided when initialising a runner. DEFAULT_RUNNER_OPTIONS = ([:conditions, :code, :executable, :sort, :debug, :script_folder, :recalc_all, :multiple_processes, :heuristic_analysis, :test_submission, :reprocess_all, :use_large_cache, :use_large_cache_but_recheck_incomplete, :use_phantom, :no_run, :server, :version, :parameters] + SUBMIT_OPTIONS).inject({}){|hash, option| hash[option] = nil; hash} # Options that apply across the CodeRunner class CLASS_OPTIONS = [:multiple_processes].inject({}){|hash, option| class_accessor option set(option, nil) hash[option] = nil; hash } DEFAULT_RUNNER_OPTIONS.keys.each do |variable| #define accessors for class options and instance options # class_accessor(variable) attr_accessor variable # class_variable_set(variable, nil) end # def self.default_script_info # Hash.phoenix('.code_runner_script_defaults.rb') # # eval(File.read('.code_runner_script_defaults.rb')) # end # # def self.add_to_default_script_info(hash) # Hash.phoenix('.code_runner_script_defaults.rb') do |defaults| # hash.each{|key,value| defaults[key] = value} # end # end DEFAULT_RUNNER_OPTIONS[:use_phantom] = :real DEFAULT_RUNNER_OPTIONS[:script_folder] = SCRIPT_FOLDER #File.dirname(File.expand_path(__FILE__)) # These are properties of the run class that must be defined. For more details see CodeRunner::Run. NECESSARY_RUN_CLASS_PROPERTIES = { :code => [String], :variables => [Array], :naming_pars => [Array], :results => [Array], :run_info => [Array], :code_long => [String], :excluded_sub_folders => [Array], :modlet_required => [TrueClass, FalseClass], :uses_mpi => [TrueClass, FalseClass] } # These are methods that the run class must implement. They should be defined in a code module. NECESSARY_RUN_CODE_METHODS = [ :process_directory_code_specific, :print_out_line, :parameter_string, :generate_input_file, :parameter_transition, :executable_location, :executable_name ] # These are methods that the run class must implement. They should be defined in a system module. NECESSARY_RUN_SYSTEM_METHODS = [ :queue_status, :run_command, :execute, :error_file, :output_file, :cancel_job ] # These are the only permitted values for the run instance variable <tt>@status</tt>. PERMITTED_STATI = [:Unknown, :Complete, :Incomplete, :NotStarted, :Failed, :Queueing, :Running, :Held] include Log # Log.log_file = nil # Dir.pwd + "/.cr_logfile.txt" # puts Log.log_file, 'hello' Log.clean_up attr_accessor :run_list, :phantom_run_list, :combined_run_list, :ids, :phantom_ids, :combined_ids, :current_status, :run_class, :requests, :current_request, :root_folder, :print_out_size, :cache, :modlet, :code, :executable, :defaults_file attr_reader :max_id, :maxes, :cmaxes, :mins, :cmins, :start_id # Instantiate a new runner. The root folder contains a set of simulations, each of which has a unique ID. There is a one-to-one correspondence between a runner and a root folder: no two runners should ever be given the same root folder in the same script (there are safeguards to prevent this causing much trouble, but it should still be avoided on philosophical grounds), and no runner should be given a folder which has more than one set of simulations within it (as these simulations will contain duplicate IDs). # # # Options is a hash whose keys may be any of the keys of the constant <tt>DEFAULT_RUNNER_OPTIONS</tt>. I.e. to see what options can be passed: # # p CodeRunner::DEFAULT_RUNNER_OPTIONS.keys def initialize(root_folder, options={}) logf :initialize raise CRFatal.new("System not defined") unless SYS root_folder.sub!(/~/, ENV['HOME']) @root_folder = root_folder read_defaults options.each do |key,value| key = LONG_TO_SHORT.key(key) if LONG_TO_SHORT.key(key) set(key, value) if value end # ep options log 'modlet in initialize', @modlet @version= options[:version] # ep 'ex', @executable @run_class = setup_run_class(@code, modlet: @modlet, version: @version, executable: @executable) @cache = {} @n_checks = 0 @print_out_size = 0 @run_list = {}; @ids = [] set_max_id(0) @phantom_run_list = {}; @phantom_ids = [] @phantom_id = -1 @combined_run_list = {}; @combined_ids = [] @current_request = nil @requests = [] @pids= [] @maxes = {}; @mins = {} @cmaxes = {}; @cmins = {} end # Read the default values of runner options from the constant hash <tt>CodeRunner::DEFAULT_RUNNER_OPTIONS</tt>. This hash usually contains options set from the command line, but it can have its values edited manually in a script. # # Also calls read_folder_defaults. def read_defaults DEFAULT_RUNNER_OPTIONS.each{|key,value| set(key, value)} #ep DEFAULT_RUNNER_OPTIONS, @multiple_processes read_folder_defaults end # Increase the value of <tt>@max_id</tt> by 1. def increment_max_id @max_id +=1 end # Return an array of runs (run_list.values) def runs run_list.values end # Set the max_id. If the number given is lower than start_id, start_id is used. Use with extreme caution... if you set max_id to be lower than the highest run id, you may end up with duplicate ids. def set_max_id(number) # :doc: # ep 'MAXES', @max_id, number, @start_id, 'END' @max_id = @start_id ? [@start_id, number].max : number end private :set_max_id # The defaults that are saved in the root folder FOLDER_DEFAULTS = [:code, :modlet, :executable, :defaults_file, :project] # Read any default options contained in the file <tt>.code_runner_script_defaults.rb</tt> in the root folder. def read_folder_defaults # p @root_folder + '/.code_runner_script_defaults.rb' if ENV['CODE_RUNNER_READONLY_DEFAULTS'] hash = eval(File.read(@root_folder + '/.code_runner_script_defaults.rb')) FOLDER_DEFAULTS.each do |var| set(var, hash[var]) if hash[var] end else Hash.phoenix(@root_folder + '/.code_runner_script_defaults.rb') do |hash| # ep hash FOLDER_DEFAULTS.each do |var| # p send(var), hash[var] hash[var] = (send(var) or hash[var]) hash[:code_runner_version] ||= CodeRunner::CODE_RUNNER_VERSION.to_s set(var, hash[var]) end @start_id = hash[:start_id] if hash[:start_id] # ep "start_id: #@start_id" hash end end raise "No default information exists for this folder. If you are running CodeRunner from the commmand line please run again with the -C <code> and -X <executable> (and -m <modlet>, if required) flag (you only need to specify these flags once in each folder). Else, please specify :code and :executable (and :modlet if required) as options in CodeRunner.new(folder, options)" unless @code and @executable end # Here we redefine the inspect function p to raise an error if anything is written to standard out # while in server mode. This is because the server mode uses standard out to communicate # and writing to standard out can break it. All messages, debug information and so on, should always # be written to standard error. def p(*args) if @server raise "Writing to stdout in server mode will break things!" else super(*args) end end # Here we redefine the function puts to raise an error if anything is written to standard out # while in server mode. This is because the server mode uses standard out to communicate # and writing to standard out can break it. All messages, debug information and so on, should always # be written to standard error. def puts(*args) if @server raise "Writing to stdout in server mode will break things!" else super(*args) end end # Here we redefine the function print to raise an error if anything is written to standard out # while in server mode. This is because the server mode uses standard out to communicate # and writing to standard out can break it. All messages, debug information and so on, should always # be written to standard error. def print(*args) if @server raise "Writing to stdout in server mode will break things!" else super(*args) end end def self.server_dump(obj) "code_runner_server_dump_start_E#{Marshal.dump(obj)}code_runner_server_dump_end_E" end def server_dump(obj) self.class.server_dump(obj) end def set_start_id(id) raise "start_id #{id} lower than max_id #@max_id" if @max_id and id < @max_id Hash.phoenix(@root_folder + '/.code_runner_script_defaults.rb') do |hash| @start_id = hash[:start_id] = id hash end end # See CodeRunner.get_run_class_name def get_run_class_name(code, modlet) self.class.get_run_class_name(code, modlet) end # See CodeRunner.setup_run_class def setup_run_class(code, options) options[:runner] ||= self self.class.setup_run_class(code, options) end def self.old_get_run_class_name(code, modlet) # :nodoc: return modlet ? "#{code.capitalize}#{modlet.capitalize.sub(/\.rb$/, '').sub(/_(\w)/){"#$1".capitalize}}Run" : "#{code.capitalize}Run" end # Return the name of the run class according to the standard CodeRunner naming scheme. If the code name is 'a_code_name', with no modlet, the run class name will be <tt>ACodeName</tt>. If on the other hand there is a modlet called 'modlet_name', the class name will be <tt>ACodeName::ModletName</tt>. def self.get_run_class_name(code, modlet=nil) return modlet ? "#{code.capitalize}::#{modlet.capitalize.sub(/\.rb$/, '').variable_to_class_name}" : "#{code.capitalize}" end def self.repair_marshal_run_class_not_found_error(err) code, modlet = err.message.scan(/CodeRunner\:\:([A-Z][a-z0-9_]+)(?:::([A-Z]\w+))?/)[0] #ep 'merror', err, code, modlet; gets code.gsub!(/([a-z0-9])([A-Z])/, '\1_\2') (modlet.gsub!(/([a-z0-9])([A-Z])/, '\1_\2'); modlet.downcase) if modlet setup_run_class(code.downcase, modlet: modlet) end SETUP_RUN_CLASSES =[] # Create, set up and check the validity of the custom class which deals with a particular simulation code. This class will be defined in a custom module in the folder <tt>code_modules/code_name</tt>, where <tt>'code_name'</tt> is the name of the code. The only option is <tt>modlet:</tt>. # # If the custom class has already been set up, this method just returns the class. def self.setup_run_class(code, options={}) # logf(:setup_code) # log(:code, code) modlet = options[:modlet] version = options[:version] # log('modlet in setup_run_class', modlet) eputs "Loading modules for #{code}, #{modlet.inspect}..." # modlet = modlet.sub(/\.rb$/, '') if modlet raise CRFatal.new("Code must contain only lowercase letters, digits, and underscore, and must begin with a letter or underscore; it is '#{code}'") unless code =~ /\A[a-z_][a-z_\d]*\Z/ raise CRFatal.new("Input_file_module must contain only lowercase letters, digits, and underscore, and must begin with a letter or underscore; it is '#{modlet}'") if modlet and not modlet =~ /\A[a-z_][a-z_\d]*\Z/ run_class_name = get_run_class_name(code, modlet) # p run_class_name FileUtils.makedirs(ENV['HOME'] + "/.coderunner/#{code}crmod/") FileUtils.makedirs(ENV['HOME'] + "/.coderunner/#{code}crmod/defaults_files") return const_get(run_class_name) if constants.include? (run_class_name).to_sym unless options[:force] SETUP_RUN_CLASSES.push run_class_name.downcase #Create the run_class, a special dynamically created class which knows how to process runs of the given code on the current system. #run.rb contains the basic methods of the class # puts run_class_name; gets # run_class = add_a_child_class(run_class_name, "") # run_class.class_eval(%[ # @@code=#{code.inspect}; @@version=#{version.inspect} # @@modlet=#{modlet.inspect} #modlet should be nil if not @@modlet_required # SYS = #{SYS.inspect} # include Log # Log.logi(:code_just_after_runfile, @@code) # ] # ) code_module_name = SCRIPT_FOLDER+ "/code_modules/#{code}/#{code}.rb" code_module_name = "#{code}crmod" require code_module_name # ep get_run_class_name(code, nil) run_class = const_get(get_run_class_name(code, nil)) run_class.instance_variable_set(:@code, code) raise "#{run_class} must inherit from CodeRunner::Run: its ancestors are: #{run_class.ancestors}" unless run_class.ancestors.include? Run if options[:runner] run_class.runner = options[:runner] run_class.instance_variable_set(:@runner, options[:runner]) end #Add methods appropriate to the current system system_module_name = SCRIPT_FOLDER+ "/system_modules/#{SYS}.rb" require system_module_name run_class.send(:include, const_get(SYS.variable_to_class_name)) # run_class.class_eval(File.read(system_module_name), system_module_name) #Some codes require an modlet; the flag modlet_required is specified in the code module if run_class.rcp.modlet_required raise CRFatal.new("Modlet necessary and none given") unless modlet end #If a modlet is specified (modlets can also be optional) if modlet # Log.logi(:modlet, modlet) #if ( modlet_location = "#{SCRIPT_FOLDER}/code_modules/#{code}/default_modlets"; #file_name = "#{modlet_location}/#{modlet}.rb"; #FileTest.exist? file_name #) #elsif ( modlet_location = "#{SCRIPT_FOLDER}/code_modules/#{code}/my_modlets"; #file_name = "#{modlet_location}/#{modlet}.rb"; #FileTest.exist? file_name #) #else #raise CRFatal.new("Could not find modlet file: #{modlet}.rb") #end #require file_name # ep run_class.constants # ep run_class_names modlet_file = "#{code}crmod/#{modlet}.rb" #ep ['requiring modlet file'] require modlet_file run_class = recursive_const_get(run_class_name) run_class.instance_variable_set(:@modlet, modlet) end run_class.check_and_update # log("random element of variables", run_class.variables.random) # logi("run_class.variables[0] in setup_code", run_class.variables[0]) # ep 'finished' return run_class end # Traverse the directory tree below the root folder, detecting and analysing all runs within that folder. Although runs submitted by CodeRunner will all be in one folder in the root folder, it is not necessary for the runs to be organised like that. This is because CodeRunner can also be used to analyse runs which it did not submit. # # All subfolders of the root_folder will be analysed, except for ones specified in the run class property <tt>excluded_sub_folders</tt>, or those containing the hidden file '.CODE_RUNNER_IGNORE_THIS_DIRECTORY' def traverse_directories # :doc: string = "" #ep 'traversing', Dir.pwd if FileTest.exist?("code_runner_info.rb") or FileTest.exist?("CODE_RUNNER_INPUTS") or FileTest.exist?("README") or @heuristic_analysis and (Dir.entries(Dir.pwd).find{|file| not [".","..","data.txt"].include? file and File.file? file} and not Dir.entries(Dir.pwd).include? '.CODE_RUNNER_IGNORE_THIS_DIRECTORY') #i.e. if there are some files in this directory (not just directories) eprint '.' if @write_status_dots begin raise CRMild.new("must recalc all") if @recalc_all or @reprocess_all #must recalculate the run results, not load them if @@recalc_all run = @run_class.load(Dir.pwd, self) #NB this doesn't always return an object of class run_class - since the run may actually be from a different code raise CRMild.new("not complete: must recalc") unless run.status == :Complete or run.status == :Failed raise CRMild.new("Not the right directory, must recalc") unless run.directory == Dir.pwd rescue ArgumentError, CRMild => err if err.class == ArgumentError unless err.message =~ /marshal data too short/ #puts err #puts err.backtrace raise err end end log(err) # puts err.class begin #interrupted = false; #old_trap2 = trap(2){} #old_trap2 = trap(2){eputs "Interrupt acknowledged...#{Dir.pwd} finishing folder analyis. Interrupt again to override (may cause file corruption)."; interrupted = true} run = @run_class.new(self).process_directory #NB this doesn't always return an object of class run_class - since the run may actually be from a different code #trap(2, old_trap2) #(eputs "Calling old interrupt #{Dir.pwd}"; Process.kill(2, 0)) if interrupted rescue => err log(err) unless @heuristic_analysis and (err.class == CRMild or err.class == CRError) # puts Dir.pwd logd eputs Dir.pwd eputs err.class eputs err # eputs err.backtrace eputs "----Only allowed to fail processing a directory if a heuristic analysis is being run" raise err end # puts err.class run = nil # puts @requests end end check = false if run # puts run.id, @run_list[run.id]; gets # raise CRFatal.new("\n\n-----Duplicate run ids: #{run.directory} and #{@run_list[run.id].directory}----") if @run_list[run.id] if @run_list[run.id] check = true raise <<EOF Duplicate run ids: New: #{run.run_name} #{run.status} in #{run.directory} Old: #{@run_list[run.id].run_name} #{@run_list[run.id].status} in #{@run_list[run.id].directory} EOF choice = Feedback.get_choice("Which do you want to keep, new or old? (The other folder will be deleted. Press Ctrl+C to cancel and sort the problem out manually)", ["New", "Old"]) case choice when /New/ raise "Aborting... this function has not been fully tested" FileUtils.rm_r(@run_list[run.id].directory) when /Old/ raise "Aborting... this function has not been fully tested" FileUtils.rm_r(run.directory) run = nil end end end if run (puts "you shouldn't see this if you chose old"; gets) if check run.save @run_list[run.id] = run @ids.push run.id @ids = @ids.uniq.sort @max_id = @max_id>run.id ? @max_id : run.id end if @heuristic_analysis Dir.foreach(Dir.pwd)do |directory| next if [".",".."].include? directory or File.file? directory or directory =~ /\.rb/ or @run_class.rcp.excluded_sub_folders.include? directory # begin Dir.chdir(directory) do traverse_directories end # rescue Errno::ENOENT # log Dir.entries # puts directory + " was not a directory" # end end end else Dir.foreach(Dir.pwd)do |directory| next if [".",".."].include? directory or File.file? directory or directory =~ /\.rb/ or @run_class.rcp.excluded_sub_folders.include? directory # begin Dir.chdir(directory) do traverse_directories end # rescue Errno::ENOENT # log Dir.entries # puts directory + " was not a directory" # end end end end private :traverse_directories # Write out a simple datafile containing all the inputs and outputs listed in the run class property <tt>readout_string</tt>. What is actually written out can be customised by redefining the method <tt>data_string</tt> in the run class, or changing <tt>readout_string</tt> or both. def write_data(filename = "data.txt") logf(:write_data) generate_combined_ids File.open(filename, "w") do |file| @combined_ids.each do |id| run = @combined_run_list[id] if run.status =~ /Complete/ data_string = run.data_string raise CRFatal.new("data_string did not return a string") unless data_string.class == String file.puts data_string end end end end # Sort the runs according to the variable <tt>@sort</tt> which can be either whitespace separated string or an array of strings. In the former case, the string is split to form an array of strings, using the separator <tt>/\s+/</tt>. For example, if # # @sort == ['height', '-weight', 'colour'] # # Then the runs will be sorted according to first height, then (descending) weight, then colour. What actually happens is that the variable <tt>@ids</tt> is sorted, rather than <tt>@run_list</tt>. For this to work, height, weight and colour must be either variables or results or instance methods of the run class. # # Type can be either '' or 'phantom', in which case the variable sorted will be either <tt>@ids</tt> or <tt>@phantom_ids</tt> respectively. def sort_runs(type = @use_phantom.to_s.sub(/real/, '')) logf(:sort_runs) log(:type, type) #ep 'sort', @sort #sort_list = @sort ? (@sort.class == String ? eval(@sort) : @sort) : [] run_list_name = [type.to_s, 'run_list'].join('_').gsub(/^_/, '') ids_name = [type.to_s, 'ids'].join('_').gsub(/^_/, '') log run_list_name set(ids_name, send(ids_name).sort_by do |id| run = send(run_list_name)[id] sortkey = run.instance_eval((@sort or '[]')) #ep 'sortkey', sortkey sortkey #sort_list.map{|str| run.instance_eval(str)} end) end # Print out a summary of all the runs in the root folder, formatted in nice pretty colours. Since this is often called in a loop, if called twice without any arguments it will erase the first printout. To stop this happening set rewind to 0. If the command is being issued not in a terminal, so that CodeRunner cannot determine the size of the terminal, the second argument must be passed as an array of [rows, columns]. def print_out(rewind = nil, options={}) # terminal_size = [rows, cols] rewind ||= @print_out_size terminal_size = options[:terminal_size] logf(:print_out) # raise CRFatal.new("terminal size must be given if this is called any where except inside a terminal (for example if yo u've called this as a subprocess)") unless terminal_size or $stdout.tty? terminal_size ||= Terminal.terminal_size #lots of gritty terminal jargon in here. Edit at your peril! unless ENV['CODE_RUNNER_NO_COLOUR']=='true' or ENV['CODE_RUNNER_NO_COLOR']=='true' dc= Terminal::WHITE # .default_colour green= Terminal::LIGHT_GREEN cyan = Terminal::CYAN bblck = Terminal::BACKGROUND_BLACK else dc= ""# Terminal::WHITE # .default_colour green= "" # Terminal::LIGHT_GREEN cyan = "" #Terminal::CYAN bblck = "" #Terminal::BACKGROUND_BLACK end cln = Terminal::CLEAR_LINE # print "\033[#{rewind}A" deco = '-'*terminal_size[1] Terminal.erewind(rewind) eputs "\n#{cln}\n#{cln}\n#{bblck}#{dc}#{deco}\n#{@run_class.rcp.code_long} Status:#{cln}\n#{deco}" i = 0; j=0 # i is no. of actual terminal lines; j is number of results lines # Group the lines by major sort key #@split = @sort && @sort.split(/\s+/).size > 1 ? @sort.split(/\s+/)[0].to_sym : nil @split_point = nil generate_combined_ids @combined_ids.each do |id| begin # puts id, :hello; gets @run = @combined_run_list[id] if filter # puts @run[:id], @id; gets #@new_split_point = @split ? @run.send(@split) : nil #if @split_point && @split_point != @new_split_point then eputs sprintf(" #{cln}", ""); i+=1 end #@split_point = @new_split_point eprint j%2==0 ? j%4==0 ? cyan : green : dc line = options[:with_comments] ? @run.comment_line : @run.print_out_line.chomp eprint line eputs cln # puts (line.size / Terminal.terminal_size[1]).class # puts (line.size / Terminal.terminal_size[1]) i+=((line.sub(/\w*$/, '').size-1) / terminal_size[1]).ceiling j+=1 end # raise "monkeys" rescue => err eputs err eputs err.backtrace eputs "---------------------\nUnable to print out line for this job:" eputs "run_name: #{@run.run_name}" eputs "status: #{@run.status}\n-----------------------" Terminal.reset return # raise CRFatal.new end end @print_out_size = i+7# + (@run_list.keys.find{|id| not [:Complete, :Failed].include? @run_list[id].status } ? 0 : 1) eprint dc, deco; Terminal.reset; eputs # puts # puts # puts dc # "\033[1;37m" # print 'rewind size is', rewind end # def filtered_run_list # logf :filtered_run_list # unless @use_phantom == :phantom # return @run_list.find_all{|id, run| filter(run)} # else # log 'using phantom' # return @phantom_run_list.find_all{|id, run| filter(run)} # end # end # Return a list of ids, filtered according to conditions. See CodeRunner#filter def filtered_ids(conditions=@conditions) generate_combined_ids # ep @combined_run_list.keys # sort_runs return @combined_ids.find_all{|id| filter(@combined_run_list[id], conditions)} end # Return true if # run.instance_eval(conditions) == true # and false if # run.instance_eval(conditions) == false. # performing some checks on the validity of the variable <tt>conditions</tt>. For people who are new to Ruby instance_eval means 'evaluate in the context of the run'. Generally <tt>conditions</tt> will be something like 'status == :Complete and height == 4.5 and not width == 20', where height and width might be some input parameters or results from the diminishing. def filter(run=@run, conditions=@conditions) logf(:filter) @run = run # to_instance_variables(directory) return true unless conditions # p conditions, @run.id, @run.is_phantom conditions = conditions.dup raise CRFatal.new(" ----------------------------- Conditions contain a single = sign: #{conditions} -----------------------------") if conditions =~ /[^!=<>]=[^=~<>]/ log conditions begin fil = @run.instance_eval(conditions) rescue => err eputs run.directory eputs conditions raise err end return fil end # Similar to CodeRunner#write_data, except that the readout is written to stdout, and formatted a bit. Will probably be rarely used. def readout logf(:readout) generate_combined_ids @split = @sort && @sort.split(/\s+/).size > 1 ? @sort.split(/\s+/)[0].to_sym : nil @split_point = nil string = @combined_ids.inject("") do |s, id| run = @combined_run_list[id] if run.status =~ /Complete/ and filter(run) @new_split_point = @split ? run.send(@split) : nil splitter = (@split_point and @split_point != @new_split_point) ? "\n\n" : "" @split_point = @new_split_point splitter = "" # comment to put split points back in # puts s.class, splitter.class, data_string(directory) data_string = run.data_string raise CRFatal.new("data_string did not return a string") unless data_string.class == String s + splitter + data_string else s end end # puts @max.inspect return string end # ? Probably can get rid of this one def readout_cols(*var_list) # :nodoc: logf :readout_cols ans = [[]] * var_list.size generate_combined_ids filtered_ids.each do |id| run = combined_run_list[id] var_list.each_with_index do |var, index| ans[index].push run.send(var) end end ans end # List every file in the root folder. def get_all_root_folder_contents # :nodoc: @root_folder_contents =[] Find.find(@root_folder){|file| @root_folder_contents.push file} end #Update the information about all the runs stored in the variable <tt>@run_list</tt>. By default, this is done by calling CodeRunner#traverse_directories. If, on the other hand, <tt>@use_large_cache</tt> is set to true, this is done by reading the temporary cache maintained in ".CODE_RUNNER_TEMP_RUN_LIST_CACHE" in the root folder. This is much quicker. If in addition <tt>@use_large_cache_but_recheck_incomplete</tt> is set to true, all runs whose status is not either :Complete or :Failed will be rechecked. def update(write_status_dots=true, use_large_cache=@use_large_cache, use_large_cache_but_recheck_incomplete=@use_large_cache_but_recheck_incomplete) @use_large_cache = use_large_cache logf(:update) @write_status_dots = write_status_dots @run_list={} @ids=[] @phantom_run_list = {} @phantom_ids = [] @run_store =[] # @multiple_processes_directories = [] set_max_id 0 @run_class.update_status(self) if @use_large_cache and not @recalc_all and not @reprocess_all log("using large cache") begin begin eputs 'Loading large cache...' if @write_status_dots Dir.chdir(@root_folder) do @run_list = Marshal.load(File.read(".CODE_RUNNER_TEMP_RUN_LIST_CACHE")) end @run_list.values.each{|run| run.runner = self} rescue ArgumentError => err eputs err raise err unless err.message =~ /undefined class/ #NB all code_names have to contain only lowercase letters: # modlet, code = err.message.scan(/CodeRunner\:\:([A-Z][\w+])?([A-Z]\w+)Run/)[0] code, modlet = err.message.scan(/CodeRunner\:\:([A-Z][a-z0-9_]+)(?:::([A-Z]\w+))?/)[0] # ep code.downcase, modlet modlet.downcase! if modlet setup_run_class(code.downcase, modlet: modlet) retry end # ep @run_list @ids = @run_list.keys @run_list.each{|id, run| run.runner = self } #eputs "Setting max id..." set_max_id(@ids.max || 0) #eputs "max_id = #@max_id" # puts @max_id; gets # @use_large_cache = false @ids.sort! redone_count = 0 # puts "hello" # ep @use_large_cache_but_recheck_incomplete; exit recheck_incomplete_runs if use_large_cache_but_recheck_incomplete # sort_runs eprint "Updating runs..." if @write_status_dots # get_all_root_folder_contents # puts @run_list.values[0].directory, File.expand_path(@root_folder).esc_regex fix_directories = (run_list.size > 0 and not @run_list.values[0].directory =~ File.expand_path(@root_folder).esc_regex) # eputs 'fdirectories', fix_directories # exit eputs "Fixing Directories..." if fix_directories @run_list.each do |id, run| eprint '.' if @write_status_dots run.directory = File.join(@root_folder, run.relative_directory) if fix_directories # run.directory = "#@root_folder/#{run.relative_directory}" # unless @root_folder_contents.include? run.directory# File.directory? run.directory and run.directory =~ File.expand_path(@root_folder).esc_regex # if @root_folder_contents.include?(rel = File.join(@root_folder, run.relative_directory)) # run.directory = rel # else # raise CRFatal.new("Directory #{run.directory} not found") # end # end # eputs @use_phantom #run.generate_phantom_runs #if @use_phantom.to_s =~ /phantom/i run.phantom_runs.each{|r| add_phantom_run(r)} if run.phantom_runs end eputs if @write_status_dots save_large_cache if fix_directories # puts redone_count return self rescue Errno::ENOENT, ArgumentError, TypeError => err if err.class == ArgumentError and not err.message =~ /marshal data too short/ or err.class == TypeError and not err.message =~ /incompatible marshal file format/ eputs err eputs err.backtrace raise CRFatal.new end eputs err, "Rereading run data" # @use_large_cache = false end end log("not using large cache") @run_list={} @ids=[] @phantom_run_list = {} @phantom_ids = [] @run_store =[] # @multiple_processes_directories = [] set_max_id 0 log("traversing directories") eprint 'Analysing runs..' if @write_status_dots #interrupted = false; #old_trap2 = trap(2){} #trap(2){eputs "Interrupt acknowledged... reloading saved cache. Interrupt again to override (may cause file corruption)."; trap(2, old_trap2); update(true, true, false); Process.kill(2,0)} Dir.chdir(@root_folder){traverse_directories} @max_id ||= 0 eputs # puts 'before request', @ids, @requests; respond_to_requests # @n_checks += 1 # exit if ($nruns > 0 && @n_checks > $nruns) sort_runs @recalc_all = false # pp @run_list save_large_cache #@run_list.each{|id, run| run.generate_phantom_runs} #trap(2, old_trap2) #Process.kill(2, 0) if interrupted return self end # Dump all the instance variables of the runner to stdout as Marshalled binary data. This is used for RemoteCodeRunner server functions. def marshalled_variables #ep 'marsh1' instance_vars = {} instance_variables.each do |var| instance_vars[var] = instance_variable_get(var) end instance_vars[:@run_list].values.each{|run| run.runner=nil} #Kernel.puts server_dump(instance_vars) instance_vars[:@cache]={} instance_vars[:@phantom_run_list].values.each{|run| run.runner = nil} #ep 'marsh2' #eputs instance_vars.pretty_inspect #instance_vars.each do |var, val| #ep var #eputs server_dump(val) #end instance_vars end # Write the variable <tt>@run_list</tt>, which contains all information currently known about the simulations in the root folder, as Marshalled binary data in the file ".CODE_RUNNER_TEMP_RUN_LIST_CACHE". This cache will be used later by CodeRunner#update. def save_large_cache # pp self # ep @run_list # pp @run_list.values.map{|run| run.instance_variables.map{|var| [var, run.instance_variable_get(var).class]}} generate_combined_ids @combined_run_list.each{|id, run| run.runner = nil} File.open(@root_folder + "/.CODE_RUNNER_TEMP_RUN_LIST_CACHE", 'w'){|file| file.puts Marshal.dump @run_list} @combined_run_list.each{|id, run| run.runner = self} end # Self-explanatory! Call CodeRunner::Run#process_directory for every run whose status is not either :Complete or :Failed. (Note, for historical reasons traverse_directories is called rather than CodeRunner::Run#process_directory directly but the effect is nearly the same). def recheck_incomplete_runs logf :recheck_incomplete_runs @run_class.update_status(self) redone_count = 0 run_list, @run_list = @run_list, {}; @ids = []; run_list.each do |id, run| # print id if run.status == :Complete or run.status == :Failed # print ".", id, "___" @run_list[id] = run @ids.push id else # print id, "%%%"; redone_count+=1 Dir.chdir(run.directory){traverse_directories} end end @ids.sort! # @ids = @run_list.keys set_max_id(@ids.max || 0) sort_runs respond_to_requests save_large_cache end # Self-explanatory! Call CodeRunner::Run#process_directory for every run for which CodeRunner#filter(run) is true. (Note, for historical reasons traverse_directories is called rather than CodeRunner::Run#process_directory directly but the effect is nearly the same). def recheck_filtered_runs(write_status_dots=false) @write_status_dots = write_status_dots logf :recheck_filtered_runs @run_class.update_status(self) @run_list.each do |id, run| if filter(run) and not (run.status == :Complete or run.status == :Failed) # eputs run.directory Dir.chdir(run.directory){run.process_directory} # eputs run.status # ep run end end save_large_cache # run_list, @run_list = @run_list, {}; @ids = []; @max_id = 0 # run_list.each do |id, run| # if not filter(run) or run.status == :Complete # @run_list[id] = run # @ids.push id # else # Dir.chdir(run.directory){traverse_directories} # end # end # @ids.sort! # @ids = @run_list.keys set_max_id(@ids.max || 0) sort_runs respond_to_requests save_large_cache end # One of the features of CodeRunner is two way communication between a runner and its runs. The runs can request actions from the runner directly by calling its instance methods, but often the runs want something to happen after the runner has processed every run in the directory. For example if a run wanted to check if it was resolved, it would need to know about all the other runs so it could compare itself with them. In this case it would place an instance method that it wanted to call in the variable <tt>@requests</tt> in the runner. The runner would then call that instance method on every run after it had finished processing all the runs. # # In summary, this method is called after every time the runner has checked through the directory. When it is called, it looks in the variable <tt>@requests</tt> which contains symbols representing methods. It calls each symbol as an instance method of every run in turn. So if <tt>@requests</tt> was <tt>[:check_converged]</tt> it would call <tt>run.check_converged</tt> for every run. def respond_to_requests logf(:respond_to_requests) logi(:@requests, @requests) log('@phantom_run_list.class', @phantom_run_list.class) while @requests[0] old_requests = @requests.uniq @requests = [] old_requests.each do |request| @current_request = request if request == :traverse_directories # a special case @ids = [] @run_list = {} @phantom_run_list = {} @phantom_ids = [] Dir.chdir(@root_folder){traverse_directories} else filtered_ids.each do |id| run = @run_list[id] Dir.chdir(run.directory){run.instance_eval(request.to_s); run.save; run.write_results} end end end end end # Start a simulation: submit the run that is passed. What happens is as follows: # # 1. Modify the run according to options. # 2. Check if any other processes are submitting runs in the same root folder. In this case there will be a file called 'submitting' in the folder. If there is such a file wait until it is gone. # 3. Check if a run with identical parameters has been submitted before. In which case skip submitting the run unless options[:skip] == false. # 4. Call <tt>run.submit</tt> # #Options can be any one of <tt>CodeRunner::SUBMIT_OPTIONS</tt>. The options passed here will override values stored as instance variables of the runner with the same name, which will override these values if they are set in the runs itself. For example if # run.nprocs == '32x4' # runner.nprocs == nil # options[:nprocs] == nil # the number of processes will be 32x4. On the other hand if # run.nprocs == '32x4' # runner.nprocs == '24x4' # options[:nprocs] == '48x4' # the number of processes will be 48x4. def submit(runs, options={}) eputs "System " + SYS eputs "No. Procs " + @nprocs.inspect runs = [runs] unless runs.class == Array #can pass a single run to submit outruns = runs.dup skip = true unless options[:skip] == false SUBMIT_OPTIONS.each do |option| set(option, options[option]) if options.keys.include? option end logf(:submit) Dir.chdir(@root_folder) do @skip=skip mess = false while FileTest.exist?("submitting") (eputs " Waiting for another process to finish submitting. If you know that no other CodeRunner processes are submitting in this folder (#@root_folder) then delete the file 'submitting' and try again"; mess = true) unless mess sleep rand end # old_trap = trap(0) old_trap0 = trap(0){eputs "Aborted Submit!"; File.delete("#@root_folder/submitting"); exit!} old_trap2 = trap(2){eputs "Aborted Submit!"; File.delete("#@root_folder/submitting") if FileTest.exist? "#@root_folder/submitting"; trap(2, "DEFAULT"); trap(0, "DEFAULT"); Process.kill(2, 0)} # File.open("submitting", "w"){|file| file.puts ""} FileUtils.touch("submitting") unless options[:no_update_before_submit] @use_large_cache, ulc = false, @use_large_cache; update; @use_large_cache = ulc end generate_combined_ids(:real) # old_job_nos = queue_status.scan(/^\s*(\d+)/).map{|match| match[0].to_i} script = "" if options[:job_chain] runs.each_with_index do |run, index| similar = similar_runs([], run) if @skip and similar[0] and not (options[:replace_existing] or options[:rerun]) eputs "Found similar run: #{@run_list[similar[0]].run_name}" eputs "Skipping submission..." runs[index] = nil next end unless options[:replace_existing] or options[:rerun] @max_id+=1 run.id = @max_id else if options[:replace_existing] FileUtils.rm_r run.directory elsif options[:rerun] ################# For backwards compatibility SUBMIT_OPTIONS.each do |opt| run.set(opt, send(opt)) unless run.send(opt) end ########################################### FileUtils.rm "#{run.directory}/code_runner_results.rb" FileUtils.rm "#{run.directory}/.code_runner_run_data" end @run_list.delete(run.id) @ids.delete run.id generate_combined_ids end begin unless options[:job_chain] run.prepare_submission unless options[:rerun] next if @test_submission Dir.chdir(run.directory) do old_job_nos = queue_status.scan(/^\s*(\d+)/).map{|match| match[0].to_i} ######################### The big tomale! run.job_no = run.execute # Start the simulation and get the job_number ######################### run.job_no = get_new_job_no(old_job_nos) unless run.job_no.kind_of? Integer # (if the execute command does not return the job number, look for it manually) # eputs 'run.job_no', run.job_no run.output_file = nil # reset the output file run.output_file # Sets the output_file on first call run.error_file = nil # reset the output file run.error_file # Sets the error_file on first call run.write_info eputs "Submitted run: #{run.run_name}" end else run.prepare_submission unless options[:rerun] script << "cd #{run.directory}\n" script << "#{run.run_command}\n" next if @test_submission end rescue => err File.delete("submitting") raise(err) end end # runs.each runs.compact! if options[:job_chain] and not @test_submission and runs.size > 0 FileUtils.makedirs('job_chain_files') @id_list = runs.map{|run| run.id} #@executable ||= runs[0].executable @submission_script = script # A hook... default is to do nothing @submission_script = @run_class.modify_job_script(self, runs, @submission_script) # To get out of job_chain_files folder @submission_script = "cd .. \n" + @submission_script old_job_nos = queue_status.scan(/^\s*(\d+)/).map{|match| match[0].to_i} ################ Submit the run Dir.chdir('job_chain_files'){job_no = execute} ################ job_no = get_new_job_no(old_job_nos) unless job_no.kind_of? Integer # (if the execute command does not return the job number, look for it manually) # eputs 'jobchain no', job_no #runs.each{|run| run.job_no = job_no} runs.each do |run| run.job_no = @job_no = job_no run.output_file = run.relative_directory.split("/").map{|d| ".."}.join("/") + "/job_chain_files/" + output_file run.error_file = run.relative_directory.split("/").map{|d| ".."}.join("/") + "/job_chain_files/" + error_file run.write_info eputs "Submitted run: #{run.run_name}" end end @write_status_dots, wsd = false, @write_status_dots @run_class.update_status(self) runs.each do |run| # ep run.id, run_list.keys Dir.chdir(run.directory){traverse_directories} end @write_status_dots = wsd save_large_cache File.delete("submitting") trap(0, old_trap0) trap(2, old_trap2) end # Dir.chdir(@root_folder) # eputs #ep 'runs submitted', outruns return outruns[0].id if outruns.size == 1 #used in parameter scans end # def submit def rcp @run_class.rcp end def executable_name return 'job_chain' unless @executable File.basename(@executable) end def executable_location return '' unless @executable File.dirname(@executable) end def code_run_environment run_class.new(self).code_run_environment end def run_command #ep 'submission_script', @submission_script @submission_script end private :run_command def job_identifier "#{@id_list[0]}-#{@id_list[-1]}" end #private :job_identifier # Assuming only one new job has been created, detect its job number. def get_new_job_no(old_job_nos) # :doc: #|| "" # qstat = qstat=~/\S/ ? qstat : nil job_no = nil if self.respond_to? :queue_wait_attempts ntimes = queue_wait_attempts else ntimes = 5 end eputs 'Waiting for job to appear in the queue...' ntimes.times do |i| # job_no may not appear instantly # eputs queue_status new_job_nos = queue_status.scan(/^\s*(\d+)/).map{|match| match[0].to_i} job_no = (new_job_nos-old_job_nos).sort[0] # eputs "job_no", job_no break if job_no sleep 0.2 qstat = queue_status if i == ntimes eputs 'Timeout... perhaps increase queue_wait_attempts in the system module?' end end job_no ||= -1 # some functions don't work if job_no couldn't be found, but most are ok end private :get_new_job_no # def submit # # # logi(:job_nos, job_nos) # ################## # # ################## # # eputs info_file # @sys = SYS # # end # # # else # File.delete("submitting") # raise CRFatal.new("queue_status did not return a string; submission cancelled. Suggest editing system_modules/#{SYS}.rb") # end # # end # Create a new instance of the class <tt>@run_class</tt> def new_run logf(:new_run) @run_class.new(self) end @@wait = true #Do you wait for the previous run to have completed when using simple scan? # Submit a series of runs according to scan_string. scan_string specifies a number of scans separated by hashes. Each scan has a number which is the ID of the run to start from followed by a colon. After the colon the user can write some code which modifies the original run. For example: # # simple_scan('23: @height *= 2; @weight *=1.1') # # will submit a series of runs, where each successive run has height twice the last one, and weight 1.1 times the last one, where we assume that height and weight are input parameters. # # Options are the same as CodeRunner#submit def simple_scan(scan_string, options={}) scans = scan_string.split('#') ppipe = PPipe.new(scans.size + 1, true, controller_refresh: 0.5, redirect: false) pipe_numbers = ppipe.fork(scans.size - 1) #p @run_class.naming_pars instructions = (scans[(ppipe.mpn > 0 ? ppipe.mpn - 1 : 0)]) id = instructions.scan(/^\d+\:/)[0].to_i instructions = instructions.sub(/^\d+\:/, '') @run= id > 0 ? @run_list[id] : (run = @run_class.new(self); run.update_submission_parameters((options[:parameters] or '{}')); run) @run_class.rcp.variables.each do |par| #p par, @run_class.naming_pars @run.naming_pars.push par if scan_string =~ Regexp.new(Regexp.escape(par.to_s)) end @run.naming_pars.uniq! # @run.naming_pars +== @run_class.naming_pars catch(:finished) do loop do #submit loop ppipe.synchronize(:submit) do @running = submit(@run, nprocs: options[:nprocs], version: @run_class.rcp.version) @conditions = "id == #@running" #print_out #ep 'Running run', @running end loop do # check finished loop dir = @run_list[@running].directory @run_list.delete(@running) @run_class.update_status(self) Dir.chdir(dir) do traverse_directories end unless @@wait and (@run_list[@running].status == :Incomplete or @run_list[@running].status == :NotStarted or @run_list[@running].status == :Queueing) @run.parameter_transition(@run_list[@running]) @old_run = @run_list[@running] break end #p @running ppipe.i_send(:running, @running, tp: 0) if ppipe.is_root arr = (pipe_numbers + [0]).inject([]) do |arr, pn| arr.push ppipe.w_recv(:running, fp: pn) end #p arr @conditions = "#{arr.inspect}.include? id" print_out end sleep 3 end @run.instance_eval(instructions) end end (ppipe.die; exit) unless ppipe.is_root ppipe.finish end # nprocs = options[:nprocs] # # version = options[:version] # skip = true unless options[:skip] == false # logf(:submit) # Dir.chdir(@root_folder) do # run.nprocs =nprocs; # A parameter scan array is a list of parameter_scans: # [parameter_scan, parameter_scan, ...] # A parameter_scan is a list of variable scans: # [variable_scan, variable_scan, ...] # # A variable_scan consists of a name, and a list of values; # # ['width', [0.3, 0.5, 0.6]] # # A parameter scan will scan through every possible combination of variable values, varying the final variable fastest. # # In between each run it will call the hook function parameter_transition. This allows you to adjust the input variables of the next run based on the results of the previous. # e.g. # parameter_scan_array = [ # [ # ['width', [0.3, 0.5, 0.6]], ['height', [0.5, 4.3]] # ], # [ # ['width', [7.2, 0.6]], ['height', [3.6, 12.6, 12.9, 0.26]] # ] # ] # # This will run two simultaneous parameter scans: one with 3x2 = 6 runs; one with 2x4 = 8 runs, a total of 14 runs # # Any variables not specified in the parameter scan will be given their default values. def parameter_scan(parameter_scan, parameters, options={}) skip = true unless options[:skip] == false # version= (options[:version] or "") nprocs = options[:nprocs] logf(:parameter_scan) raise CRFatal.new("Wrong directory: parameter scan being conducted in #{Dir.pwd} instead of my root folder: #{@root_folder}") unless Dir.pwd == File.expand_path(@root_folder) @skip = skip puts parameter_scan.inspect @nprocs = nprocs; @skip=skip; log '@run_class', @run_class @run = @run_class.new(self) @run.update_submission_parameters(parameters) # @running_scans = {}; @gammas = {} beginning = "catch(:finished) do \n" end_string = "\nend" parameter_scan.each do |variable_scan| beginning += %[ #{variable_scan[1].inspect}.each do |value|\n\t@run.#{variable_scan[0]} = value\n] @run_class.rcp.naming_pars.push variable_scan[0].to_sym; @run_class.rcp.naming_pars.uniq! end_string += %[\nend] end middle = <<EOF @@psppipe.synchronize(:pssubmit){@running = submit(@run, nprocs: @nprocs, version: @version, skip: @skip); update}; loop do # @@mutex.synchronize{} @run_class.update_status(self) # puts run_class.current_status Dir.chdir(@run_list[@running].directory){@run_list.delete(@running); traverse_directories} # ep @run_list[@running].status, @run_list[@running].id, @run_list[@running].job_no, queue_status unless @run_list[@running].status == :Incomplete or @run_list[@running].status == :NotStarted @run.parameter_transition(@run_list[@running]) break end sleep 3 # Thread.pass # puts Thread.current.to_s + " is looping, @run_list[@running].status = " + @run_list[@running].status.to_s + " @running = " + @running.to_s + " @run_list[@running].job_no = " + @run_list[@running].job_no.to_s end EOF command = beginning + middle + end_string puts command instance_eval(command, 'parameter_scan_code') # puts Thread.current.object_id # puts Thread.current.to_s; print " is finished" # @@psppipe.i_send(:finished, true, tp: 0) end # Find runs whose input parameters are all the same as those for <tt>run</tt>, with the exception of those listed in <tt>exclude_variables</tt> def similar_runs(exclude_variables=[], run=@run) #all runs for which variables are the same as 'run', with the exception of exclude_variables logf(:similar_runs) raise CRFatal.new("generate_combined_ids must be called before this function is called") unless (@combined_run_list.size > 0 and @combined_ids.size > 0) or @ids.size ==0 command = (run.class.rcp.variables+run.class.rcp.run_info-exclude_variables - [:output_file, :error_file, :runner, :phantom_runs]).inject("@combined_ids.find_all{|id| @combined_run_list[id].class == run.class}"){ |s,v| s + %<.find_all{|id| @combined_run_list[id].#{v}.class == #{run.send(v).inspect}.class and @combined_run_list[id].#{v} == #{run.send(v).inspect}}>} #the second send call retrieves the type conversion # log command #puts command begin similar = instance_eval(command) rescue => err log command raise err end return similar end # def max_conditional(variable,sweep=nil, conditions=nil) # logf(:max_complete) # return get_max_complete(variable,sweep, complete) == @run.id # end # # def max(variable,sweep=nil, complete=nil) # logf(:max) # return get_max(variable,sweep, complete) == @run.id # end # # def get_max(variable,sweep=nil, complete=nil) # logf :get_max # sweep ||= variable # logi @run.maxes # @run.maxes[variable] ||= {} # similar = similar_runs([sweep]) # similar = similar.find_all{|id| @combined_run_list[id].status == :Complete} if complete # logi(:similar, similar, @combined_run_list[similar[0]].send(variable)) # @run.maxes[variable][sweep] ||= similar[1] ? similar.max{|id1,id2| @combined_run_list[id1].send(variable) <=> @combined_run_list[id2].send(variable)} : @run.id # # puts "got_here" # logi("@run.maxes[#{variable}][#{sweep}]", @run.maxes[variable][sweep]) # return @run.maxes[variable][sweep] # end def get_max(run, variable,sweep, complete=nil) logf :get_max generate_combined_ids sweep = [sweep] unless sweep.class == Array similar = similar_runs(sweep, run) similar = similar.find_all{|id| @combined_run_list[id].status == :Complete} if complete logi(:similar, similar, @combined_run_list[similar[0]].send(variable)) max = similar[1] ? similar.max{|id1,id2| @combined_run_list[id1].send(variable) <=> @combined_run_list[id2].send(variable)} : similar[0] # puts "got_here" return max end def get_min(run, variable,sweep, complete=nil) logf :get_min generate_combined_ids sweep = [sweep] unless sweep.class == Array similar = similar_runs(sweep, run) similar = similar.find_all{|id| @combined_run_list[id].status == :Complete} if complete logi(:similar, similar, @combined_run_list[similar[0]].send(variable)) min = similar[1] ? similar.min{|id1,id2| @combined_run_list[id1].send(variable) <=> @combined_run_list[id2].send(variable)} : similar[0] # puts "got_here" return min end # # def get_max_conditional(variable,sweep=nil, conditions=nil) # logf(:get_max_conditional) # raise CRFatal.new("generate_combined_ids must be called before this function is called") unless @combined_run_list[0] # sweep ||= variable # similar = similar_runs([sweep]).find_all{|id| filter(@combined_run_list[id], conditions)} # similar = similar.find_all{|id| @combined_run_list[id].status == :Complete} if complete # logi(:similar, similar, @combined_run_list[similar[0]].send(variable)) # id_of_max = similar[1] ? similar.max{|id1,id2| @combined_run_list[id1].send(variable) <=> @combined_run_list[id2].send(variable)} : @run.id # # puts "got_here" # return id_of_max # end # Duplicate the runner, trying to be intelligent as far as possible in duplicating instance variables. Not fully correct yet. Avoid using at the moment. def dup logf(:dup) new_one = self.class.new(@code, @root_folder, modlet: @modlet, version: @version) new_one.ids = @ids.dup; new_one.phantom_ids = @phantom_ids.dup; new_one.run_list = @run_list.dup; new_one.phantom_run_list = @phantom_run_list.dup new_one.run_class = @run_class return new_one end # Delete the folders of all runs for whom CodeRunner#filter(run) is true. This will permanently erase the runs. This is an interactive method which asks for confirmation. def destroy(options={}) ids = @ids.find_all{|id| filter @run_list[id]} unless options[:no_confirm] logf(:destroy) puts "About to delete:" ids.each{|id| eputs @run_list[id].run_name} return unless Feedback.get_boolean("You are about to DESTROY #{ids.size} jobs. There is no way back. All data will be eliminated. Please confirm the delete.") #gets eputs "Please confirm again. Press Enter to confirm, Ctrl + C to cancel" gets end ids.each{|id| FileUtils.rm_r @run_list[id].directory if @run_list[id].directory and not ["", ".", ".."].include? @run_list[id].directory @run_list.delete(id); @ids.delete(id); generate_combined_ids} set_max_id(@ids.max || 0) save_large_cache generate_combined_ids end # Cancel the job with the given ID. Options are: # :no_confirm ---> true or false, cancel without asking for confirmation if true # :delete ---> if (no_confirm and delete), delete cancelled run def cancel_job(id, options={}) @run=@run_list[id] raise "Run with id #{id} does not exist" unless @run unless options[:no_confirm] eputs "Cancelling job: #{@run.job_no}: #{@run.run_name}. \n Press enter to confirm" # puts 'asfda' gets end @run.cancel_job if options[:no_confirm] delete = options[:delete] else delete = Feedback.get_boolean("Do you want to delete the folder (#{@run.directory}) as well?") end FileUtils.rm_r(@run.directory) if delete and @run.directory and not @run.directory == "" update print_out end # Needs to be fixed. # def rename_variable(old, new) # puts "Please confirm complete renaming of #{old} to #{new}" # gets # @run_list.each do |directory| # Dir.chdir directory[:directory] do # begin # @readme = File.read("CODE_RUNNER_INPUTS") # rescue Errno::ENOENT => err # # puts err, err.class # @readme = File.read("README") # end # @readme.sub!(Regexp.new("^\s+#{old}:"), "^\s+#{new}:") # File.open("CODE_RUNNER_INPUTS_TEST", 'w'){|file| file.puts @readme} # end # end # old_recalc, @recalc_all = @recalc_all, true # update # @recalc_all = old_recalc # end def add_phantom_run(run) @phantom_run_list[@phantom_id] = run @phantom_ids.push @phantom_id #run.real_id = run.id run.id = @phantom_id @phantom_id += -1 end def generate_combined_ids(kind= nil) logf(:generate_combined_ids) # case purpose # when :print_out # @combined_ids = [] # @combined_ids += @phantom_ids if @run_class.print_out_phantom_run_list # @combined_ids += @ids if @run_class.print_out_real_run_list # when :readout # @combined_ids = [] # @combined_ids += @phantom_ids if @run_class.readout_phantom_run_list # @combined_ids += @ids if @run_class.readout_real_run_list # when :submitting # @combined_ids = @ids kind ||= @use_phantom case kind when :real @combined_ids = @ids when :phantom @combined_ids = @phantom_ids when :both @combined_ids = @ids + @phantom_ids else raise CRFatal.new("Bad use phantom variable: #{kind.inspect}") end log('@phantom_run_list.class', @phantom_run_list.class) #puts 'crlist', @phantom_run_list.keys, @run_list.keys @combined_run_list = @phantom_run_list + @run_list log(:kind, kind) # log(:combined_ids, @combined_ids) sort_runs(:combined) end def save_all save_large_cache @run_list.values.each do |run| run.save run.write_results end end def save_all_and_overwrite_info save_all @run_list.values.each do |run| run.write_info end end private :save_all_and_overwrite_info # Permanently change the id of every run in the folder by adding num to them. Num can be negative unless it makes any of the ids negative. Use if you want to combine these runs with the runs in another folder, either by creating an instance of CodeRunner::Merge, or by directly copying and pasting the run folders. def alter_ids(num, options={}) Dir.chdir(@root_folder) do return unless options[:no_confirm] or Feedback.get_boolean("This will permanently alter all the ids in the folder #@root_folder. Scripts that use those ids may be affected. Do you wish to continue?") raise ArgumentError.new("Cannot have negative ids") if @run_list.keys.min + num < 0 runs = @run_list.values fids = filtered_ids @run_list = {} runs.each do |run| old_id = run.id if fids.include? old_id run.id += num old_dir = run.relative_directory new_dir = old_dir.sub(Regexp.new("id_#{old_id}(\\D|$)")){"id_#{run.id}#$1"} # ep old_dir, new_dir FileUtils.mv(old_dir, new_dir) run.relative_directory = new_dir run.directory = File.expand_path(new_dir) end @run_list[run.id] = run end @ids = @run_list.keys set_max_id(@ids.max || 0) save_all_and_overwrite_info end end def continue_in_new_folder(folder, options={}) Dir.chdir(@root_folder) do raise "Folder already exists" if FileTest.exist?(folder) FileUtils.makedirs("#{folder}/v") #FileUtils.makedirs(folder) FileUtils.cp(".code_runner_script_defaults.rb", "#{folder}/.code_runner_script_defaults.rb") FileUtils.cp(".code-runner-irb-save-history", "#{folder}/.code-runner-irb-save-history") FileUtils.cp("#{@defaults_file}_defaults.rb", "#{folder}/#{@defaults_file}_defaults.rb") if options[:copy_ids] options[:copy_ids].each do |id| FileUtils.cp_r(@run_list[id].directory, "#{folder}/v/id_#{id}") end end end end # Create a tar archive of the root folder and all the files in it. Options are # :compression => true or false # :folder => folder in which to place the archive. # :verbose => true or false # :group => group of new files # def create_archive(options={}) verbose = options[:verbose] ? 'v' : '' very_verbose = options[:very_verbose] ? 'v' : '' comp = options[:compression] Dir.chdir(@root_folder) do temp_root = ".tmparch/#{File.basename(@root_folder)}" FileUtils.makedirs(temp_root) system "chgrp #{options[:group]} #{temp_root}" if options[:group] size=@run_list.size @run_list.values.each_with_index do |run, index| archive_name = "#{File.basename(run.directory)}.tar#{comp ? '.gz' : ''}" tar_name = archive_name.delsubstr('.gz') relative = run.directory.delete_substrings(@root_folder, File.basename(run.directory)) FileUtils.makedirs(temp_root + relative) unless FileTest.exist? temp_root + relative + archive_name eputs "Archiving #{index} out of #{size}" if options[:verbose] Dir.chdir(run.directory + '/..') do command = "tar -cW#{very_verbose}f #{tar_name} #{File.basename(run.directory)}" eputs command if options[:verbose] unless system command raise "Archiving failed" end break unless comp command = "gzip -4 -vf #{tar_name}" eputs command if options[:verbose] unless system command raise "Compression failed" end command = "gzip -t #{archive_name}" eputs command if options[:verbose] unless system command raise "Compression failed" end #exit end FileUtils.mv(relative.delsubstr('/') + archive_name, temp_root + '/' + relative + archive_name) end system "chgrp -R #{options[:group]} #{temp_root}" if options[:group] end Dir.entries.each do |file| case file when '.', '..', '.tmparch' next when /^v/ next unless File.file? file else FileUtils.cp_r(file, "#{temp_root}/#{file}") end end Dir.chdir('.tmparch') do command = "tar -cWv --remove-files -f #{File.basename(@root_folder)}.tar #{File.basename(@root_folder)}" command = "tar -cWv -f #{File.basename(@root_folder)}.tar #{File.basename(@root_folder)}" eputs command if options[:verbose] raise "Archiving Failed" unless system command end FileUtils.mv(".tmparch/#{File.basename(@root_folder)}.tar", "#{File.basename(@root_folder)}.tar") #FileUtils.rm_r(".tmparch") end end end [ "/graphs_and_films.rb", "/remote_code_runner.rb", "/merged_code_runner.rb", '/run.rb', '/heuristic_run_methods.rb', ].each do |file| file = CodeRunner::SCRIPT_FOLDER + file require file eprint '.' unless $has_put_startup_message_for_code_runner end
module JiraRest VERSION = "0.1.1" end Update version.rb module JiraRest VERSION = "0.1." + ENV['TRAVIS_BUILD_NUMBER'] end
require 'jsonapi/callbacks' module JSONAPI class Resource include Callbacks @@resource_types = {} attr_reader :context attr_reader :model define_jsonapi_resources_callbacks :create, :update, :remove, :save, :create_to_many_link, :replace_to_many_links, :create_to_one_link, :replace_to_one_link, :replace_polymorphic_to_one_link, :remove_to_many_link, :remove_to_one_link, :replace_fields def initialize(model, context = nil) @model = model @context = context end def id model.public_send(self.class._primary_key) end def is_new? id.nil? end def change(callback) completed = false if @changing run_callbacks callback do completed = (yield == :completed) end else run_callbacks is_new? ? :create : :update do @changing = true run_callbacks callback do completed = (yield == :completed) end completed = (save == :completed) if @save_needed || is_new? end end return completed ? :completed : :accepted end def remove run_callbacks :remove do _remove end end def create_to_many_links(relationship_type, relationship_key_values) change :create_to_many_link do _create_to_many_links(relationship_type, relationship_key_values) end end def replace_to_many_links(relationship_type, relationship_key_values) change :replace_to_many_links do _replace_to_many_links(relationship_type, relationship_key_values) end end def replace_to_one_link(relationship_type, relationship_key_value) change :replace_to_one_link do _replace_to_one_link(relationship_type, relationship_key_value) end end def replace_polymorphic_to_one_link(relationship_type, relationship_key_value, relationship_key_type) change :replace_polymorphic_to_one_link do _replace_polymorphic_to_one_link(relationship_type, relationship_key_value, relationship_key_type) end end def remove_to_many_link(relationship_type, key) change :remove_to_many_link do _remove_to_many_link(relationship_type, key) end end def remove_to_one_link(relationship_type) change :remove_to_one_link do _remove_to_one_link(relationship_type) end end def replace_fields(field_data) change :replace_fields do _replace_fields(field_data) end end # Override this on a resource instance to override the fetchable keys def fetchable_fields self.class.fields end # Override this on a resource to customize how the associated records # are fetched for a model. Particularly helpful for authorization. def records_for(relation_name, _options = {}) model.public_send relation_name end private def save run_callbacks :save do _save end end # Override this on a resource to return a different result code. Any # value other than :completed will result in operations returning # `:accepted` # # For example to return `:accepted` if your model does not immediately # save resources to the database you could override `_save` as follows: # # ``` # def _save # super # return :accepted # end # ``` def _save unless @model.valid? fail JSONAPI::Exceptions::ValidationErrors.new(self) end if defined? @model.save saved = @model.save fail JSONAPI::Exceptions::SaveFailed.new unless saved else saved = true end @save_needed = !saved :completed end def _remove @model.destroy :completed end def _create_to_many_links(relationship_type, relationship_key_values) relationship = self.class._relationships[relationship_type] relationship_key_values.each do |relationship_key_value| related_resource = relationship.resource_klass.find_by_key(relationship_key_value, context: @context) relation_name = relationship.relation_name(context: @context) # TODO: Add option to skip relations that already exist instead of returning an error? relation = @model.public_send(relation_name).where(relationship.primary_key => relationship_key_value).first if relation.nil? @model.public_send(relation_name) << related_resource.model else fail JSONAPI::Exceptions::HasManyRelationExists.new(relationship_key_value) end end :completed end def _replace_to_many_links(relationship_type, relationship_key_values) relationship = self.class._relationships[relationship_type] send("#{relationship.foreign_key}=", relationship_key_values) @save_needed = true :completed end def _replace_to_one_link(relationship_type, relationship_key_value) relationship = self.class._relationships[relationship_type] send("#{relationship.foreign_key}=", relationship_key_value) @save_needed = true :completed end def _replace_polymorphic_to_one_link(relationship_type, key_value, key_type) relationship = self.class._relationships[relationship_type.to_sym] model.public_send("#{relationship.foreign_key}=", key_value) model.public_send("#{relationship.polymorphic_type}=", key_type.to_s.classify) @save_needed = true :completed end def _remove_to_many_link(relationship_type, key) @model.public_send(relationship_type).delete(key) :completed end def _remove_to_one_link(relationship_type) relationship = self.class._relationships[relationship_type] send("#{relationship.foreign_key}=", nil) @save_needed = true :completed end def _replace_fields(field_data) field_data[:attributes].each do |attribute, value| begin send "#{attribute}=", value @save_needed = true rescue ArgumentError # :nocov: Will be thrown if an enum value isn't allowed for an enum. Currently not tested as enums are a rails 4.1 and higher feature raise JSONAPI::Exceptions::InvalidFieldValue.new(attribute, value) # :nocov: end end field_data[:to_one].each do |relationship_type, value| if value.nil? remove_to_one_link(relationship_type) else case value when Hash replace_polymorphic_to_one_link(relationship_type.to_s, value.fetch(:id), value.fetch(:type)) else replace_to_one_link(relationship_type, value) end end end if field_data[:to_one] field_data[:to_many].each do |relationship_type, values| replace_to_many_links(relationship_type, values) end if field_data[:to_many] :completed end class << self def inherited(base) base.abstract(false) base._attributes = (_attributes || {}).dup base._relationships = (_relationships || {}).dup base._allowed_filters = (_allowed_filters || Set.new).dup type = base.name.demodulize.sub(/Resource$/, '').underscore base._type = type.pluralize.to_sym base.attribute :id, format: :id check_reserved_resource_name(base._type, base.name) end def resource_for(type) resource_name = JSONAPI::Resource._resource_name_from_type(type) resource = resource_name.safe_constantize if resource_name if resource.nil? fail NameError, "JSONAPI: Could not find resource '#{type}'. (Class #{resource_name} not found)" end resource end attr_accessor :_attributes, :_relationships, :_allowed_filters, :_type, :_paginator def create(context) new(create_model, context) end def create_model _model_class.new end def routing_options(options) @_routing_resource_options = options end def routing_resource_options @_routing_resource_options ||= {} end # Methods used in defining a resource class def attributes(*attrs) options = attrs.extract_options!.dup attrs.each do |attr| attribute(attr, options) end end def attribute(attr, options = {}) check_reserved_attribute_name(attr) if (attr.to_sym == :id) && (options[:format].nil?) ActiveSupport::Deprecation.warn('Id without format is no longer supported. Please remove ids from attributes, or specify a format.') end @_attributes ||= {} @_attributes[attr] = options define_method attr do @model.public_send(attr) end unless method_defined?(attr) define_method "#{attr}=" do |value| @model.public_send "#{attr}=", value end unless method_defined?("#{attr}=") end def default_attribute_options { format: :default } end def relationship(*attrs) options = attrs.extract_options! klass = case options[:to] when :one Relationship::ToOne when :many Relationship::ToMany else #:nocov:# fail ArgumentError.new('to: must be either :one or :many') #:nocov:# end _add_relationship(klass, *attrs, options.except(:to)) end def has_one(*attrs) _add_relationship(Relationship::ToOne, *attrs) end def has_many(*attrs) _add_relationship(Relationship::ToMany, *attrs) end def model_name(model) @_model_name = model.to_sym end def filters(*attrs) @_allowed_filters.merge!(attrs.inject({}) { |h, attr| h[attr] = {}; h }) end def filter(attr, *args) @_allowed_filters[attr.to_sym] = args.extract_options! end def primary_key(key) @_primary_key = key.to_sym end # TODO: remove this after the createable_fields and updateable_fields are phased out # :nocov: def method_missing(method, *args) if method.to_s.match /createable_fields/ ActiveSupport::Deprecation.warn('`createable_fields` is deprecated, please use `creatable_fields` instead') creatable_fields(*args) elsif method.to_s.match /updateable_fields/ ActiveSupport::Deprecation.warn('`updateable_fields` is deprecated, please use `updatable_fields` instead') updatable_fields(*args) else super end end # :nocov: # Override in your resource to filter the updatable keys def updatable_fields(_context = nil) _updatable_relationships | _attributes.keys - [:id] end # Override in your resource to filter the creatable keys def creatable_fields(_context = nil) _updatable_relationships | _attributes.keys end # Override in your resource to filter the sortable keys def sortable_fields(_context = nil) _attributes.keys end def fields _relationships.keys | _attributes.keys end def resolve_relationship_names_to_relations(resource_klass, model_includes, options = {}) case model_includes when Array return model_includes.map do |value| resolve_relationship_names_to_relations(resource_klass, value, options) end when Hash model_includes.keys.each do |key| relationship = resource_klass._relationships[key] value = model_includes[key] model_includes.delete(key) model_includes[relationship.relation_name(options)] = resolve_relationship_names_to_relations(relationship.resource_klass, value, options) end return model_includes when Symbol relationship = resource_klass._relationships[model_includes] return relationship.relation_name(options) end end def apply_includes(records, options = {}) include_directives = options[:include_directives] if include_directives model_includes = resolve_relationship_names_to_relations(self, include_directives.model_includes, options) records = records.includes(model_includes) end records end def apply_pagination(records, paginator, order_options) records = paginator.apply(records, order_options) if paginator records end def apply_sort(records, order_options) if order_options.any? records.order(order_options) else records end end def apply_filter(records, filter, value, _options = {}) records.where(filter => value) end def apply_filters(records, filters, options = {}) required_includes = [] if filters filters.each do |filter, value| if _relationships.include?(filter) if _relationships[filter].is_a?(JSONAPI::Relationship::ToMany) required_includes.push(filter.to_s) records = apply_filter(records, "#{filter}.#{_relationships[filter].primary_key}", value, options) else records = apply_filter(records, "#{_relationships[filter].foreign_key}", value, options) end else records = apply_filter(records, filter, value, options) end end end if required_includes.any? records = apply_includes(records, options.merge(include_directives: IncludeDirectives.new(required_includes))) end records end def filter_records(filters, options, records = records(options)) records = apply_filters(records, filters, options) apply_includes(records, options) end def sort_records(records, order_options) apply_sort(records, order_options) end def find_count(filters, options = {}) filter_records(filters, options).count(:all) end # Override this method if you have more complex requirements than this basic find method provides def find(filters, options = {}) context = options[:context] records = filter_records(filters, options) sort_criteria = options.fetch(:sort_criteria) { [] } order_options = construct_order_options(sort_criteria) records = sort_records(records, order_options) records = apply_pagination(records, options[:paginator], order_options) resources = [] records.each do |model| resources.push new(model, context) end resources end def find_by_key(key, options = {}) context = options[:context] records = records(options) records = apply_includes(records, options) model = records.where({_primary_key => key}).first fail JSONAPI::Exceptions::RecordNotFound.new(key) if model.nil? new(model, context) end # Override this method if you want to customize the relation for # finder methods (find, find_by_key) def records(_options = {}) _model_class end def verify_filters(filters, context = nil) verified_filters = {} filters.each do |filter, raw_value| verified_filter = verify_filter(filter, raw_value, context) verified_filters[verified_filter[0]] = verified_filter[1] end verified_filters end def is_filter_relationship?(filter) filter == _type || _relationships.include?(filter) end def verify_filter(filter, raw, context = nil) filter_values = [] filter_values += CSV.parse_line(raw) unless raw.nil? || raw.empty? if is_filter_relationship?(filter) verify_relationship_filter(filter, filter_values, context) else verify_custom_filter(filter, filter_values, context) end end def key_type(key_type) @_resource_key_type = key_type end def resource_key_type @_resource_key_type || JSONAPI.configuration.resource_key_type end def verify_key(key, context = nil) key_type = resource_key_type verification_proc = case key_type when :integer -> (key, context) { begin return key if key.nil? Integer(key) rescue raise JSONAPI::Exceptions::InvalidFieldValue.new(:id, key) end } when :string -> (key, context) { return key if key.nil? if key.to_s.include?(',') raise JSONAPI::Exceptions::InvalidFieldValue.new(:id, key) else key end } when :uuid -> (key, context) { return key if key.nil? if key.to_s.match(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/) key else raise JSONAPI::Exceptions::InvalidFieldValue.new(:id, key) end } else key_type end verification_proc.call(key, context) rescue raise JSONAPI::Exceptions::InvalidFieldValue.new(:id, key) end # override to allow for key processing and checking def verify_keys(keys, context = nil) return keys.collect do |key| verify_key(key, context) end end # override to allow for custom filters def verify_custom_filter(filter, value, _context = nil) [filter, value] end # override to allow for custom relationship logic, such as uuids, multiple keys or permission checks on keys def verify_relationship_filter(filter, raw, _context = nil) [filter, raw] end # quasi private class methods def _attribute_options(attr) default_attribute_options.merge(@_attributes[attr]) end def _updatable_relationships @_relationships.map { |key, _relationship| key } end def _relationship(type) type = type.to_sym @_relationships[type] end def _model_name @_model_name ||= name.demodulize.sub(/Resource$/, '') end def _primary_key @_primary_key ||= _model_class.respond_to?(:primary_key) ? _model_class.primary_key : :id end def _as_parent_key @_as_parent_key ||= "#{_type.to_s.singularize}_id" end def _allowed_filters !@_allowed_filters.nil? ? @_allowed_filters : { id: {} } end def _resource_name_from_type(type) class_name = @@resource_types[type] if class_name.nil? class_name = "#{type.to_s.underscore.singularize}_resource".camelize @@resource_types[type] = class_name end return class_name end def _paginator @_paginator ||= JSONAPI.configuration.default_paginator end def paginator(paginator) @_paginator = paginator end def abstract(val = true) @abstract = val end def _abstract @abstract end def _model_class return nil if _abstract return @model if @model @model = _model_name.to_s.safe_constantize warn "[MODEL NOT FOUND] Model could not be found for #{self.name}. If this a base Resource declare it as abstract." if @model.nil? @model end def _allowed_filter?(filter) !_allowed_filters[filter].nil? end def module_path @module_path ||= name =~ /::[^:]+\Z/ ? ($`.freeze.gsub('::', '/') + '/').underscore : '' end def construct_order_options(sort_params) return {} unless sort_params sort_params.each_with_object({}) do |sort, order_hash| field = sort[:field] == 'id' ? _primary_key : sort[:field] order_hash[field] = sort[:direction] end end private def check_reserved_resource_name(type, name) if [:ids, :types, :hrefs, :links].include?(type) warn "[NAME COLLISION] `#{name}` is a reserved resource name." return end end def check_reserved_attribute_name(name) # Allow :id since it can be used to specify the format. Since it is a method on the base Resource # an attribute method won't be created for it. if [:type, :href, :links, :model].include?(name.to_sym) warn "[NAME COLLISION] `#{name}` is a reserved key in #{@@resource_types[_type]}." end end def check_reserved_relationship_name(name) if [:id, :ids, :type, :types, :href, :hrefs, :link, :links].include?(name.to_sym) warn "[NAME COLLISION] `#{name}` is a reserved relationship name in #{@@resource_types[_type]}." end end def _add_relationship(klass, *attrs) options = attrs.extract_options! options[:module_path] = module_path attrs.each do |attr| check_reserved_relationship_name(attr) # Initialize from an ActiveRecord model's properties if _model_class && _model_class.ancestors.collect{|ancestor| ancestor.name}.include?('ActiveRecord::Base') model_association = _model_class.reflect_on_association(attr) if model_association options[:class_name] ||= model_association.class_name end end @_relationships[attr] = relationship = klass.new(attr, options) associated_records_method_name = case relationship when JSONAPI::Relationship::ToOne then "record_for_#{attr}" when JSONAPI::Relationship::ToMany then "records_for_#{attr}" end foreign_key = relationship.foreign_key define_method "#{foreign_key}=" do |value| @model.method("#{foreign_key}=").call(value) end unless method_defined?("#{foreign_key}=") define_method associated_records_method_name do relation_name = relationship.relation_name(context: @context) records_for(relation_name, context: @context) end unless method_defined?(associated_records_method_name) if relationship.is_a?(JSONAPI::Relationship::ToOne) if relationship.belongs_to? define_method foreign_key do @model.method(foreign_key).call end unless method_defined?(foreign_key) define_method attr do |options = {}| if relationship.polymorphic? associated_model = public_send(associated_records_method_name) resource_klass = Resource.resource_for(self.class.module_path + associated_model.class.to_s.underscore) if associated_model return resource_klass.new(associated_model, @context) if resource_klass else resource_klass = relationship.resource_klass if resource_klass associated_model = public_send(associated_records_method_name) return associated_model ? resource_klass.new(associated_model, @context) : nil end end end unless method_defined?(attr) else define_method foreign_key do record = public_send(associated_records_method_name) return nil if record.nil? record.public_send(relationship.resource_klass._primary_key) end unless method_defined?(foreign_key) define_method attr do |options = {}| resource_klass = relationship.resource_klass if resource_klass associated_model = public_send(associated_records_method_name) return associated_model ? resource_klass.new(associated_model, @context) : nil end end unless method_defined?(attr) end elsif relationship.is_a?(JSONAPI::Relationship::ToMany) define_method foreign_key do records = public_send(associated_records_method_name) return records.collect do |record| record.public_send(relationship.resource_klass._primary_key) end end unless method_defined?(foreign_key) define_method attr do |options = {}| resource_klass = relationship.resource_klass records = public_send(associated_records_method_name) filters = options.fetch(:filters, {}) unless filters.nil? || filters.empty? records = resource_klass.apply_filters(records, filters, options) end sort_criteria = options.fetch(:sort_criteria, {}) unless sort_criteria.nil? || sort_criteria.empty? order_options = relationship.resource_klass.construct_order_options(sort_criteria) records = resource_klass.apply_sort(records, order_options) end paginator = options[:paginator] if paginator records = resource_klass.apply_pagination(records, paginator, order_options) end return records.collect do |record| if relationship.polymorphic? resource_klass = Resource.resource_for(self.class.module_path + record.class.to_s.underscore) end resource_klass.new(record, @context) end end unless method_defined?(attr) end end end end end end Make context a required initialize parameter require 'jsonapi/callbacks' module JSONAPI class Resource include Callbacks @@resource_types = {} attr_reader :context attr_reader :model define_jsonapi_resources_callbacks :create, :update, :remove, :save, :create_to_many_link, :replace_to_many_links, :create_to_one_link, :replace_to_one_link, :replace_polymorphic_to_one_link, :remove_to_many_link, :remove_to_one_link, :replace_fields def initialize(model, context) @model = model @context = context end def id model.public_send(self.class._primary_key) end def is_new? id.nil? end def change(callback) completed = false if @changing run_callbacks callback do completed = (yield == :completed) end else run_callbacks is_new? ? :create : :update do @changing = true run_callbacks callback do completed = (yield == :completed) end completed = (save == :completed) if @save_needed || is_new? end end return completed ? :completed : :accepted end def remove run_callbacks :remove do _remove end end def create_to_many_links(relationship_type, relationship_key_values) change :create_to_many_link do _create_to_many_links(relationship_type, relationship_key_values) end end def replace_to_many_links(relationship_type, relationship_key_values) change :replace_to_many_links do _replace_to_many_links(relationship_type, relationship_key_values) end end def replace_to_one_link(relationship_type, relationship_key_value) change :replace_to_one_link do _replace_to_one_link(relationship_type, relationship_key_value) end end def replace_polymorphic_to_one_link(relationship_type, relationship_key_value, relationship_key_type) change :replace_polymorphic_to_one_link do _replace_polymorphic_to_one_link(relationship_type, relationship_key_value, relationship_key_type) end end def remove_to_many_link(relationship_type, key) change :remove_to_many_link do _remove_to_many_link(relationship_type, key) end end def remove_to_one_link(relationship_type) change :remove_to_one_link do _remove_to_one_link(relationship_type) end end def replace_fields(field_data) change :replace_fields do _replace_fields(field_data) end end # Override this on a resource instance to override the fetchable keys def fetchable_fields self.class.fields end # Override this on a resource to customize how the associated records # are fetched for a model. Particularly helpful for authorization. def records_for(relation_name, _options = {}) model.public_send relation_name end private def save run_callbacks :save do _save end end # Override this on a resource to return a different result code. Any # value other than :completed will result in operations returning # `:accepted` # # For example to return `:accepted` if your model does not immediately # save resources to the database you could override `_save` as follows: # # ``` # def _save # super # return :accepted # end # ``` def _save unless @model.valid? fail JSONAPI::Exceptions::ValidationErrors.new(self) end if defined? @model.save saved = @model.save fail JSONAPI::Exceptions::SaveFailed.new unless saved else saved = true end @save_needed = !saved :completed end def _remove @model.destroy :completed end def _create_to_many_links(relationship_type, relationship_key_values) relationship = self.class._relationships[relationship_type] relationship_key_values.each do |relationship_key_value| related_resource = relationship.resource_klass.find_by_key(relationship_key_value, context: @context) relation_name = relationship.relation_name(context: @context) # TODO: Add option to skip relations that already exist instead of returning an error? relation = @model.public_send(relation_name).where(relationship.primary_key => relationship_key_value).first if relation.nil? @model.public_send(relation_name) << related_resource.model else fail JSONAPI::Exceptions::HasManyRelationExists.new(relationship_key_value) end end :completed end def _replace_to_many_links(relationship_type, relationship_key_values) relationship = self.class._relationships[relationship_type] send("#{relationship.foreign_key}=", relationship_key_values) @save_needed = true :completed end def _replace_to_one_link(relationship_type, relationship_key_value) relationship = self.class._relationships[relationship_type] send("#{relationship.foreign_key}=", relationship_key_value) @save_needed = true :completed end def _replace_polymorphic_to_one_link(relationship_type, key_value, key_type) relationship = self.class._relationships[relationship_type.to_sym] model.public_send("#{relationship.foreign_key}=", key_value) model.public_send("#{relationship.polymorphic_type}=", key_type.to_s.classify) @save_needed = true :completed end def _remove_to_many_link(relationship_type, key) @model.public_send(relationship_type).delete(key) :completed end def _remove_to_one_link(relationship_type) relationship = self.class._relationships[relationship_type] send("#{relationship.foreign_key}=", nil) @save_needed = true :completed end def _replace_fields(field_data) field_data[:attributes].each do |attribute, value| begin send "#{attribute}=", value @save_needed = true rescue ArgumentError # :nocov: Will be thrown if an enum value isn't allowed for an enum. Currently not tested as enums are a rails 4.1 and higher feature raise JSONAPI::Exceptions::InvalidFieldValue.new(attribute, value) # :nocov: end end field_data[:to_one].each do |relationship_type, value| if value.nil? remove_to_one_link(relationship_type) else case value when Hash replace_polymorphic_to_one_link(relationship_type.to_s, value.fetch(:id), value.fetch(:type)) else replace_to_one_link(relationship_type, value) end end end if field_data[:to_one] field_data[:to_many].each do |relationship_type, values| replace_to_many_links(relationship_type, values) end if field_data[:to_many] :completed end class << self def inherited(base) base.abstract(false) base._attributes = (_attributes || {}).dup base._relationships = (_relationships || {}).dup base._allowed_filters = (_allowed_filters || Set.new).dup type = base.name.demodulize.sub(/Resource$/, '').underscore base._type = type.pluralize.to_sym base.attribute :id, format: :id check_reserved_resource_name(base._type, base.name) end def resource_for(type) resource_name = JSONAPI::Resource._resource_name_from_type(type) resource = resource_name.safe_constantize if resource_name if resource.nil? fail NameError, "JSONAPI: Could not find resource '#{type}'. (Class #{resource_name} not found)" end resource end attr_accessor :_attributes, :_relationships, :_allowed_filters, :_type, :_paginator def create(context) new(create_model, context) end def create_model _model_class.new end def routing_options(options) @_routing_resource_options = options end def routing_resource_options @_routing_resource_options ||= {} end # Methods used in defining a resource class def attributes(*attrs) options = attrs.extract_options!.dup attrs.each do |attr| attribute(attr, options) end end def attribute(attr, options = {}) check_reserved_attribute_name(attr) if (attr.to_sym == :id) && (options[:format].nil?) ActiveSupport::Deprecation.warn('Id without format is no longer supported. Please remove ids from attributes, or specify a format.') end @_attributes ||= {} @_attributes[attr] = options define_method attr do @model.public_send(attr) end unless method_defined?(attr) define_method "#{attr}=" do |value| @model.public_send "#{attr}=", value end unless method_defined?("#{attr}=") end def default_attribute_options { format: :default } end def relationship(*attrs) options = attrs.extract_options! klass = case options[:to] when :one Relationship::ToOne when :many Relationship::ToMany else #:nocov:# fail ArgumentError.new('to: must be either :one or :many') #:nocov:# end _add_relationship(klass, *attrs, options.except(:to)) end def has_one(*attrs) _add_relationship(Relationship::ToOne, *attrs) end def has_many(*attrs) _add_relationship(Relationship::ToMany, *attrs) end def model_name(model) @_model_name = model.to_sym end def filters(*attrs) @_allowed_filters.merge!(attrs.inject({}) { |h, attr| h[attr] = {}; h }) end def filter(attr, *args) @_allowed_filters[attr.to_sym] = args.extract_options! end def primary_key(key) @_primary_key = key.to_sym end # TODO: remove this after the createable_fields and updateable_fields are phased out # :nocov: def method_missing(method, *args) if method.to_s.match /createable_fields/ ActiveSupport::Deprecation.warn('`createable_fields` is deprecated, please use `creatable_fields` instead') creatable_fields(*args) elsif method.to_s.match /updateable_fields/ ActiveSupport::Deprecation.warn('`updateable_fields` is deprecated, please use `updatable_fields` instead') updatable_fields(*args) else super end end # :nocov: # Override in your resource to filter the updatable keys def updatable_fields(_context = nil) _updatable_relationships | _attributes.keys - [:id] end # Override in your resource to filter the creatable keys def creatable_fields(_context = nil) _updatable_relationships | _attributes.keys end # Override in your resource to filter the sortable keys def sortable_fields(_context = nil) _attributes.keys end def fields _relationships.keys | _attributes.keys end def resolve_relationship_names_to_relations(resource_klass, model_includes, options = {}) case model_includes when Array return model_includes.map do |value| resolve_relationship_names_to_relations(resource_klass, value, options) end when Hash model_includes.keys.each do |key| relationship = resource_klass._relationships[key] value = model_includes[key] model_includes.delete(key) model_includes[relationship.relation_name(options)] = resolve_relationship_names_to_relations(relationship.resource_klass, value, options) end return model_includes when Symbol relationship = resource_klass._relationships[model_includes] return relationship.relation_name(options) end end def apply_includes(records, options = {}) include_directives = options[:include_directives] if include_directives model_includes = resolve_relationship_names_to_relations(self, include_directives.model_includes, options) records = records.includes(model_includes) end records end def apply_pagination(records, paginator, order_options) records = paginator.apply(records, order_options) if paginator records end def apply_sort(records, order_options) if order_options.any? records.order(order_options) else records end end def apply_filter(records, filter, value, _options = {}) records.where(filter => value) end def apply_filters(records, filters, options = {}) required_includes = [] if filters filters.each do |filter, value| if _relationships.include?(filter) if _relationships[filter].is_a?(JSONAPI::Relationship::ToMany) required_includes.push(filter.to_s) records = apply_filter(records, "#{filter}.#{_relationships[filter].primary_key}", value, options) else records = apply_filter(records, "#{_relationships[filter].foreign_key}", value, options) end else records = apply_filter(records, filter, value, options) end end end if required_includes.any? records = apply_includes(records, options.merge(include_directives: IncludeDirectives.new(required_includes))) end records end def filter_records(filters, options, records = records(options)) records = apply_filters(records, filters, options) apply_includes(records, options) end def sort_records(records, order_options) apply_sort(records, order_options) end def find_count(filters, options = {}) filter_records(filters, options).count(:all) end # Override this method if you have more complex requirements than this basic find method provides def find(filters, options = {}) context = options[:context] records = filter_records(filters, options) sort_criteria = options.fetch(:sort_criteria) { [] } order_options = construct_order_options(sort_criteria) records = sort_records(records, order_options) records = apply_pagination(records, options[:paginator], order_options) resources = [] records.each do |model| resources.push new(model, context) end resources end def find_by_key(key, options = {}) context = options[:context] records = records(options) records = apply_includes(records, options) model = records.where({_primary_key => key}).first fail JSONAPI::Exceptions::RecordNotFound.new(key) if model.nil? new(model, context) end # Override this method if you want to customize the relation for # finder methods (find, find_by_key) def records(_options = {}) _model_class end def verify_filters(filters, context = nil) verified_filters = {} filters.each do |filter, raw_value| verified_filter = verify_filter(filter, raw_value, context) verified_filters[verified_filter[0]] = verified_filter[1] end verified_filters end def is_filter_relationship?(filter) filter == _type || _relationships.include?(filter) end def verify_filter(filter, raw, context = nil) filter_values = [] filter_values += CSV.parse_line(raw) unless raw.nil? || raw.empty? if is_filter_relationship?(filter) verify_relationship_filter(filter, filter_values, context) else verify_custom_filter(filter, filter_values, context) end end def key_type(key_type) @_resource_key_type = key_type end def resource_key_type @_resource_key_type || JSONAPI.configuration.resource_key_type end def verify_key(key, context = nil) key_type = resource_key_type verification_proc = case key_type when :integer -> (key, context) { begin return key if key.nil? Integer(key) rescue raise JSONAPI::Exceptions::InvalidFieldValue.new(:id, key) end } when :string -> (key, context) { return key if key.nil? if key.to_s.include?(',') raise JSONAPI::Exceptions::InvalidFieldValue.new(:id, key) else key end } when :uuid -> (key, context) { return key if key.nil? if key.to_s.match(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/) key else raise JSONAPI::Exceptions::InvalidFieldValue.new(:id, key) end } else key_type end verification_proc.call(key, context) rescue raise JSONAPI::Exceptions::InvalidFieldValue.new(:id, key) end # override to allow for key processing and checking def verify_keys(keys, context = nil) return keys.collect do |key| verify_key(key, context) end end # override to allow for custom filters def verify_custom_filter(filter, value, _context = nil) [filter, value] end # override to allow for custom relationship logic, such as uuids, multiple keys or permission checks on keys def verify_relationship_filter(filter, raw, _context = nil) [filter, raw] end # quasi private class methods def _attribute_options(attr) default_attribute_options.merge(@_attributes[attr]) end def _updatable_relationships @_relationships.map { |key, _relationship| key } end def _relationship(type) type = type.to_sym @_relationships[type] end def _model_name @_model_name ||= name.demodulize.sub(/Resource$/, '') end def _primary_key @_primary_key ||= _model_class.respond_to?(:primary_key) ? _model_class.primary_key : :id end def _as_parent_key @_as_parent_key ||= "#{_type.to_s.singularize}_id" end def _allowed_filters !@_allowed_filters.nil? ? @_allowed_filters : { id: {} } end def _resource_name_from_type(type) class_name = @@resource_types[type] if class_name.nil? class_name = "#{type.to_s.underscore.singularize}_resource".camelize @@resource_types[type] = class_name end return class_name end def _paginator @_paginator ||= JSONAPI.configuration.default_paginator end def paginator(paginator) @_paginator = paginator end def abstract(val = true) @abstract = val end def _abstract @abstract end def _model_class return nil if _abstract return @model if @model @model = _model_name.to_s.safe_constantize warn "[MODEL NOT FOUND] Model could not be found for #{self.name}. If this a base Resource declare it as abstract." if @model.nil? @model end def _allowed_filter?(filter) !_allowed_filters[filter].nil? end def module_path @module_path ||= name =~ /::[^:]+\Z/ ? ($`.freeze.gsub('::', '/') + '/').underscore : '' end def construct_order_options(sort_params) return {} unless sort_params sort_params.each_with_object({}) do |sort, order_hash| field = sort[:field] == 'id' ? _primary_key : sort[:field] order_hash[field] = sort[:direction] end end private def check_reserved_resource_name(type, name) if [:ids, :types, :hrefs, :links].include?(type) warn "[NAME COLLISION] `#{name}` is a reserved resource name." return end end def check_reserved_attribute_name(name) # Allow :id since it can be used to specify the format. Since it is a method on the base Resource # an attribute method won't be created for it. if [:type, :href, :links, :model].include?(name.to_sym) warn "[NAME COLLISION] `#{name}` is a reserved key in #{@@resource_types[_type]}." end end def check_reserved_relationship_name(name) if [:id, :ids, :type, :types, :href, :hrefs, :link, :links].include?(name.to_sym) warn "[NAME COLLISION] `#{name}` is a reserved relationship name in #{@@resource_types[_type]}." end end def _add_relationship(klass, *attrs) options = attrs.extract_options! options[:module_path] = module_path attrs.each do |attr| check_reserved_relationship_name(attr) # Initialize from an ActiveRecord model's properties if _model_class && _model_class.ancestors.collect{|ancestor| ancestor.name}.include?('ActiveRecord::Base') model_association = _model_class.reflect_on_association(attr) if model_association options[:class_name] ||= model_association.class_name end end @_relationships[attr] = relationship = klass.new(attr, options) associated_records_method_name = case relationship when JSONAPI::Relationship::ToOne then "record_for_#{attr}" when JSONAPI::Relationship::ToMany then "records_for_#{attr}" end foreign_key = relationship.foreign_key define_method "#{foreign_key}=" do |value| @model.method("#{foreign_key}=").call(value) end unless method_defined?("#{foreign_key}=") define_method associated_records_method_name do relation_name = relationship.relation_name(context: @context) records_for(relation_name, context: @context) end unless method_defined?(associated_records_method_name) if relationship.is_a?(JSONAPI::Relationship::ToOne) if relationship.belongs_to? define_method foreign_key do @model.method(foreign_key).call end unless method_defined?(foreign_key) define_method attr do |options = {}| if relationship.polymorphic? associated_model = public_send(associated_records_method_name) resource_klass = Resource.resource_for(self.class.module_path + associated_model.class.to_s.underscore) if associated_model return resource_klass.new(associated_model, @context) if resource_klass else resource_klass = relationship.resource_klass if resource_klass associated_model = public_send(associated_records_method_name) return associated_model ? resource_klass.new(associated_model, @context) : nil end end end unless method_defined?(attr) else define_method foreign_key do record = public_send(associated_records_method_name) return nil if record.nil? record.public_send(relationship.resource_klass._primary_key) end unless method_defined?(foreign_key) define_method attr do |options = {}| resource_klass = relationship.resource_klass if resource_klass associated_model = public_send(associated_records_method_name) return associated_model ? resource_klass.new(associated_model, @context) : nil end end unless method_defined?(attr) end elsif relationship.is_a?(JSONAPI::Relationship::ToMany) define_method foreign_key do records = public_send(associated_records_method_name) return records.collect do |record| record.public_send(relationship.resource_klass._primary_key) end end unless method_defined?(foreign_key) define_method attr do |options = {}| resource_klass = relationship.resource_klass records = public_send(associated_records_method_name) filters = options.fetch(:filters, {}) unless filters.nil? || filters.empty? records = resource_klass.apply_filters(records, filters, options) end sort_criteria = options.fetch(:sort_criteria, {}) unless sort_criteria.nil? || sort_criteria.empty? order_options = relationship.resource_klass.construct_order_options(sort_criteria) records = resource_klass.apply_sort(records, order_options) end paginator = options[:paginator] if paginator records = resource_klass.apply_pagination(records, paginator, order_options) end return records.collect do |record| if relationship.polymorphic? resource_klass = Resource.resource_for(self.class.module_path + record.class.to_s.underscore) end resource_klass.new(record, @context) end end unless method_defined?(attr) end end end end end end
require 'fileutils' require 'digest/sha1' require 'RMagick' require 'pp' module Juli module Macro # embed photo(image) in juli wiki text with minimum maintenance cost # # See 'doc/photo(macro).txt' for the detail. class Photo < Base include Juli::Visitor::Html::TagHelper PUBLIC_PHOTO_DIR_DEFAULT = 'public_photo' SEED_DEFAULT = '-- Juli seed default!! --' CONF_DEFAULT = { 'mount' => '/home/YOUR_NAME/Photos', 'small' => { 'width' => 512, # default small width in pixel 'style' => 'float: right' }, 'large' => { 'width' => 1024 # default large width in pixel } } class DirNameConflict < Juli::JuliError; end class ConfigNoMount < Juli::JuliError; end def self.conf_template <<EOM # Photo macro setup sample is as follows. # #photo: # mount: '#{CONF_DEFAULT['mount']}' # small: # width: #{CONF_DEFAULT['small']['width']} # style: '#{CONF_DEFAULT['small']['style']}' # large: # width: #{CONF_DEFAULT['large']['width']} EOM end def set_conf_default(conf) set_conf_default_sub(conf, 'photo', CONF_DEFAULT) end # rotate image to fit orientation def rotate(img) exif = img.get_exif_by_entry(:Orientation) return img if !(exif && exif[0] && exif[0][0] == :Orientation) case exif[0][1] when '1' # Normal img when '6' # 90 degree img.rotate(90) # 90[deg] to clock direction when '8' # 270 degree img.rotate(-90) # 90[deg] to reversed-clock direction else img end end # public photo directory is used to: # # * store converted photo from original one # * protect private photo in 'mount' directory from public web access # by copying (with conversion) to it on demand. # # === INPUTS # url:: when true, return url, else, return physical file-system path def public_photo_dir(url = true) dir = File.join(conf['output_top'], PUBLIC_PHOTO_DIR_DEFAULT) raise DirNameConflict if File.file?(dir) if !File.directory?(dir) FileUtils.mkdir(dir) end url ? PUBLIC_PHOTO_DIR_DEFAULT : dir end # simplify path to the non-directory name with size. # # === Example # path:: a/b/c.jpg # photo_name:: a_b_c_#{size}.jpg def photo_name(path, size) flat = path.gsub(/\//, '_') sprintf("%s_%s%s", File.basename(flat, '.*'), size, File.extname(flat)) end # cached photo path # # === INPUTS # path:: photo-macro path argument # size:: :small, or :large # url:: when true, return url, else, return physical file-system path def photo_path(path, size, url = true) File.join(public_photo_dir(url), photo_name(path, size)) end # create resized, rotated, and 'exif' eliminated cache when: # 1. not already created, or # 1. cache is obsolete # # and return the path. # # === INPUTS # path:: photo-macro path argument # size:: :small, or :large # url:: when true, return url, else, return physical file-system path def intern(path, size = :small, url = true) protected_path = File.join(conf_photo['mount'], path) public_phys_path = photo_path(path, size, false) if !File.exist?(public_phys_path) || File::Stat.new(public_phys_path).mtime < File::Stat.new(protected_path).mtime img = Magick::ImageList.new(protected_path) width = (s = conf_photo[size.to_s]) && s['width'] img.resize_to_fit!(width, img.rows * width / img.columns) self.rotate(img). strip!. write(public_phys_path).destroy! end photo_path(path, size, url) end # return <img...> HTML tag for the photo with this macro features. def run(*args) path = args[0].gsub(/\.\./, '') # sanitize '..' style = conf_photo['small']['style'] small_url = intern(path) large_url = intern(path, :large) content_tag(:a, :href=>large_url) do tag(:img, :src => intern(path), :class => 'juli_photo_small', :style => style) end end def conf_photo @conf_photo ||= conf['photo'] end private def set_conf_default_sub(hash, key, val) case val when Hash hash[key] = {} if !hash[key] for k, v in val do set_conf_default_sub(hash[key], k, v) end else hash[key] = val if !hash[key] end end end end end rename gem name require 'fileutils' require 'digest/sha1' require 'rmagick' require 'pp' module Juli module Macro # embed photo(image) in juli wiki text with minimum maintenance cost # # See 'doc/photo(macro).txt' for the detail. class Photo < Base include Juli::Visitor::Html::TagHelper PUBLIC_PHOTO_DIR_DEFAULT = 'public_photo' SEED_DEFAULT = '-- Juli seed default!! --' CONF_DEFAULT = { 'mount' => '/home/YOUR_NAME/Photos', 'small' => { 'width' => 512, # default small width in pixel 'style' => 'float: right' }, 'large' => { 'width' => 1024 # default large width in pixel } } class DirNameConflict < Juli::JuliError; end class ConfigNoMount < Juli::JuliError; end def self.conf_template <<EOM # Photo macro setup sample is as follows. # #photo: # mount: '#{CONF_DEFAULT['mount']}' # small: # width: #{CONF_DEFAULT['small']['width']} # style: '#{CONF_DEFAULT['small']['style']}' # large: # width: #{CONF_DEFAULT['large']['width']} EOM end def set_conf_default(conf) set_conf_default_sub(conf, 'photo', CONF_DEFAULT) end # rotate image to fit orientation def rotate(img) exif = img.get_exif_by_entry(:Orientation) return img if !(exif && exif[0] && exif[0][0] == :Orientation) case exif[0][1] when '1' # Normal img when '6' # 90 degree img.rotate(90) # 90[deg] to clock direction when '8' # 270 degree img.rotate(-90) # 90[deg] to reversed-clock direction else img end end # public photo directory is used to: # # * store converted photo from original one # * protect private photo in 'mount' directory from public web access # by copying (with conversion) to it on demand. # # === INPUTS # url:: when true, return url, else, return physical file-system path def public_photo_dir(url = true) dir = File.join(conf['output_top'], PUBLIC_PHOTO_DIR_DEFAULT) raise DirNameConflict if File.file?(dir) if !File.directory?(dir) FileUtils.mkdir(dir) end url ? PUBLIC_PHOTO_DIR_DEFAULT : dir end # simplify path to the non-directory name with size. # # === Example # path:: a/b/c.jpg # photo_name:: a_b_c_#{size}.jpg def photo_name(path, size) flat = path.gsub(/\//, '_') sprintf("%s_%s%s", File.basename(flat, '.*'), size, File.extname(flat)) end # cached photo path # # === INPUTS # path:: photo-macro path argument # size:: :small, or :large # url:: when true, return url, else, return physical file-system path def photo_path(path, size, url = true) File.join(public_photo_dir(url), photo_name(path, size)) end # create resized, rotated, and 'exif' eliminated cache when: # 1. not already created, or # 1. cache is obsolete # # and return the path. # # === INPUTS # path:: photo-macro path argument # size:: :small, or :large # url:: when true, return url, else, return physical file-system path def intern(path, size = :small, url = true) protected_path = File.join(conf_photo['mount'], path) public_phys_path = photo_path(path, size, false) if !File.exist?(public_phys_path) || File::Stat.new(public_phys_path).mtime < File::Stat.new(protected_path).mtime img = Magick::ImageList.new(protected_path) width = (s = conf_photo[size.to_s]) && s['width'] img.resize_to_fit!(width, img.rows * width / img.columns) self.rotate(img). strip!. write(public_phys_path).destroy! end photo_path(path, size, url) end # return <img...> HTML tag for the photo with this macro features. def run(*args) path = args[0].gsub(/\.\./, '') # sanitize '..' style = conf_photo['small']['style'] small_url = intern(path) large_url = intern(path, :large) content_tag(:a, :href=>large_url) do tag(:img, :src => intern(path), :class => 'juli_photo_small', :style => style) end end def conf_photo @conf_photo ||= conf['photo'] end private def set_conf_default_sub(hash, key, val) case val when Hash hash[key] = {} if !hash[key] for k, v in val do set_conf_default_sub(hash[key], k, v) end else hash[key] = val if !hash[key] end end end end end
require "kafka/compression" module Kafka # Compresses message sets using a specified codec. # # A message set is only compressed if its size meets the defined threshold. # # ## Instrumentation # # Whenever a message set is compressed, the notification # `compress.compressor.kafka` will be emitted with the following payload: # # * `message_count` – the number of messages in the message set. # * `uncompressed_bytesize` – the byte size of the original data. # * `compressed_bytesize` – the byte size of the compressed data. # class Compressor # @param codec_name [Symbol, nil] # @param threshold [Integer] the minimum number of messages in a message set # that will trigger compression. def initialize(codec_name: nil, threshold: 1, instrumenter:) # Codec may be nil, in which case we won't compress. @codec = codec_name && Compression.find_codec(codec_name) @threshold = threshold @instrumenter = instrumenter end # @param record_batch [Protocol::RecordBatch] # @param offset [Integer] used to simulate broker behaviour in tests # @return [Protocol::RecordBatch] def compress(record_batch, offset: -1) if record_batch.is_a?(Protocol::RecordBatch) compress_record_batch(record_batch) else # Deprecated message set format compress_message_set(record_batch, offset) end end private def compress_message_set(message_set, offset) return message_set if @codec.nil? || message_set.size < @threshold data = Protocol::Encoder.encode_with(message_set) compressed_data = @codec.compress(data) @instrumenter.instrument("compress.compressor") do |notification| notification[:message_count] = message_set.size notification[:uncompressed_bytesize] = data.bytesize notification[:compressed_bytesize] = compressed_data.bytesize end wrapper_message = Protocol::Message.new( value: compressed_data, codec_id: @codec.codec_id, offset: offset ) Protocol::MessageSet.new(messages: [wrapper_message]) end def compress_record_batch(record_batch) byebug if @codec.nil? || record_batch.size < @threshold record_batch.codec_id = 0 return Protocol::Encoder.encode_with(record_batch) end record_batch.codec_id = @codec.codec_id data = Protocol::Encoder.encode_with(record_batch) @instrumenter.instrument("compress.compressor") do |notification| notification[:message_count] = record_batch.size notification[:compressed_bytesize] = data.bytesize end data end end end Remove byebug require "kafka/compression" module Kafka # Compresses message sets using a specified codec. # # A message set is only compressed if its size meets the defined threshold. # # ## Instrumentation # # Whenever a message set is compressed, the notification # `compress.compressor.kafka` will be emitted with the following payload: # # * `message_count` – the number of messages in the message set. # * `uncompressed_bytesize` – the byte size of the original data. # * `compressed_bytesize` – the byte size of the compressed data. # class Compressor # @param codec_name [Symbol, nil] # @param threshold [Integer] the minimum number of messages in a message set # that will trigger compression. def initialize(codec_name: nil, threshold: 1, instrumenter:) # Codec may be nil, in which case we won't compress. @codec = codec_name && Compression.find_codec(codec_name) @threshold = threshold @instrumenter = instrumenter end # @param record_batch [Protocol::RecordBatch] # @param offset [Integer] used to simulate broker behaviour in tests # @return [Protocol::RecordBatch] def compress(record_batch, offset: -1) if record_batch.is_a?(Protocol::RecordBatch) compress_record_batch(record_batch) else # Deprecated message set format compress_message_set(record_batch, offset) end end private def compress_message_set(message_set, offset) return message_set if @codec.nil? || message_set.size < @threshold data = Protocol::Encoder.encode_with(message_set) compressed_data = @codec.compress(data) @instrumenter.instrument("compress.compressor") do |notification| notification[:message_count] = message_set.size notification[:uncompressed_bytesize] = data.bytesize notification[:compressed_bytesize] = compressed_data.bytesize end wrapper_message = Protocol::Message.new( value: compressed_data, codec_id: @codec.codec_id, offset: offset ) Protocol::MessageSet.new(messages: [wrapper_message]) end def compress_record_batch(record_batch) if @codec.nil? || record_batch.size < @threshold record_batch.codec_id = 0 return Protocol::Encoder.encode_with(record_batch) end record_batch.codec_id = @codec.codec_id data = Protocol::Encoder.encode_with(record_batch) @instrumenter.instrument("compress.compressor") do |notification| notification[:message_count] = record_batch.size notification[:compressed_bytesize] = data.bytesize end data end end end
# encoding: utf-8 module Kleiber # Provides objects with command patterns for particular terminal # @author Bobykin Kirill <qelphybox@gmail.com> class Terminal def initialize(name = 'xfce4-terminal') @name = name @terminal = JSON.parse(IO.read("#{ROOT}/resources/terminals/#{@name}.json"), sybolize_names: true) end # Executes command in new tab # @param command [type] [description] # @return [type] [description] def execute(command) new_tab(command) end private def new_tab(command) comm = @terminal[:exec_command] % { tab_command: command } "#{@terminal[:exec]} "\ "#{@terminal[:new_tab]} "\ "#{@terminal[:set_title]}} "\ "#{comm}" end end end Edited syntax at Terminal # encoding: utf-8 module Kleiber # Provides objects with command patterns for particular terminal # @author Bobykin Kirill <qelphybox@gmail.com> class Terminal def initialize(name = 'xfce4-terminal') @name = name @terminal = JSON.parse(IO.read("#{ROOT}/resources/terminals/#{@name}.json"), sybolize_names: true) end # Executes command in new tab # @param command [type] [description] # @return [type] [description] def execute(command) new_tab(command) end private def new_tab(command) comm = @terminal[:exec_command] % { tab_command: command } [@terminal[:exec], @terminal[:new_tab], @terminal[:set_title], comm].join(' ') end end end
require 'narray' class KMeansClusterer CalculateCentroid = -> (a) { a.mean(1) } Distance = -> (x, y, yy = nil) do if x.is_a?(NMatrix) && y.is_a?(NMatrix) xx = x.map {|v| v**2}.sum(0) yy ||= y.map {|v| v**2}.sum(0) xy = x * y.transpose distance = xy * -2 distance += xx distance += yy.transpose NMath.sqrt distance else NMath.sqrt ((x - y)**2).sum(0) end end class Point attr_reader :data attr_accessor :cluster, :label def initialize data, label = nil @data = NArray.to_na data @label = label end def [] index @data[index] end def to_a @data.to_a end def to_s to_a.to_s end def dimension @data.length end end class Cluster attr_reader :centroid, :points attr_accessor :label def initialize centroid, label = nil @centroid = centroid @label = label @points = [] end def recenter return 0 if @points.empty? old_centroid = @centroid @centroid = calculate_centroid_from_points Distance.call @centroid.data, old_centroid.data end def << point point.cluster = self @points << point end def reset_points @points = [] end def sorted_points distances = points_distances_from(centroid) @points.sort_by.with_index {|c, i| distances[i] } end def sum_of_squares_error return 0 if @points.empty? distances = points_distances_from(centroid) (distances**2).sum end def sum_of_distances return 0 if @points.empty? points_distances_from(centroid).sum end def dissimilarity point distances = points_distances_from(point) distances.sum / distances.length.to_f end def points_narray NArray.cast @points.map(&:data) end private def calculate_centroid_from_points data = CalculateCentroid.call points_narray Point.new data end def points_distances_from point Distance.call points_narray, point.data end # def points_narray # NArray.to_na @points.map(&:data) # end end def self.run k, data, opts = {} raise(ArgumentError, "k cannot be greater than the number of points") if k > data.length data = if opts[:scale_data] scale_data data else data.map {|row| NArray.to_na(row).to_f} end runcount = opts[:runs] || 10 errors = [] opts[:points_matrix] = NMatrix.cast data opts[:points_norms] = opts[:points_matrix].map {|v| v**2}.sum(0) runs = runcount.times.map do |i| km = new(k, data, opts).run error = km.error if opts[:log] puts "[#{i + 1}] #{km.iterations} iter\t#{km.runtime.round(2)}s\t#{error.round(2)} err" end errors << error km end runs.sort_by.with_index {|run, i| errors[i] }.first end # see scikit-learn scale and _mean_and_std methods def self.scale_data data nadata = NArray.to_na(data).to_f mean = nadata.mean(1) std = nadata.rmsdev(1) std[std.eq(0)] = 1.0 # so we don't divide by 0 nadata = (nadata - mean) / std # convert back to an array, containing NArrays for each row data.length.times.map {|i| nadata[true, i] } end attr_reader :k, :points, :clusters, :iterations, :runtime def initialize k, data, opts = {} @k = k @init = opts[:init] || :kmpp @labels = opts[:labels] || [] # @points = data.map.with_index do |instance, i| # Point.new instance, labels[i] # end @points_matrix = opts[:points_matrix] @points_norms = opts[:points_norms] @points_count = @points_matrix.shape[1] # init_clusters @centroids = @points_matrix[true, pick_k_random_indexes] end def run start_time = Time.now @iterations, @runtime = 0, 0 @cluster_point_ids = Array.new(@k) { [] } loop do @iterations +=1 distances = Distance.call(@centroids, @points_matrix, @points_norms) # assign point ids to @cluster_point_ids @points_count.times do |i| min_distance_index = distances[i, true].sort_index[0] @cluster_point_ids[min_distance_index] << i end # moves = clusters.map(&:recenter) moves = [] updated_centroids = [] @k.times do |i| centroid = NArray.cast(@centroids[true, i].flatten) point_ids = @cluster_point_ids[i] if point_ids.empty? newcenter = centroid moves << 0 else points = @points_matrix[true, point_ids] newcenter = points.mean(1) moves << Distance.call(centroid, newcenter) end updated_centroids << newcenter end @centroids = NMatrix.cast updated_centroids break if moves.max < 0.001 # i.e., no movement break if @iterations >= 300 # clusters.each(&:reset_points) @cluster_point_ids = Array.new(@k) { [] } end @points = @points_count.times.map do |i| data = NArray.cast @points_matrix[true, i].flatten Point.new(data, @labels[i]) end @clusters = @k.times.map do |i| centroid = NArray.cast @centroids[true, i].flatten c = Cluster.new Point.new(centroid), i + 1 @cluster_point_ids[i].each do |p| c << @points[p] end c end @runtime = Time.now - start_time self end def error errors = @clusters.map do |c| if c.points.empty? 0 else distances = Distance.call NArray.cast(c.points.map(&:data)), c.centroid.data (distances**2).sum end end errors.reduce(:+) end def closest_cluster point = origin sorted_clusters(point).first end def sorted_clusters point = origin point = Point.new(point) unless point.is_a?(Point) centroids = get_cluster_centroids distances = Distance.call(centroids, point.data) @clusters.sort_by.with_index {|c, i| distances[i] } end def origin Point.new Array.new(@points[0].dimension, 0) end def silhouette_score return 1.0 if @clusters.length < 2 scores = @points.map do |point| acluster, bcluster = sorted_clusters(point).slice(0,2) a = dissimilarity(acluster.points_narray, point.data) b = dissimilarity(bcluster.points_narray, point.data) (b - a) / [a,b].max end scores.reduce(:+) / scores.length # mean score for all points end private def dissimilarity points, point distances = Distance.call points, point distances.sum / distances.length.to_f end def init_clusters case @init when :random random_cluster_init when Array custom_cluster_init else kmpp_cluster_init end end # k-means++ def kmpp_cluster_init @clusters = [] pick = rand(@points.length) centroid = Point.new @points[pick].data.to_a @clusters << Cluster.new(centroid, 1) while @clusters.length < @k centroids = get_cluster_centroids d2 = @points.map do |point| dists = Distance.call centroids, point.data dists.min**2 # closest cluster distance, squared end d2 = NArray.to_na d2 probs = d2 / d2.sum cumprobs = probs.cumsum r = rand # pick = cumprobs.to_a.index {|prob| r < prob } pick = (cumprobs >= r).where[0] centroid = Point.new @points[pick].data.to_a cluster = Cluster.new(centroid, @clusters.length + 1) @clusters << cluster end end def custom_cluster_init @clusters = @init.map.with_index do |instance, i| point = Point.new NArray.to_na(instance).to_f Cluster.new point, i+1 end end def random_cluster_init @clusters = pick_k_random_points.map.with_index {|centroid, i| Cluster.new centroid, i+1 } end def pick_k_random_points pick_k_random_indexes.map {|i| Point.new @points[i].data.to_a } end def pick_k_random_indexes @points_count.times.to_a.shuffle.slice(0, @k) end def get_cluster_centroids NArray.to_na @clusters.map {|c| c.centroid.data } end end # class KMediansClusterer < KMeansClusterer # Distance = -> (x, y, yy = nil) { (x - y).abs.sum(0) } # CalculateCentroid = -> (a) { a.rot90.median(0) } # def error # @clusters.map(&:sum_of_distances).reduce(:+) # end # end Update kmpp init to use bulk distance calc require 'narray' class KMeansClusterer CalculateCentroid = -> (a) { a.mean(1) } Distance = -> (x, y, yy = nil) do if x.is_a?(NMatrix) && y.is_a?(NMatrix) xx = x.map {|v| v**2}.sum(0) yy ||= y.map {|v| v**2}.sum(0) xy = x * y.transpose distance = xy * -2 distance += xx distance += yy.transpose NMath.sqrt distance else NMath.sqrt ((x - y)**2).sum(0) end end class Point attr_reader :data attr_accessor :cluster, :label def initialize data, label = nil @data = NArray.to_na data @label = label end def [] index @data[index] end def to_a @data.to_a end def to_s to_a.to_s end def dimension @data.length end end class Cluster attr_reader :centroid, :points attr_accessor :label def initialize centroid, label = nil @centroid = centroid @label = label @points = [] end def recenter return 0 if @points.empty? old_centroid = @centroid @centroid = calculate_centroid_from_points Distance.call @centroid.data, old_centroid.data end def << point point.cluster = self @points << point end def reset_points @points = [] end def sorted_points distances = points_distances_from(centroid) @points.sort_by.with_index {|c, i| distances[i] } end def sum_of_squares_error return 0 if @points.empty? distances = points_distances_from(centroid) (distances**2).sum end def sum_of_distances return 0 if @points.empty? points_distances_from(centroid).sum end def dissimilarity point distances = points_distances_from(point) distances.sum / distances.length.to_f end def points_narray NArray.cast @points.map(&:data) end private def calculate_centroid_from_points data = CalculateCentroid.call points_narray Point.new data end def points_distances_from point Distance.call points_narray, point.data end # def points_narray # NArray.to_na @points.map(&:data) # end end def self.run k, data, opts = {} raise(ArgumentError, "k cannot be greater than the number of points") if k > data.length data = if opts[:scale_data] scale_data data else data.map {|row| NArray.to_na(row).to_f} end runcount = opts[:runs] || 10 errors = [] opts[:points_matrix] = NMatrix.cast data opts[:points_norms] = opts[:points_matrix].map {|v| v**2}.sum(0) runs = runcount.times.map do |i| km = new(k, data, opts).run error = km.error if opts[:log] puts "[#{i + 1}] #{km.iterations} iter\t#{km.runtime.round(2)}s\t#{error.round(2)} err" end errors << error km end runs.sort_by.with_index {|run, i| errors[i] }.first end # see scikit-learn scale and _mean_and_std methods def self.scale_data data nadata = NArray.to_na(data).to_f mean = nadata.mean(1) std = nadata.rmsdev(1) std[std.eq(0)] = 1.0 # so we don't divide by 0 nadata = (nadata - mean) / std # convert back to an array, containing NArrays for each row data.length.times.map {|i| nadata[true, i] } end attr_reader :k, :points, :clusters, :iterations, :runtime def initialize k, data, opts = {} @k = k @init = opts[:init] || :kmpp @labels = opts[:labels] || [] # @points = data.map.with_index do |instance, i| # Point.new instance, labels[i] # end @points_matrix = opts[:points_matrix] @points_norms = opts[:points_norms] @points_count = @points_matrix.shape[1] init_centroids end def run start_time = Time.now @iterations, @runtime = 0, 0 @cluster_point_ids = Array.new(@k) { [] } loop do @iterations +=1 distances = Distance.call(@centroids, @points_matrix, @points_norms) # assign point ids to @cluster_point_ids @points_count.times do |i| min_distance_index = distances[i, true].sort_index[0] @cluster_point_ids[min_distance_index] << i end # moves = clusters.map(&:recenter) moves = [] updated_centroids = [] @k.times do |i| centroid = NArray.cast(@centroids[true, i].flatten) point_ids = @cluster_point_ids[i] if point_ids.empty? newcenter = centroid moves << 0 else points = @points_matrix[true, point_ids] newcenter = points.mean(1) moves << Distance.call(centroid, newcenter) end updated_centroids << newcenter end @centroids = NMatrix.cast updated_centroids break if moves.max < 0.001 # i.e., no movement break if @iterations >= 300 # clusters.each(&:reset_points) @cluster_point_ids = Array.new(@k) { [] } end @points = @points_count.times.map do |i| data = NArray.cast @points_matrix[true, i].flatten Point.new(data, @labels[i]) end @clusters = @k.times.map do |i| centroid = NArray.cast @centroids[true, i].flatten c = Cluster.new Point.new(centroid), i + 1 @cluster_point_ids[i].each do |p| c << @points[p] end c end @runtime = Time.now - start_time self end def error errors = @clusters.map do |c| if c.points.empty? 0 else distances = Distance.call NArray.cast(c.points.map(&:data)), c.centroid.data (distances**2).sum end end errors.reduce(:+) end def closest_cluster point = origin sorted_clusters(point).first end def sorted_clusters point = origin point = Point.new(point) unless point.is_a?(Point) centroids = get_cluster_centroids distances = Distance.call(centroids, point.data) @clusters.sort_by.with_index {|c, i| distances[i] } end def origin Point.new Array.new(@points[0].dimension, 0) end def silhouette_score return 1.0 if @clusters.length < 2 scores = @points.map do |point| acluster, bcluster = sorted_clusters(point).slice(0,2) a = dissimilarity(acluster.points_narray, point.data) b = dissimilarity(bcluster.points_narray, point.data) (b - a) / [a,b].max end scores.reduce(:+) / scores.length # mean score for all points end private def dissimilarity points, point distances = Distance.call points, point distances.sum / distances.length.to_f end def init_centroids case @init when :random random_centroid_init when Array custom_centroid_init else kmpp_centroid_init end end # k-means++ def kmpp_centroid_init centroid_ids = [] pick = rand(@points_count) centroid_ids << pick while centroid_ids.length < @k centroids = @points_matrix[true, centroid_ids] distances = Distance.call(centroids, @points_matrix, @points_norms) d2 = [] @points_count.times do |i| min_distance = distances[i, true].min d2 << min_distance**2 end d2 = NArray.to_na d2 probs = d2 / d2.sum cumprobs = probs.cumsum r = rand pick = (cumprobs >= r).where[0] centroid_ids << pick end @centroids = @points_matrix[true, centroid_ids] end def custom_centroid_init @centroids = NMatrix.cast @init end def random_centroid_init @centroids = @points_matrix[true, pick_k_random_indexes] end def pick_k_random_indexes @points_count.times.to_a.shuffle.slice(0, @k) end def get_cluster_centroids NArray.to_na @clusters.map {|c| c.centroid.data } end end # class KMediansClusterer < KMeansClusterer # Distance = -> (x, y, yy = nil) { (x - y).abs.sum(0) } # CalculateCentroid = -> (a) { a.rot90.median(0) } # def error # @clusters.map(&:sum_of_distances).reduce(:+) # end # end
require "lazily/enumerable" module Lazily class Filtering include Lazily::Enumerable def initialize(&generator) @generator = generator end def each return to_enum unless block_given? yielder = proc { |x| yield x } @generator.call(yielder) end end module Enumerable def collect Filtering.new do |output| each do |element| output.call yield(element) end end end alias map collect def select Filtering.new do |output| each do |element| output.call(element) if yield(element) end end end alias find_all select def reject Filtering.new do |output| each do |element| output.call(element) unless yield(element) end end end def uniq Filtering.new do |output| seen = Set.new each do |element| output.call(element) if seen.add?(element) end end end def uniq_by Filtering.new do |output| seen = Set.new each do |element| output.call(element) if seen.add?(yield element) end end end def take(n) Filtering.new do |output| if n > 0 each_with_index do |element, index| output.call(element) break if index + 1 == n end end end end def take_while Filtering.new do |output| each do |element| break unless yield(element) output.call(element) end end end def drop(n) Filtering.new do |output| each_with_index do |element, index| next if index < n output.call(element) end end end def drop_while Filtering.new do |output| take = false each do |element| take ||= !yield(element) output.call(element) if take end end end def [](n) drop(n).first end end end Replace "break" with catch/throw. require "lazily/enumerable" module Lazily class Filtering include Lazily::Enumerable def initialize(&generator) @generator = generator end DONE = "Lazily::DONE".to_sym def each return to_enum unless block_given? yielder = proc { |x| yield x } catch DONE do @generator.call(yielder) end end end module Enumerable def collect Filtering.new do |output| each do |element| output.call yield(element) end end end alias map collect def select Filtering.new do |output| each do |element| output.call(element) if yield(element) end end end alias find_all select def reject Filtering.new do |output| each do |element| output.call(element) unless yield(element) end end end def uniq Filtering.new do |output| seen = Set.new each do |element| output.call(element) if seen.add?(element) end end end def uniq_by Filtering.new do |output| seen = Set.new each do |element| output.call(element) if seen.add?(yield element) end end end def take(n) Filtering.new do |output| if n > 0 each_with_index do |element, index| output.call(element) throw Lazily::Filtering::DONE if index + 1 == n end end end end def take_while Filtering.new do |output| each do |element| throw Lazily::Filtering::DONE unless yield(element) output.call(element) end end end def drop(n) Filtering.new do |output| each_with_index do |element, index| next if index < n output.call(element) end end end def drop_while Filtering.new do |output| take = false each do |element| take ||= !yield(element) output.call(element) if take end end end def [](n) drop(n).first end end end
module LearnConfig class CLI attr_reader :github_username attr_accessor :token def initialize(github_username) @github_username = github_username end def ask_for_oauth_token puts <<-LONG To connect with the Learn web application, you will need to configure the Learn gem with an OAuth token. You can find yours on your profile page at: https://learn.co/#{github_username ? github_username : 'your-github-username'}. LONG print('Once you have it, please come back here and paste it in: ') self.token = gets.chomp verify_token_or_ask_again! end private def verify_token_or_ask_again! if token_valid? token else ask_for_oauth_token end end def token_valid? learn = LearnConfig::LearnWebInteractor.new(token, silent_output: true) learn.valid_token? # TODO: Make authed request. If 200, valid. If 401/422/500 invalid. end end end Mo bettah' output module LearnConfig class CLI attr_reader :github_username attr_accessor :token def initialize(github_username) @github_username = github_username end def ask_for_oauth_token(short_text: false) if !short_text puts <<-LONG To connect with the Learn web application, you will need to configure the Learn gem with an OAuth token. You can find yours on your profile page at: https://learn.co/#{github_username ? github_username : 'your-github-username'}. LONG print 'Once you have it, please come back here and paste it in: ' else print "Hmm...that token doesn't seem to be correct. Please try again: " end self.token = gets.chomp verify_token_or_ask_again! end private def verify_token_or_ask_again! if token_valid? token else puts "" ask_for_oauth_token(short_text: true) end end def token_valid? learn = LearnConfig::LearnWebInteractor.new(token, silent_output: true) learn.valid_token? # TODO: Make authed request. If 200, valid. If 401/422/500 invalid. end end end
require "active_support/core_ext/hash" require 'active_support/builder' require "net/http" require "uri" require "rexml/document" module LemonWay class Client @@api_method_calls = %w( FastPay GetBalances GetKycStatus GetMoneyInIBANDetails GetMoneyInTransDetails GetMoneyOutTransDetails GetPaymentDetails GetWalletDetails GetWalletTransHistory MoneyIn MoneyIn3DConfirm MoneyIn3DInit MoneyInWebInit MoneyInWithCardId MoneyOut RefundMoneyIn RegisterCard RegisterIBAN RegisterWallet SendPayment UnregisterCard UpdateWalletDetails UpdateWalletStatus UploadFile ) attr_reader :uri, :xml_mini_backend, :entity_expansion_text_limit, :options def initialize opts = {} @options = opts.symbolize_keys!.except(:uri, :xml_mini_backend).camelize_keys @uri = URI.parse opts[:uri] @xml_mini_backend = opts[:xml_mini_backend] || ActiveSupport::XmlMini_REXML @entity_expansion_text_limit = opts[:entity_expansion_text_limit] || 10**20 end def method_missing *args, &block camelized_method_name = args.first.to_s.camelize if @@api_method_calls.include? camelized_method_name attrs = attrs_from_options args.extract_options! query camelized_method_name, attrs, &block else super end end private def make_body(method_name, attrs={}) options = {} options[:builder] = Builder::XmlMarkup.new(:indent => 2) options[:builder].instruct! options[:builder].tag! "soap12:Envelope", "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xmlns:xsd"=>"http://www.w3.org/2001/XMLSchema", "xmlns:soap12"=>"http://www.w3.org/2003/05/soap-envelope" do options[:builder].tag! "soap12:Body" do options[:builder].__send__(:method_missing, method_name.to_s.camelize, xmlns: "Service_mb") do @options.merge(attrs).each do |key, value| ActiveSupport::XmlMini.to_tag(key, value, options) end end end end end def query(method, attrs={}) http = Net::HTTP.new(@uri.host, @uri.port) http.use_ssl = true if @uri.port == 443 req = Net::HTTP::Post.new(@uri.request_uri) req.body = make_body(method, attrs) req.add_field 'Content-type', 'text/xml; charset=utf-8' response = http.request(req).read_body with_custom_parser_options do response = Hash.from_xml(response)["Envelope"]['Body']["#{method}Response"]["#{method}Result"] response = Hash.from_xml(response).with_indifferent_access.underscore_keys(true) end if response.has_key?("e") raise Error, [response["e"]["code"], response["e"]["msg"]].join(' : ') elsif block_given? yield(response) else response end end # quickly retreat date and big decimal potential attributes def attrs_from_options attrs attrs.symbolize_keys!.camelize_keys! [:amount, :amountTot, :amountCom].each do |key| attrs[key] = sprintf("%.2f",attrs[key]) if attrs.key?(key) and attrs[key].is_a?(Numeric) end [:updateDate].each do |key| attrs[key] = attrs[key].to_datetime.utc.to_i.to_s if attrs.key?(key) and [Date, Time].any?{|k| attrs[key].is_a?(k)} end attrs end # work around for # - Nokogiri::XML::SyntaxError: xmlns: URI Service_mb is not absolute # - RuntimeError: entity expansion has grown too large def with_custom_parser_options &block backend = ActiveSupport::XmlMini.backend ActiveSupport::XmlMini.backend= @xml_mini_backend text_limit = REXML::Document.entity_expansion_text_limit REXML::Document.entity_expansion_text_limit = @entity_expansion_text_limit yield ensure ActiveSupport::XmlMini.backend = backend REXML::Document.entity_expansion_text_limit = text_limit end class Error < Exception; end end end add methods require "active_support/core_ext/hash" require 'active_support/builder' require "net/http" require "uri" require "rexml/document" module LemonWay class Client @@api_method_calls = %w( FastPay GetBalances GetKycStatus GetMoneyInIBANDetails GetMoneyInTransDetails GetMoneyOutTransDetails GetPaymentDetails GetWalletDetails GetWalletTransHistory MoneyIn MoneyIn3DConfirm MoneyIn3DInit MoneyInWebInit MoneyInWithCardId MoneyInSddInit MoneyOut RefundMoneyIn RegisterCard RegisterIBAN RegisterWallet RegisterSddMandate SendPayment SignDocumentInit UnregisterCard UpdateWalletDetails UpdateWalletStatus UploadFile ) attr_reader :uri, :xml_mini_backend, :entity_expansion_text_limit, :options def initialize opts = {} @options = opts.symbolize_keys!.except(:uri, :xml_mini_backend).camelize_keys @uri = URI.parse opts[:uri] @xml_mini_backend = opts[:xml_mini_backend] || ActiveSupport::XmlMini_REXML @entity_expansion_text_limit = opts[:entity_expansion_text_limit] || 10**20 end def method_missing *args, &block camelized_method_name = args.first.to_s.camelize if @@api_method_calls.include? camelized_method_name attrs = attrs_from_options args.extract_options! query camelized_method_name, attrs, &block else super end end private def make_body(method_name, attrs={}) options = {} options[:builder] = Builder::XmlMarkup.new(:indent => 2) options[:builder].instruct! options[:builder].tag! "soap12:Envelope", "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xmlns:xsd"=>"http://www.w3.org/2001/XMLSchema", "xmlns:soap12"=>"http://www.w3.org/2003/05/soap-envelope" do options[:builder].tag! "soap12:Body" do options[:builder].__send__(:method_missing, method_name.to_s.camelize, xmlns: "Service_mb") do @options.merge(attrs).each do |key, value| ActiveSupport::XmlMini.to_tag(key, value, options) end end end end end def query(method, attrs={}) http = Net::HTTP.new(@uri.host, @uri.port) http.use_ssl = true if @uri.port == 443 req = Net::HTTP::Post.new(@uri.request_uri) req.body = make_body(method, attrs) req.add_field 'Content-type', 'text/xml; charset=utf-8' response = http.request(req).read_body with_custom_parser_options do response = Hash.from_xml(response)["Envelope"]['Body']["#{method}Response"]["#{method}Result"] response = Hash.from_xml(response).with_indifferent_access.underscore_keys(true) end if response.has_key?("e") raise Error, [response["e"]["code"], response["e"]["msg"]].join(' : ') elsif block_given? yield(response) else response end end # quickly retreat date and big decimal potential attributes def attrs_from_options attrs attrs.symbolize_keys!.camelize_keys! [:amount, :amountTot, :amountCom].each do |key| attrs[key] = sprintf("%.2f",attrs[key]) if attrs.key?(key) and attrs[key].is_a?(Numeric) end [:updateDate].each do |key| attrs[key] = attrs[key].to_datetime.utc.to_i.to_s if attrs.key?(key) and [Date, Time].any?{|k| attrs[key].is_a?(k)} end attrs end # work around for # - Nokogiri::XML::SyntaxError: xmlns: URI Service_mb is not absolute # - RuntimeError: entity expansion has grown too large def with_custom_parser_options &block backend = ActiveSupport::XmlMini.backend ActiveSupport::XmlMini.backend= @xml_mini_backend text_limit = REXML::Document.entity_expansion_text_limit REXML::Document.entity_expansion_text_limit = @entity_expansion_text_limit yield ensure ActiveSupport::XmlMini.backend = backend REXML::Document.entity_expansion_text_limit = text_limit end class Error < Exception; end end end
module LetItFall CODESET = { face: [*0x1F600..0x1F64F] - [*0x1F641..0x1F644], snow: 0x2736, gem: 0x1F48E, python: 0x1F40D, ghost: 0x1F47B, cocktail: 0x1F378, kanji: (0x4E00..0x4F00), juice: 0x1F379, time: (0x1F550..0x1f567), beer: 0x1F37A, tower: 0x1F5FC, cake: 0x1F382, sparkle: 0x2728, animal: (0x1F40C..0x1F43C), cyclone: 0x1F300, octopus: 0x1F419, perl: 0x1F42A, dancer: 0x1F483, bee: 0x1F41D, dolphin: 0x1F42C, wine: 0x1F377, food: (0x1F344..0x1F373), japan: 0x1F5FE, bikini: 0x1F459, oden: 0x1F362, paw: 0x1F43E, eyes: 0x1F440, mouth: 0x1F444, love: (0x1F493..0x1F49F), nose: 0x1F443, latin: [*0x0021..0x007E, *0x00A1..0x00FF, *0x0100..0x017F, *0x0250..0x02AF], poo: 0x1F4A9, money: [0x1F4B0, 0x1F4B3, 0x1F4B4, 0x1F4B5, 0x1F4B6, 0x1F4B7, 0x1F4B8], pushpin: 0x1F4CD, ear: 0x1F442, sushi: 0x1F363, arrow: (0x2190..0x21FF), hocho: 0x1F52A, tongue: 0x1F445, beers: 0x1F37B, oreilly: (0x1F40C..0x1F43C), beginner: 0x1F530, helicopter: 0x1F681, earth: [0x1F30D, 0x1F30E], liberty: 0x1F5FD, angel: 0x1F47C, alien: 0x1F47D, pistol: 0x1F52B, kiss: 0x1F48B, alphabet: [*0x0041..0x005A, *0x0061..0x007A], pizza: 0x1F355, dingbat: (0x2701..0x27BF), naruto: 0x1F365, moon: (0x1F311..0x1F315), cookie: 0x1F36A, fuji: 0x1F5FB, lollipop: 0x1F36D, } end add several mark commands module LetItFall CODESET = { face: [*0x1F600..0x1F64F] - [*0x1F641..0x1F644], snow: 0x2736, gem: 0x1F48E, python: 0x1F40D, ghost: 0x1F47B, cocktail: 0x1F378, kanji: (0x4E00..0x4F00), juice: 0x1F379, time: (0x1F550..0x1f567), beer: 0x1F37A, tower: 0x1F5FC, sorry: 0x1F647, cake: 0x1F382, sparkle: 0x2728, animal: (0x1F40C..0x1F43C), cyclone: 0x1F300, octopus: 0x1F419, perl: 0x1F42A, dancer: 0x1F483, bee: 0x1F41D, downarrow: 0x2935, cross: 0x274C, dolphin: 0x1F42C, wine: 0x1F377, food: (0x1F344..0x1F373), japan: 0x1F5FE, bikini: 0x1F459, oden: 0x1F362, wavy: 0x3030, please: 0x1F64F, apple: 0x1F34E, paw: 0x1F43E, eyes: 0x1F440, smoking: 0x1F6AC, m: 0x24C2, thunder: 0x26A1, toilet: 0x1F6BD, cactus: 0x1F335, mouth: 0x1F444, love: (0x1F493..0x1F49F), nose: 0x1F443, snowman: 0x26C4, latin: [*0x0021..0x007E, *0x00A1..0x00FF, *0x0100..0x017F, *0x0250..0x02AF], poo: 0x1F4A9, money: [0x1F4B0, 0x1F4B3, 0x1F4B4, 0x1F4B5, 0x1F4B6, 0x1F4B7, 0x1F4B8], pushpin: 0x1F4CD, ear: 0x1F442, sushi: 0x1F363, arrow: (0x2190..0x21FF), hocho: 0x1F52A, tongue: 0x1F445, soccer: 0x26BD, beers: 0x1F37B, oreilly: (0x1F40C..0x1F43C), beginner: 0x1F530, helicopter: 0x1F681, earth: [0x1F30D, 0x1F30E], liberty: 0x1F5FD, angel: 0x1F47C, alien: 0x1F47D, uparrow: 0x2934, pistol: 0x1F52B, kiss: 0x1F48B, alphabet: [*0x0041..0x005A, *0x0061..0x007A], pizza: 0x1F355, dingbat: (0x2701..0x27BF), naruto: 0x1F365, moon: (0x1F311..0x1F315), cookie: 0x1F36A, christmas: [0x1F384, 0x1F385, 0x1F370], fuji: 0x1F5FB, lollipop: 0x1F36D, } end
# frozen_string_literal: true module TaskVault class Task < SubComponent STATES = [ :created, :queued, :ready, :running, :finished, :error, :waiting, :canceled, :timedout, :unknown ].freeze after :set_initial_priority, :priority= after :status_change, :status= after :calculate_start_time, :delay=, :repeat= attr_int :id attr_string :name, default: '', serialize: true, always: true attr_float :delay, allow_nil: true, default: 0, serialize: true, always: true attr_time :start_at, fallback: Time.now attr_float_between 0, nil, :weight, default: 1, serialize: true, always: true attr_int_between 0, nil, :run_limit, default: nil, allow_nil: true, serialize: true, always: true attr_int_between 0, 6, :priority, default: 3, serialize: true, always: true attr_float_between 0, nil, :timeout, allow_nil: true, default: nil, serialize: true, always: true attr_element_of STATES, :status, default: :created, fallback: :unknown attr_of [String, Fixnum, TrueClass, FalseClass], :repeat, serialize: true, always: true attr_int_between 1, nil, :elevate_interval, default: nil, allow_nil: true, serialize: true, always: true attr_reader :run_count, :initial_priority, :timer, :times def stop @timer.stop if @timer.active? super end def cancel queue_msg('Cancel has been called. Task should end shortly.', severity: :info) self.status = :canceled !running? end def rerun return false if parent.nil? || [:created, :queued, :running, :ready, :waiting].any? { |s| s == status } queue_msg('Rerun has been called. Task should begin to run again now.', severity: :info) @priority = @initial_priority @run_limit += 1 if @run_limit @parent.rerun(id) true end def elevate @priority = BBLib.keep_between(@priority - 1, 0, 6) set_time :last_elevated end def elevate_check(parent_interval = nil) interval = @elevate_interval || parent_interval return unless interval elevate if Time.now >= ((last_elevated || created) + interval) end def set_time(type, time = Time.now) return nil unless @times.include?(type) && time.is_a?(Time) @times[type] = time end def reload(args) _lazy_init(args) end def details(*attributes) attributes.map do |a| [a, (respond_to?(a.to_sym) ? send(a.to_sym) : nil)] end.to_h end def calculate_start_time return false if status == :canceled rpt = true self.start_at = Time.now + @delay if run_count.zero? if @repeat.nil? || @repeat == false || run_limit && run_limit.positive? && run_count >= run_limit || @repeat.is_a?(Numeric) && @repeat <= @run_count rpt = false elsif @repeat == true self.start_at = Time.now elsif @repeat.is_a?(String) if @repeat.start_with?('every') && run_count.positive? self.start_at = Time.at(started + @repeat.parse_duration(output: :sec)) elsif @repeat.start_with?('after') && run_count.positive? self.start_at = Time.at(Time.now + @repeat.parse_duration(output: :sec)) elsif BBLib::Cron.valid?(@repeat) self.start_at = BBLib::Cron.next(@repeat, time: (run_count.positive? ? Time.now : start_at)) end end rpt end def timeout_check if running? && @timeout && Time.now - started > timeout self.status = :timed_out true else false end end def stats @timer.stats :default end def save(path = Dir.pwd, format: :yml) super(path, format: format, name: @name) end def method_missing(*args) if @times.include?(args.first) @times[args.first] else super end end def respond_to_missing?(method, include_private = false) @times.include?(method) || super end def self.load(data, parent: nil, namespace: Tasks) super end protected def lazy_setup super @times = { queued: nil, added: nil, started: nil, finished: nil, last_elevated: nil, created: Time.now } @run_count = 0 @initial_priority = 3 @timer = BBLib::TaskTimer.new self.delay = 0 self.repeat = 1 end def init_thread @thread = Thread.new do begin @timer.start run @timer.stop self.status = :finished rescue => e @timer.stop self.status = :error queue_msg e end end self.status = :running @run_count += 1 end def hide_on_inspect super + [:@history] end def add_history(value, **other) @history.push({ value: value, time: Time.now, run_count: @run_count }.merge(**other)) @history.shift while @history.size > @history_limit value end def msg_metadata { id: @id, name: @name, status: @status, run_count: @run_count } end def set_initial_priority @initial_priority = @priority end def status_change case @status when :created set_time :created, Time.now when :queued set_time :queued, Time.now when :ready set_time :added, Time.now set_time :last_elevated, Time.now when :running set_time :started, Time.now when :finished || :error || :canceled || :timeout set_time :finished, Time.now stop end end end end Fixed timeout naming and bad syntax in status change handler. # frozen_string_literal: true module TaskVault class Task < SubComponent STATES = [ :created, :queued, :ready, :running, :finished, :error, :waiting, :canceled, :timeout, :unknown ].freeze after :set_initial_priority, :priority= after :status_change, :status= after :calculate_start_time, :delay=, :repeat= attr_int :id attr_string :name, default: '', serialize: true, always: true attr_float :delay, allow_nil: true, default: 0, serialize: true, always: true attr_time :start_at, fallback: Time.now attr_float_between 0, nil, :weight, default: 1, serialize: true, always: true attr_int_between 0, nil, :run_limit, default: nil, allow_nil: true, serialize: true, always: true attr_int_between 0, 6, :priority, default: 3, serialize: true, always: true attr_float_between 0, nil, :timeout, allow_nil: true, default: nil, serialize: true, always: true attr_element_of STATES, :status, default: :created, fallback: :unknown attr_of [String, Fixnum, TrueClass, FalseClass], :repeat, serialize: true, always: true attr_int_between 1, nil, :elevate_interval, default: nil, allow_nil: true, serialize: true, always: true attr_reader :run_count, :initial_priority, :timer, :times def stop @timer.stop if @timer.active? super end def cancel queue_msg('Cancel has been called. Task should end shortly.', severity: :info) self.status = :canceled !running? end def rerun return false if parent.nil? || [:created, :queued, :running, :ready, :waiting].any? { |s| s == status } queue_msg('Rerun has been called. Task should begin to run again now.', severity: :info) @priority = @initial_priority @run_limit += 1 if @run_limit @parent.rerun(id) true end def elevate @priority = BBLib.keep_between(@priority - 1, 0, 6) set_time :last_elevated end def elevate_check(parent_interval = nil) interval = @elevate_interval || parent_interval return unless interval elevate if Time.now >= ((last_elevated || created) + interval) end def set_time(type, time = Time.now) return nil unless @times.include?(type) && time.is_a?(Time) @times[type] = time end def reload(args) _lazy_init(args) end def details(*attributes) attributes.map do |a| [a, (respond_to?(a.to_sym) ? send(a.to_sym) : nil)] end.to_h end def calculate_start_time return false if status == :canceled rpt = true self.start_at = Time.now + @delay if run_count.zero? if @repeat.nil? || @repeat == false || run_limit && run_limit.positive? && run_count >= run_limit || @repeat.is_a?(Numeric) && @repeat <= @run_count rpt = false elsif @repeat == true self.start_at = Time.now elsif @repeat.is_a?(String) if @repeat.start_with?('every') && run_count.positive? self.start_at = Time.at(started + @repeat.parse_duration(output: :sec)) elsif @repeat.start_with?('after') && run_count.positive? self.start_at = Time.at(Time.now + @repeat.parse_duration(output: :sec)) elsif BBLib::Cron.valid?(@repeat) self.start_at = BBLib::Cron.next(@repeat, time: (run_count.positive? ? Time.now : start_at)) end end rpt end def timeout_check if running? && @timeout && Time.now - started > timeout self.status = :timeout true else false end end def stats @timer.stats :default end def save(path = Dir.pwd, format: :yml) super(path, format: format, name: @name) end def method_missing(*args) if @times.include?(args.first) @times[args.first] else super end end def respond_to_missing?(method, include_private = false) @times.include?(method) || super end def self.load(data, parent: nil, namespace: Tasks) super end protected def lazy_setup super @times = { queued: nil, added: nil, started: nil, finished: nil, last_elevated: nil, created: Time.now } @run_count = 0 @initial_priority = 3 @timer = BBLib::TaskTimer.new self.delay = 0 self.repeat = 1 end def init_thread @thread = Thread.new do begin @timer.start run @timer.stop self.status = :finished rescue => e @timer.stop self.status = :error queue_msg e end end self.status = :running @run_count += 1 end def hide_on_inspect super + [:@history] end def add_history(value, **other) @history.push({ value: value, time: Time.now, run_count: @run_count }.merge(**other)) @history.shift while @history.size > @history_limit value end def msg_metadata { id: @id, name: @name, status: @status, run_count: @run_count } end def set_initial_priority @initial_priority = @priority end def status_change case @status when :created set_time :created, Time.now when :queued set_time :queued, Time.now when :ready set_time :added, Time.now set_time :last_elevated, Time.now when :running set_time :started, Time.now when :finished, :error, :canceled, :timeout stop set_time :finished, Time.now end end end end
# Copyright (c) 2012, Peter Allin <peter@peca.dk> All rights reserved. # See LICENSE file for licensing information. module Conversation class DialogFactory def calendar(options={},&spec) c = Calendar.new(options) c.instance_eval &spec if spec return c end def checklist(options={}, &spec) c = Checklist.new(options) c.instance_eval &spec if spec return c end def radiolist(options={}, &spec) c = Radiolist.new(options) c.instance_eval &spec if spec return c end def menu(options={}, &spec) c = Menu.new(options) c.instance_eval &spec if spec return c end def yesno(options={}, &spec) yn = YesNo.new(options) yn.instance_eval &spec if spec return yn end def textbox(options={}, &spec) tb = TextBox.new(options) tb.instance_eval &spec if spec return tv end def msgbox(options={}, &spec) mb = MsgBox.new(options) mb.instance_eval &spec if spec return mb end end end Refactored DialogFactory for less duplication # Copyright (c) 2012, Peter Allin <peter@peca.dk> All rights reserved. # See LICENSE file for licensing information. module Conversation class DialogFactory def calendar(options={},&spec) make_dialog(Calendar, options, &spec) end def checklist(options={}, &spec) make_dialog(Checklist, options, &spec) end def radiolist(options={}, &spec) make_dialog(Radiolist, options, &spec) end def menu(options={}, &spec) make_dialog(Menu, options, &spec) end def yesno(options={}, &spec) make_dialog(YesNo, options, &spec) end def textbox(options={}, &spec) make_dialog(TextBox, options, &spec) end def msgbox(options={}, &spec) make_dialog(MsgBox, options, &spec) end private def make_dialog(cls, options, &spec) d = cls.new(options) d.instance_eval &spec if spec return d end end end
module Linguist VERSION = "4.7.4" end Bumping version module Linguist VERSION = "4.7.5" end
Add blog drop to repository. class Liquid::BlogDrop < Liquid::BaseDrop liquid_attributes << :title << :description << :id << :updated_at end
module Lobbyist class Version MAJOR = 0 unless defined? Lobbyist::Version::MAJOR MINOR = 8 unless defined? Lobbyist::Version::MINOR PATCH = 56 unless defined? Lobbyist::Version::PATCH class << self # @return [String] def to_s [MAJOR, MINOR, PATCH].compact.join('.') end end end end Updating version to 0.8.57 module Lobbyist class Version MAJOR = 0 unless defined? Lobbyist::Version::MAJOR MINOR = 8 unless defined? Lobbyist::Version::MINOR PATCH = 57 unless defined? Lobbyist::Version::PATCH class << self # @return [String] def to_s [MAJOR, MINOR, PATCH].compact.join('.') end end end end
# frozen_string_literal: true class Loglevel VERSION = '0.3.0'.freeze end Bump to 0.4.0 # frozen_string_literal: true class Loglevel VERSION = '0.4.0'.freeze end
module Whm module Args # Check the included hash for the included parameters, and ensure they aren't blank. # # ==== Example # # class User # def initialize # requires!(options, :username, :password) # end # end # # >> User.new # ArgumentError: Missing required parameter: username # # >> User.new(:username => "john") # ArgumentError: Missing required parameter: password def requires!(hash, *params) params.each do |param| if param.is_a?(Array) raise Whm::ArgumentError.new("Missing required parameter: #{param.first}") unless hash.has_key?(param.first) raise Whm::ArgumentError.new("Required parameter cannot be blank: #{param.first}") if hash[param.first].blank? else raise Whm::ArgumentError.new("Missing required parameter: #{param}") unless hash.has_key?(param) raise Whm::ArgumentError.new("Required parameter cannot be blank: #{param}") if hash[param].blank? end end end # Checks to see if supplied params (which are booleans) contain # either a 1 ("Yes") or 0 ("No") value. def booleans!(hash, *params) params.each do |param| if param.is_a?(Array) raise ArgumentError.new("Boolean parameter must be \"1\" or \"0\": #{param.first}") unless hash[param.first].to_s.match(/(1|0)/) else raise ArgumentError.new("Boolean parameter must be \"1\" or \"0\": #{param}") unless hash[param].to_s.match(/(1|0)/) end end end # Checks the hash to see if the hash includes any parameter # which is not included in the list of valid parameters. # # ==== Example # # class User # def initialize # valid_options!(options, :username) # end # end # # >> User.new(:username => "josh") # => #<User:0x18a1190 @username="josh"> # # >> User.new(:username => "josh", :credit_card => "5105105105105100") # ArgumentError: Not a valid parameter: credit_card def valid_options!(hash, *params) keys = hash.keys keys.each do |key| raise ArgumentError.new("Not a valid parameter: #{key}") unless params.include?(key) end end end end Duh, .blank? is rails module Whm module Args # Check the included hash for the included parameters, and ensure they aren't blank. # # ==== Example # # class User # def initialize # requires!(options, :username, :password) # end # end # # >> User.new # ArgumentError: Missing required parameter: username # # >> User.new(:username => "john") # ArgumentError: Missing required parameter: password def requires!(hash, *params) params.each do |param| if param.is_a?(Array) raise Whm::ArgumentError.new("Missing required parameter: #{param.first}") unless hash.has_key?(param.first) raise Whm::ArgumentError.new("Required parameter cannot be blank: #{param.first}") if (hash[param.first].nil? || hash[param.first].empty?) else raise Whm::ArgumentError.new("Missing required parameter: #{param}") unless hash.has_key?(param) raise Whm::ArgumentError.new("Required parameter cannot be blank: #{param}") if (hash[param].nil? || hash[param].empty?) end end end # Checks to see if supplied params (which are booleans) contain # either a 1 ("Yes") or 0 ("No") value. def booleans!(hash, *params) params.each do |param| if param.is_a?(Array) raise ArgumentError.new("Boolean parameter must be \"1\" or \"0\": #{param.first}") unless hash[param.first].to_s.match(/(1|0)/) else raise ArgumentError.new("Boolean parameter must be \"1\" or \"0\": #{param}") unless hash[param].to_s.match(/(1|0)/) end end end # Checks the hash to see if the hash includes any parameter # which is not included in the list of valid parameters. # # ==== Example # # class User # def initialize # valid_options!(options, :username) # end # end # # >> User.new(:username => "josh") # => #<User:0x18a1190 @username="josh"> # # >> User.new(:username => "josh", :credit_card => "5105105105105100") # ArgumentError: Not a valid parameter: credit_card def valid_options!(hash, *params) keys = hash.keys keys.each do |key| raise ArgumentError.new("Not a valid parameter: #{key}") unless params.include?(key) end end end end
module Madness # Handle a single markdown document. class Document include ServerHelper using StringRefinements attr_reader :base, :path def initialize(path) @path = path @base = path.empty? ? docroot : "#{docroot}/#{path}" @base.chomp! '/' end # Return :readme, :file or :empty def type set_base_attributes unless @type @type end # Return the path to the actual markdown file def file set_base_attributes unless @file @file end # Return the path to the document directory def dir set_base_attributes unless @dir @dir end # Return the HTML for that document def content @content ||= content! end # Return the HTML for that document, force re-read. def content! type == :empty ? '' : markdown_to_html end # Return a reasonable HTML title for the file or directory def title if type == :readme result = File.basename File.dirname(file) else result = File.basename(file,'.md') end result.tr '-', ' ' end private # Identify file, dir and type. # :readme - in case the path is a directory, and it contains index.md # or README.md # :file - in case the path is a *.md file # :empty - in any other case, we don't know. def set_base_attributes @dir = docroot @type = :empty @file = '' if File.directory? base @dir = base @type = :readme if File.exist? "#{base}/index.md" @file = "#{base}/index.md" elsif File.exist? "#{base}/README.md" @file = "#{base}/README.md" else @type = :empty end elsif File.exist? "#{base}.md" @file = "#{base}.md" @dir = File.dirname file @type = :file end end def markdown @markdown ||= File.read file end # Convert markdown to HTML, with some additional processing: # 1. Add anchors to headers # 2. Syntax highilghting # 3. Prepend H1 if needed def markdown_to_html doc = CommonMarker.render_doc markdown, :DEFAULT, [:table] doc.walk do |node| if node.type == :header anchor = CommonMarker::Node.new(:inline_html) anchor_id = node.first_child.string_content.to_slug anchor.string_content = "<a id='#{anchor_id}'></a>" node.prepend_child anchor end end html = doc.to_html html = syntax_highlight(html) if config.highlighter html = prepend_h1(html) if config.auto_h1 html end # If the document does not start with an H1 tag, add it. def prepend_h1(html) unless html[0..3] == "<h1>" html = "<h1>#{title}</h1>\n#{html}" end html end # Apply syntax highlighting with CodeRay. This will parse for any # <code class='LANG'> sections in the HTML, pass it to CodeRay for # highlighting. # Since CodeRay adds another HTML escaping, on top of what RDiscount # does, we unescape it before passing it to CodeRay. # # Open StackOverflow question: # http://stackoverflow.com/questions/37771279/prevent-double-escaping-with-coderay-and-rdiscount def syntax_highlight(html) line_numbers = config.line_numbers ? :table : nil opts = { css: :style, wrap: nil, line_numbers: line_numbers } html.gsub(/\<code class="language-(.+?)"\>(.+?)\<\/code\>/m) do lang, code = $1, $2 code = CGI.unescapeHTML code CodeRay.scan(code, lang).html opts end end end end attempt to satisfy code climate module Madness # Handle a single markdown document. class Document include ServerHelper using StringRefinements attr_reader :base, :path def initialize(path) @path = path @base = path.empty? ? docroot : "#{docroot}/#{path}" @base.chomp! '/' end # Return :readme, :file or :empty def type set_base_attributes unless @type @type end # Return the path to the actual markdown file def file set_base_attributes unless @file @file end # Return the path to the document directory def dir set_base_attributes unless @dir @dir end # Return the HTML for that document def content @content ||= content! end # Return the HTML for that document, force re-read. def content! type == :empty ? '' : markdown_to_html end # Return a reasonable HTML title for the file or directory def title if type == :readme result = File.basename File.dirname(file) else result = File.basename(file,'.md') end result.tr '-', ' ' end private # Identify file, dir and type. # :readme - in case the path is a directory, and it contains index.md # or README.md # :file - in case the path is a *.md file # :empty - in any other case, we don't know. def set_base_attributes @dir = docroot @type = :empty @file = '' if File.directory? base set_base_attributes_for_directory elsif File.exist? "#{base}.md" @file = "#{base}.md" @dir = File.dirname file @type = :file end end def set_base_attributes_for_directory @dir = base @type = :readme if File.exist? "#{base}/index.md" @file = "#{base}/index.md" elsif File.exist? "#{base}/README.md" @file = "#{base}/README.md" else @type = :empty end end def markdown @markdown ||= File.read file end # Convert markdown to HTML, with some additional processing: # 1. Add anchors to headers # 2. Syntax highilghting # 3. Prepend H1 if needed def markdown_to_html doc = CommonMarker.render_doc markdown, :DEFAULT, [:table] doc.walk do |node| if node.type == :header anchor = CommonMarker::Node.new(:inline_html) anchor_id = node.first_child.string_content.to_slug anchor.string_content = "<a id='#{anchor_id}'></a>" node.prepend_child anchor end end html = doc.to_html html = syntax_highlight(html) if config.highlighter html = prepend_h1(html) if config.auto_h1 html end # If the document does not start with an H1 tag, add it. def prepend_h1(html) unless html[0..3] == "<h1>" html = "<h1>#{title}</h1>\n#{html}" end html end # Apply syntax highlighting with CodeRay. This will parse for any # <code class='LANG'> sections in the HTML, pass it to CodeRay for # highlighting. # Since CodeRay adds another HTML escaping, on top of what RDiscount # does, we unescape it before passing it to CodeRay. # # Open StackOverflow question: # http://stackoverflow.com/questions/37771279/prevent-double-escaping-with-coderay-and-rdiscount def syntax_highlight(html) line_numbers = config.line_numbers ? :table : nil opts = { css: :style, wrap: nil, line_numbers: line_numbers } html.gsub(/\<code class="language-(.+?)"\>(.+?)\<\/code\>/m) do lang, code = $1, $2 code = CGI.unescapeHTML code CodeRay.scan(code, lang).html opts end end end end
module Mangabey VERSION = '0.0.1' end Working on new version now.. module Mangabey VERSION = '0.0.2' end
$" = [] $* = ARGV $SAFE = 0 TRUE = true FALSE = false NIL = nil RUBY_VERSION = "1.8.5" VERSION = "1.8.5" TOPLEVEL_BINDING = self module Kernel def nil? false end def fork raise NotImplementedError, "the fork() function is unimplemented on this machine" end def =~ x false end def singleton_method_added symbol end def singleton_method_removed symbol end def singleton_method_undefined symbol end #private def require(file_name) return false if ($".include?(file_name) || $".include?(file_name + ".rb")) load(file_name); end #private def load(file_name) if __load_with_reflection__(file_name) return true end # $:.each do |path| # return true if load_rb_file(path, file_name) # end raise LoadError, "no such file to load -- " + file_name end private def method_added symbol end end class Object # def to_a # [self] # end alias type :class private def initialize end end module Enumerable def each_with_index i = 0; each {|x| yield x, i; i = i + 1} end def to_a arr = [] each{|obj| arr <<obj} return arr end alias entries :to_a def inject(*args) if args.size == 0 then vals = to_a memo = vals[0] vals[1..vals.size-1].each {|obj| memo = yield(memo, obj)} return memo elsif args.size == 1 then memo = args[0] each {|obj| memo = yield(memo, obj)} return memo else nil end end def collect arr = [] each{|obj| arr << yield(obj)} return arr end alias map :collect def max(&proc) proc = lambda { |a, b| a <=> b } unless block_given? max = nil each {|obj| max = obj if max.nil? || proc.call(max, obj) < 0} max end def min(&proc) proc = lambda { |a, b| a <=> b } unless block_given? min = nil each {|obj| min = obj if min.nil? || proc.call(min, obj) > 0} min end end class Array alias reject! delete_if def reject a = [] each {|x| if !yield x a << x end } a end # def to_a # self # end def join(sepString="") return to_s if sepString.nil? || sepString == "" result = "" (length - 1).times do |index| result += (self[index].to_s) + sepString end result += self[length - 1].to_s if length != 0 result end alias map! collect! alias size length alias to_ary to_a alias to_s inspect def inspect str = "[" is_first = true self.each() { |x| if (!is_first) str << ", " end is_first = false str << x.inspect } str << "]" end end class File SEPARATOR = '/' def File.join *aString s = "" first = true aString.each {|x| if !first s += File::SEPARATOR end s+= x first = false } s end end class IO def each while !eof yield gets end close end end class Time include Comparable end class Hash def each ks = keys ks.each {|k| yield([k, self[k]])} end def each_key ks = keys ks.each {|k| yield(k)} end def each_value vs = values vs.each {|k| yield(k)} end def empty? length == 0 end alias each_pair each def to_a res = [] each_pair do |k, v| item = [] item << k item << v res << item end res end def inspect r = '{' is_first = true each_pair do |k, v| if !is_first r << ", " end is_first = false r << k.inspect r << '=>' r << v.inspect end r << '}' end alias to_s inspect def invert h = {} each {|k, v| h[v] = k} h end def update other other.each {|k, v| self[k] = v} self end alias merge! update def merge other clone.merge!(other) end def index value each {|k, v| return k if value == v } return nil end end class Symbol alias to_s id2name end class << self def to_s return "main" end def public Object.public end def private Object.private end def protected Object.protected end end class Fixnum def is_alpha_numeric return (self>=?0 && self<=?9) || (self>=?a && self<=?z) || (self>=?A && self<=?Z) end end module Comparable def >=(value) compare = (self <=> value) return compare != -1 and compare != nil end def ==(value) compare = (self <=> value) return compare == 0 end def <=(value) compare = (self <=> value) return compare != 1 and compare != nil end def >(value) compare = (self <=> value) return compare == 1 end def <(value) compare = (self <=> value) return compare == -1 end def between?(a, b) self >= a && self <= b end end class Numeric include Comparable def floor self.to_f.floor end def abs return -self if (self <=> 0) == -1 self end def div value (self/value).floor end def divmod(value) [(self/value).floor, self % value] end def integer? false end alias eql? :== def modulo(value) self % value end def nonzero? return nil if self == 0 self end def zero? return true if self == 0 false end def remainder(value) self_sign = (self < 0) value_sign = (value < 0) return self % value if self_sign == value_sign self % (-value) end end class Integer < Numeric def to_i return self end alias to_int to_i #Returns the Integer equal to int + 1 def next self + 1 end #Synonym for Integer#next def succ self + 1 end #Always returns true def integer? true end def upto(to) a = self while a <= to yield a a += 1 end end def downto(to) a = self while a >= to yield a a -= 1 end end def size 4 end def integer? true end end class Fixnum < Integer def to_i self end alias inspect to_s end class NilClass #Returns false def &(anObject) false end #Returns false if anObject is nil or false, true otherwise def ^(anObject) anObject ? true : false end #Returns false if anObject is nil or false, true otherwise def |(anObject) anObject ? true : false end #Always returns true def nil? true end #Always returns an empty array def to_a [] end #Always returns zero def to_i 0 end def to_f 0.0 end #Always returns the empty string def to_s "" end def inspect "nil" end alias to_str to_s end class TrueClass #Returns false if anObject is nil or false, true otherwise def &(anObject) anObject ? true : false end #Returns true if anObject is nil or false, false otherwise def ^(anObject) anObject ? false : true end #Returns true def |(anObject) true end def to_s "true" end def inspect "true" end end class FalseClass #Returns false def &(anObject) false end #If anObject is nil or false, returns false; otherwise, returns true def ^(anObject) anObject ? true : false end #Returns false if anObject is nil or false; true otherwise def |(anObject) anObject ? true : false end def to_s "false" end def inspect "false" end end class String include Comparable def to_s return self end def empty? length == 0 end def inspect '"' + to_s + '"' end #from rubinius # justify left = -1, center = 0, right = 1 def justify_string(width, str, justify) return self if width <= length pad = width - length out = str.to_str * (pad / str.length) out << str[0, pad - out.length] if out.length < pad # Left justification return self << out if justify == -1 # Right justification return out << self if justify == 1 # and finially center split = (width / 2) - (length / 2) return out.insert(split-((width-length)%2), self) end #from rubinius def rjust(width, str=" ") justify_string(width, str, 1) end #from rubinius def ljust(width, str=" ") justify_string(width, str, -1) end #from rubinius def center(width, str=" ") justify_string(width, str, 0) end alias to_str to_s alias size length end [#243]Fixed issue with stack overflow $" = [] $* = ARGV $SAFE = 0 TRUE = true FALSE = false NIL = nil RUBY_VERSION = "1.8.5" VERSION = "1.8.5" TOPLEVEL_BINDING = self module Kernel def nil? false end def fork raise NotImplementedError, "the fork() function is unimplemented on this machine" end def =~ x false end def singleton_method_added symbol end def singleton_method_removed symbol end def singleton_method_undefined symbol end #private def require(file_name) return false if ($".include?(file_name) || $".include?(file_name + ".rb")) load(file_name); end #private def load(file_name) if __load_with_reflection__(file_name) return true end # $:.each do |path| # return true if load_rb_file(path, file_name) # end raise LoadError, "no such file to load -- " + file_name end private def method_added symbol end end class Object # def to_a # [self] # end alias type :class private def initialize end end module Enumerable def each_with_index i = 0; each {|x| yield x, i; i = i + 1} end def to_a arr = [] each{|obj| arr <<obj} return arr end alias entries :to_a def inject(*args) if args.size == 0 then vals = to_a memo = vals[0] vals[1..vals.size-1].each {|obj| memo = yield(memo, obj)} return memo elsif args.size == 1 then memo = args[0] each {|obj| memo = yield(memo, obj)} return memo else nil end end def collect arr = [] each{|obj| arr << yield(obj)} return arr end alias map :collect def max(&proc) proc = lambda { |a, b| a <=> b } unless block_given? max = nil each {|obj| max = obj if max.nil? || proc.call(max, obj) < 0} max end def min(&proc) proc = lambda { |a, b| a <=> b } unless block_given? min = nil each {|obj| min = obj if min.nil? || proc.call(min, obj) > 0} min end end class Array alias reject! delete_if def reject a = [] each {|x| if !yield x a << x end } a end # def to_a # self # end def join(sepString="") return to_s if sepString.nil? || sepString == "" result = "" (length - 1).times do |index| result += (self[index].to_s) + sepString end result += self[length - 1].to_s if length != 0 result end alias map! collect! alias size length alias to_ary to_a def inspect str = "[" is_first = true self.each() { |x| if (!is_first) str << ", " end is_first = false str << x.inspect } str << "]" end alias to_s inspect end class File SEPARATOR = '/' def File.join *aString s = "" first = true aString.each {|x| if !first s += File::SEPARATOR end s+= x first = false } s end end class IO def each while !eof yield gets end close end end class Time include Comparable end class Hash def each ks = keys ks.each {|k| yield([k, self[k]])} end def each_key ks = keys ks.each {|k| yield(k)} end def each_value vs = values vs.each {|k| yield(k)} end def empty? length == 0 end alias each_pair each def to_a res = [] each_pair do |k, v| item = [] item << k item << v res << item end res end def inspect r = '{' is_first = true each_pair do |k, v| if !is_first r << ", " end is_first = false r << k.inspect r << '=>' r << v.inspect end r << '}' end alias to_s inspect def invert h = {} each {|k, v| h[v] = k} h end def update other other.each {|k, v| self[k] = v} self end alias merge! update def merge other clone.merge!(other) end def index value each {|k, v| return k if value == v } return nil end end class Symbol alias to_s id2name end class << self def to_s return "main" end def public Object.public end def private Object.private end def protected Object.protected end end class Fixnum def is_alpha_numeric return (self>=?0 && self<=?9) || (self>=?a && self<=?z) || (self>=?A && self<=?Z) end end module Comparable def >=(value) compare = (self <=> value) return compare != -1 and compare != nil end def ==(value) compare = (self <=> value) return compare == 0 end def <=(value) compare = (self <=> value) return compare != 1 and compare != nil end def >(value) compare = (self <=> value) return compare == 1 end def <(value) compare = (self <=> value) return compare == -1 end def between?(a, b) self >= a && self <= b end end class Numeric include Comparable def floor self.to_f.floor end def abs return -self if (self <=> 0) == -1 self end def div value (self/value).floor end def divmod(value) [(self/value).floor, self % value] end def integer? false end alias eql? :== def modulo(value) self % value end def nonzero? return nil if self == 0 self end def zero? return true if self == 0 false end def remainder(value) self_sign = (self < 0) value_sign = (value < 0) return self % value if self_sign == value_sign self % (-value) end end class Integer < Numeric def to_i return self end alias to_int to_i #Returns the Integer equal to int + 1 def next self + 1 end #Synonym for Integer#next def succ self + 1 end #Always returns true def integer? true end def upto(to) a = self while a <= to yield a a += 1 end end def downto(to) a = self while a >= to yield a a -= 1 end end def size 4 end def integer? true end end class Fixnum < Integer def to_i self end alias inspect to_s end class NilClass #Returns false def &(anObject) false end #Returns false if anObject is nil or false, true otherwise def ^(anObject) anObject ? true : false end #Returns false if anObject is nil or false, true otherwise def |(anObject) anObject ? true : false end #Always returns true def nil? true end #Always returns an empty array def to_a [] end #Always returns zero def to_i 0 end def to_f 0.0 end #Always returns the empty string def to_s "" end def inspect "nil" end alias to_str to_s end class TrueClass #Returns false if anObject is nil or false, true otherwise def &(anObject) anObject ? true : false end #Returns true if anObject is nil or false, false otherwise def ^(anObject) anObject ? false : true end #Returns true def |(anObject) true end def to_s "true" end def inspect "true" end end class FalseClass #Returns false def &(anObject) false end #If anObject is nil or false, returns false; otherwise, returns true def ^(anObject) anObject ? true : false end #Returns false if anObject is nil or false; true otherwise def |(anObject) anObject ? true : false end def to_s "false" end def inspect "false" end end class String include Comparable def to_s return self end def empty? length == 0 end def inspect '"' + to_s + '"' end #from rubinius # justify left = -1, center = 0, right = 1 def justify_string(width, str, justify) return self if width <= length pad = width - length out = str.to_str * (pad / str.length) out << str[0, pad - out.length] if out.length < pad # Left justification return self << out if justify == -1 # Right justification return out << self if justify == 1 # and finially center split = (width / 2) - (length / 2) return out.insert(split-((width-length)%2), self) end #from rubinius def rjust(width, str=" ") justify_string(width, str, 1) end #from rubinius def ljust(width, str=" ") justify_string(width, str, -1) end #from rubinius def center(width, str=" ") justify_string(width, str, 0) end alias to_str to_s alias size length end
# encoding: utf-8 require 'mapnik' require 'yaml' require 'fileutils' require 'logger' require 'mapnik_legendary/feature' require 'mapnik_legendary/docwriter' module MapnikLegendary DEFAULT_ZOOM = 17 def self.generate_legend(legend_file, map_file, options) log = Logger.new(STDERR) legend = YAML.load(File.read(legend_file)) if legend.key?('fonts_dir') Mapnik::FontEngine.register_fonts(legend['fonts_dir']) end map = Mapnik::Map.from_xml(File.read(map_file), false, File.dirname(map_file)) map.width = legend['width'] map.height = legend['height'] map.srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over' if legend.key?('background') map.background = Mapnik::Color.new(legend['background']) end layer_styles = [] map.layers.each do |l| layer_styles.push(name: l.name, style: l.styles.map { |s| s } # get them out of the collection ) end docs = Docwriter.new docs.image_width = legend['width'] legend['features'].each_with_index do |feature, idx| # TODO: use a proper csv library rather than .join(",") ! zoom = options.zoom || feature['zoom'] || DEFAULT_ZOOM feature = Feature.new(feature, zoom, map, legend['extra_tags']) map.zoom_to_box(feature.envelope) map.layers.clear feature.parts.each do |part| if part.layers.nil? log.warn "Can't find any layers defined for a part of #{feature.name}" next end part.layers.each do |layer_name| ls = layer_styles.select { |l| l[:name] == layer_name } if ls.empty? log.warn "Can't find #{layer_name} in the xml file" next else ls.each do |layer_style| l = Mapnik::Layer.new(layer_name, map.srs) datasource = Mapnik::Datasource.create(type: 'csv', inline: part.to_csv) l.datasource = datasource layer_style[:style].each do |style_name| l.styles << style_name end map.layers << l end end end end FileUtils.mkdir_p('output') # map.zoom_to_box(Mapnik::Envelope.new(0,0,1,1)) id = feature.name || "legend-#{idx}" filename = File.join(Dir.pwd, 'output', "#{id}-#{zoom}.png") i = 0 while File.exist?(filename) && !options.overwrite i += 1 filename = File.join(Dir.pwd, 'output', "#{id}-#{zoom}-#{i}.png") end map.render_to_file(filename, 'png256:t=2') docs.add File.basename(filename), feature.description end f = File.open(File.join(Dir.pwd, 'output', 'docs.html'), 'w') f.write(docs.to_html) f.close title = legend.key?('title') ? legend['title'] : 'Legend' docs.to_pdf(File.join(Dir.pwd, 'output', 'legend.pdf'), title) end end Intercept and handle missing attribute errors from the CSV plugin # encoding: utf-8 require 'mapnik' require 'yaml' require 'fileutils' require 'logger' require 'mapnik_legendary/feature' require 'mapnik_legendary/docwriter' module MapnikLegendary DEFAULT_ZOOM = 17 def self.generate_legend(legend_file, map_file, options) log = Logger.new(STDERR) legend = YAML.load(File.read(legend_file)) if legend.key?('fonts_dir') Mapnik::FontEngine.register_fonts(legend['fonts_dir']) end map = Mapnik::Map.from_xml(File.read(map_file), false, File.dirname(map_file)) map.width = legend['width'] map.height = legend['height'] map.srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over' if legend.key?('background') map.background = Mapnik::Color.new(legend['background']) end layer_styles = [] map.layers.each do |l| layer_styles.push(name: l.name, style: l.styles.map { |s| s } # get them out of the collection ) end docs = Docwriter.new docs.image_width = legend['width'] legend['features'].each_with_index do |feature, idx| # TODO: use a proper csv library rather than .join(",") ! zoom = options.zoom || feature['zoom'] || DEFAULT_ZOOM feature = Feature.new(feature, zoom, map, legend['extra_tags']) map.zoom_to_box(feature.envelope) map.layers.clear feature.parts.each do |part| if part.layers.nil? log.warn "Can't find any layers defined for a part of #{feature.name}" next end part.layers.each do |layer_name| ls = layer_styles.select { |l| l[:name] == layer_name } if ls.empty? log.warn "Can't find #{layer_name} in the xml file" next else ls.each do |layer_style| l = Mapnik::Layer.new(layer_name, map.srs) datasource = Mapnik::Datasource.create(type: 'csv', inline: part.to_csv) l.datasource = datasource layer_style[:style].each do |style_name| l.styles << style_name end map.layers << l end end end end FileUtils.mkdir_p('output') # map.zoom_to_box(Mapnik::Envelope.new(0,0,1,1)) id = feature.name || "legend-#{idx}" filename = File.join(Dir.pwd, 'output', "#{id}-#{zoom}.png") i = 0 while File.exist?(filename) && !options.overwrite i += 1 filename = File.join(Dir.pwd, 'output', "#{id}-#{zoom}-#{i}.png") end begin map.render_to_file(filename, 'png256:t=2') rescue RuntimeError => e r = /^CSV Plugin: no attribute '(?<key>[^']*)'/ match_data = r.match(e.message) if match_data log.error "'#{match_data[:key]}' is a key needed for the '#{feature.name}' feature." log.error "Try adding '#{match_data[:key]}' to the extra_tags list." next else raise e end end docs.add File.basename(filename), feature.description end f = File.open(File.join(Dir.pwd, 'output', 'docs.html'), 'w') f.write(docs.to_html) f.close title = legend.key?('title') ? legend['title'] : 'Legend' docs.to_pdf(File.join(Dir.pwd, 'output', 'legend.pdf'), title) end end
require_relative 'request' require 'faraday' require 'json' require 'base64' module Marketcloud class File < Request def self.plural "files" end # Create a new file in the Marketcloud CDN # @param name a human friendly name # @param filename a filename # @param file_url a URL to a file # @param description the description of the file # @param slug a URL-friendly slug # @return a file def self.create(name, filename, file_url, description, slug) file = ::File.open(file_url) new_file = perform_request(api_url(self.plural, {}), :post, { name: name, filename: filename, file: Base64.encode64(file.read), description: description, slug: slug }, true) if new_file new new_file['data'] else nil end end end end extending mime-type require_relative 'request' require 'faraday' require 'json' require 'base64' module Marketcloud class File < Request def self.plural "files" end # Create a new file in the Marketcloud CDN # @param name a human friendly name # @param filename a filename # @param file_url a URL to a file # @param description the description of the file # @param slug a URL-friendly slug # @return a file def self.create(name, filename, file_url, description, slug, mime = "image/jpeg") file = ::File.open(file_url) new_file = perform_request(api_url(self.plural, {}), :post, { name: name, filename: filename, file: Base64.encode64(file.read), mime_type: mime, description: description, slug: slug }, true) if new_file new new_file['data'] else nil end end end end
module Masamune VERSION = '0.0.9' end Bump version module Masamune VERSION = '0.0.10' end
module MCProvision class Node attr_reader :hostname, :inventory def initialize(hostname, config, agent) @config = config @hostname = hostname @agent = agent setup @inventory = fetch_inventory end def lock MCProvision.info("Creating lock file on node") request("lock_deploy") end def unlock MCProvision.info("Removing lock file on node") request("unlock_deploy") end # Check if the lock file exist def locked? MCProvision.info("Checking if the deploy is locked on this node") result = request("is_locked") result[:data][:locked] end # Do we already have a puppet cert? def has_cert? MCProvision.info("Finding out if we already have a certificate") result = request("has_cert") result[:data][:has_cert] end # sets the ip of the puppet master host using the # set_puppet_host action on the node def set_puppet_host(ipaddress) MCProvision.info("Calling set_puppet_host with ip #{ipaddress}") request("set_puppet_host", {:ipaddress => ipaddress}) end # calls the request_certificate action on the node being provisioned def send_csr MCProvision.info("Calling request_certificate") request("request_certificate") end # calls the bootstrap_puppet action to do initial puppet run def bootstrap MCProvision.info("Calling bootstrap_puppet") result = request("bootstrap_puppet") check_puppet_output(result[:data][:output].split("\n")) end # Do the final run of the client by calling run_puppet def run_puppet MCProvision.info("Calling run_puppet") result = request("run_puppet") check_puppet_output(result[:data][:output].split("\n")) end private # Wrapper that calls to a node, checks the result structure and status messages and return # the result structure for the node def request(action, arguments={}) result = @node.custom_request(action, arguments, @hostname, {"identity" => @hostname}) raise "Uknown result from remote node: #{result.pretty_inspect}" unless result.is_a?(Array) result = result.first unless result[:statuscode] == 0 raise "Request to #{@hostname}##{action} failed: #{result[:statusmsg]}" end result end # checks output from puppetd that ran with --summarize for errors def check_puppet_output(output) output.each do |o| if o =~ /^\s+Failed: (\d+)/ raise "Puppet failed due to #{$1} failed resource(s)" unless $1 == "0" end end end # Gets the inventory from the discovery agent on the node def fetch_inventory result = {} # Does a MC::Client request to the main discovery agent, we should use the # rpcutil agent for this @node.client.req("inventory", "discovery", @node.client.options, 1) do |resp| result[:agents] = resp[:body][:agents] result[:facts] = resp[:body][:facts] result[:classes] = resp[:body][:classes] end result end def setup @node = rpcclient(@agent) @node.identity_filter @hostname @node.progress = false end end end use the rpcutil agent for inventory purposes module MCProvision class Node attr_reader :hostname, :inventory def initialize(hostname, config, agent) @config = config @hostname = hostname @agent = agent setup @inventory = fetch_inventory end def lock MCProvision.info("Creating lock file on node") request("lock_deploy") end def unlock MCProvision.info("Removing lock file on node") request("unlock_deploy") end # Check if the lock file exist def locked? MCProvision.info("Checking if the deploy is locked on this node") result = request("is_locked") result[:data][:locked] end # Do we already have a puppet cert? def has_cert? MCProvision.info("Finding out if we already have a certificate") result = request("has_cert") result[:data][:has_cert] end # sets the ip of the puppet master host using the # set_puppet_host action on the node def set_puppet_host(ipaddress) MCProvision.info("Calling set_puppet_host with ip #{ipaddress}") request("set_puppet_host", {:ipaddress => ipaddress}) end # calls the request_certificate action on the node being provisioned def send_csr MCProvision.info("Calling request_certificate") request("request_certificate") end # calls the bootstrap_puppet action to do initial puppet run def bootstrap MCProvision.info("Calling bootstrap_puppet") result = request("bootstrap_puppet") check_puppet_output(result[:data][:output].split("\n")) end # Do the final run of the client by calling run_puppet def run_puppet MCProvision.info("Calling run_puppet") result = request("run_puppet") check_puppet_output(result[:data][:output].split("\n")) end private # Wrapper that calls to a node, checks the result structure and status messages and return # the result structure for the node def request(action, arguments={}) result = @node.custom_request(action, arguments, @hostname, {"identity" => @hostname}) raise "Uknown result from remote node: #{result.pretty_inspect}" unless result.is_a?(Array) result = result.first unless result[:statuscode] == 0 raise "Request to #{@hostname}##{action} failed: #{result[:statusmsg]}" end result end # checks output from puppetd that ran with --summarize for errors def check_puppet_output(output) output.each do |o| if o =~ /^\s+Failed: (\d+)/ raise "Puppet failed due to #{$1} failed resource(s)" unless $1 == "0" end end end # Gets the inventory from the discovery agent on the node def fetch_inventory rpcutil = rpcclient("rpcutil") rpcutil.identity_filter @hostname rpcutil.progress = false result = rpcutil.inventory.first {:agents => result[:data][:agents], :facts => result[:data][:facts], :classes => result[:data][:classes]} end def setup @node = rpcclient(@agent) @node.identity_filter @hostname @node.progress = false end end end
module Measured VERSION = "1.2.0" end Bump version to 1.3.0 module Measured VERSION = "1.3.0" end
module Mementus VERSION = '0.5.11'.freeze end Bump version to 0.5.12 module Mementus VERSION = '0.5.12'.freeze end
module Menuizer VERSION = "0.1.1" end version dump module Menuizer VERSION = "0.1.2" end
module Mobvious VERSION = "0.2.0" end version bump module Mobvious VERSION = "0.3.0" end
module Audit class Team < Sequel::Model class << self def refresh(id, type) self.type(type).where(id: id).first.refresh end def type(type) type == "bnet" ? TeamBnet : (type == "raiderio" ? TeamRaiderio : TeamWcl) end end def characters(characters) characters.each_with_index do |character, index| characters[index].realm = character.realm.to_s.empty? ? realm : character.realm end characters.select{ |character| character.active } end def guild_data(type) @guild_data ||= Guild.where(:id => guild_id).first @guild_data.send(type) end def guild_name guild_data("name") end def realm guild_data("realm") end def region guild_data("region") end def patreon guild_data("patreon") end def updated_at guild_data("updated_at") end def days_remaining if patreon 60 elsif updated_at 60 - (Date.today - updated_at.to_date).to_i else 0 end end end end Fix for inactivity warning module Audit class Team < Sequel::Model class << self def refresh(id, type) self.type(type).where(id: id).first.refresh end def type(type) type == "bnet" ? TeamBnet : (type == "raiderio" ? TeamRaiderio : TeamWcl) end end def characters(characters) characters.each_with_index do |character, index| characters[index].realm = character.realm.to_s.empty? ? realm : character.realm end characters.select{ |character| character.active } end def guild_data(type) @guild_data ||= Guild.where(:id => guild_id).first @guild_data.send(type) end def guild_name guild_data("name") end def realm guild_data("realm") end def region guild_data("region") end def patreon guild_data("patreon") end def updated_at guild_data("updated_at") end def days_remaining if patreon > 0 60 elsif updated_at 60 - (Date.today - updated_at.to_date).to_i else 0 end end end end
module Download def self.request params Download::Router.request(params.delete('domain'), params) end def self.poll params Download::Poller.poll(params) end def self.link_to filename Download::Utils.link_to filename end def self.set_email params Download::Router.set_email(params.delete('domain'), params) end def self.clear_downloads Utils.clear_downloads end def self.generation_info domain, identifier, format Download::Utils.properties(Download::Utils.key(domain, identifier, format)) end def self.has_failed? domain, identifier, format status = generation_info(domain, identifier, format)['status'] status.present? && !%w(generating ready).include?(status) end def self.is_ready? domain, identifier, format generation_info(domain, identifier, format)['status'] == 'ready' end TMP_PATH = File.join(Rails.root, 'tmp') CURRENT_PREFIX = 'current/' IMPORT_PREFIX = 'import/' GENERATORS = { shp: Download::Generators::Shapefile, csv: Download::Generators::Csv, gdb: Download::Generators::Gdb, pdf: Download::Generators::Pdf }.freeze def self.generate format, download_name, opts={} generator = GENERATORS[format.to_sym] zip_path = Utils.zip_path(download_name) generated = generator.generate zip_path, opts[option(format)] if generated upload_to_s3 zip_path, opts[:for_import] clean_up zip_path end end private def self.option(format) format.to_s == 'pdf' ? :identifier : :wdpa_ids end def self.upload_to_s3 zip_path, for_import download_name = File.basename(zip_path) prefix = for_import ? IMPORT_PREFIX : CURRENT_PREFIX prefixed_download_name = prefix + download_name S3.upload prefixed_download_name, zip_path end def self.clean_up path FileUtils.rm_rf path end end Add rescue block to debug error module Download def self.request params Download::Router.request(params.delete('domain'), params) end def self.poll params Download::Poller.poll(params) end def self.link_to filename Download::Utils.link_to filename end def self.set_email params Download::Router.set_email(params.delete('domain'), params) end def self.clear_downloads Utils.clear_downloads end def self.generation_info domain, identifier, format Download::Utils.properties(Download::Utils.key(domain, identifier, format)) end def self.has_failed? domain, identifier, format status = generation_info(domain, identifier, format)['status'] status.present? && !%w(generating ready).include?(status) end def self.is_ready? domain, identifier, format generation_info(domain, identifier, format)['status'] == 'ready' end TMP_PATH = File.join(Rails.root, 'tmp') CURRENT_PREFIX = 'current/' IMPORT_PREFIX = 'import/' GENERATORS = { shp: Download::Generators::Shapefile, csv: Download::Generators::Csv, gdb: Download::Generators::Gdb, pdf: Download::Generators::Pdf }.freeze def self.generate format, download_name, opts={} begin generator = GENERATORS[format.to_sym] zip_path = Utils.zip_path(download_name) generated = generator.generate zip_path, opts[option(format)] if generated upload_to_s3 zip_path, opts[:for_import] clean_up zip_path end rescue StandardError => e Rails.logger.info("===DOWNLOAD GENERATION ERROR===") Rails.logger.info(e.backtrace) puts(e.backtrace) end end private def self.option(format) format.to_s == 'pdf' ? :identifier : :wdpa_ids end def self.upload_to_s3 zip_path, for_import download_name = File.basename(zip_path) prefix = for_import ? IMPORT_PREFIX : CURRENT_PREFIX prefixed_download_name = prefix + download_name S3.upload prefixed_download_name, zip_path end def self.clean_up path FileUtils.rm_rf path end end
module MoteSMS VERSION = '1.3.9'.freeze end restore v1.3.8 module MoteSMS VERSION = '1.3.8'.freeze end
tri1267 -- Wiring up the disease core config load to a production migration for existing system upgrades. git-svn-id: 105a8f2fe5eb3dca76b21e204c69f6587dfa9961@2147 b21a84b9-e453-0410-92a3-c4f515f7ae45 # Copyright (C) 2007, 2008, The Collaborative Software Foundation # # This file is part of TriSano. # # TriSano is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # TriSano 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt. class ProductionAddCdcDiseaseCoreConfig < ActiveRecord::Migration def self.up if RAILS_ENV == 'production' ruby "#{RAILS_ROOT}/script/runner #{RAILS_ROOT}/script/load_cdc_export_data_for_disease_core.rb" end end def self.down end end
maintainer "Opscode, Inc." maintainer_email "cookbooks@opscode.com" license "Apache 2.0" description "Installs and configures postgresql for clients or servers" long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc')) version "0.11.1" recipe "postgresql", "Empty, use one of the other recipes" recipe "postgresql::client", "Installs postgresql client package(s)" recipe "postgresql::server", "Installs postgresql server packages, templates" recipe "postgresql::server_redhat", "Installs postgresql server packages, redhat family style" recipe "postgresql::server_debian", "Installs postgresql server packages, debian family style" %w{rhel centos fedora ubuntu debian suse}.each do |os| supports os end Update PostgreSQL cookbook metadata maintainer "Travis CI Team" maintainer_email "michaelklishin@me.com" license "Apache 2.0" description "Installs and configures PostgreSQL for clients or servers" long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc')) version "0.11.2" recipe "postgresql", "Empty, use one of the other recipes" recipe "postgresql::client", "Installs postgresql client package(s)" recipe "postgresql::server", "Installs postgresql server packages, templates" %w{ubuntu debian}.each do |os| supports os end
class ArcadeLearningEnvironment < Formula desc "Platform for AI research" homepage "https://github.com/mgbellemare/Arcade-Learning-Environment" url "https://github.com/mgbellemare/Arcade-Learning-Environment/archive/v0.6.1.tar.gz" sha256 "8059a4087680da03878c1648a8ceb0413a341032ecaa44bef4ef1f9f829b6dde" head "https://github.com/mgbellemare/Arcade-Learning-Environment.git" bottle do cellar :any sha256 "7c00ddc0d9693ceaba062b77fb94e2a7aea2e6ccdfd16bb877c00c24e1ceaa48" => :catalina sha256 "1ccf63b1ee913ffeffcbc28d36e75bfc6c28f5afac6b51ff31e28d0dd06f51fd" => :mojave sha256 "bf91e1153dcc19178f77faa72b1761a5dcb284626cf16065196011d7b7d7ef6d" => :high_sierra end depends_on "cmake" => :build depends_on "numpy" depends_on "python" depends_on "sdl" def install args = std_cmake_args + %W[ -DCMAKE_INSTALL_NAME_DIR=#{opt_lib} -DCMAKE_BUILD_WITH_INSTALL_NAME_DIR=ON ] system "cmake", ".", *args system "make", "install" system "python3", *Language::Python.setup_install_args(prefix) end test do output = shell_output("#{bin}/ale 2>&1", 1).lines.last.chomp assert_equal "No ROM File specified.", output (testpath/"test.py").write <<~EOS from ale_python_interface import ALEInterface; ale = ALEInterface(); EOS assert_match "ale.cfg", shell_output("python3 test.py 2>&1") end end arcade-learning-environment: revision bump for python@3.8 class ArcadeLearningEnvironment < Formula desc "Platform for AI research" homepage "https://github.com/mgbellemare/Arcade-Learning-Environment" url "https://github.com/mgbellemare/Arcade-Learning-Environment/archive/v0.6.1.tar.gz" sha256 "8059a4087680da03878c1648a8ceb0413a341032ecaa44bef4ef1f9f829b6dde" revision 1 head "https://github.com/mgbellemare/Arcade-Learning-Environment.git" bottle do cellar :any sha256 "7c00ddc0d9693ceaba062b77fb94e2a7aea2e6ccdfd16bb877c00c24e1ceaa48" => :catalina sha256 "1ccf63b1ee913ffeffcbc28d36e75bfc6c28f5afac6b51ff31e28d0dd06f51fd" => :mojave sha256 "bf91e1153dcc19178f77faa72b1761a5dcb284626cf16065196011d7b7d7ef6d" => :high_sierra end depends_on "cmake" => :build depends_on "numpy" depends_on "python@3.8" depends_on "sdl" def install args = std_cmake_args + %W[ -DCMAKE_INSTALL_NAME_DIR=#{opt_lib} -DCMAKE_BUILD_WITH_INSTALL_NAME_DIR=ON ] system "cmake", ".", *args system "make", "install" system Formula["python@3.8"].opt_bin/"python3", *Language::Python.setup_install_args(prefix) end test do output = shell_output("#{bin}/ale 2>&1", 1).lines.last.chomp assert_equal "No ROM File specified.", output (testpath/"test.py").write <<~EOS from ale_python_interface import ALEInterface; ale = ALEInterface(); EOS assert_match "ale.cfg", shell_output("#{Formula["python@3.8"].opt_bin}/python3 test.py 2>&1") end end
class GoogleAuthenticatorLibpam < Formula desc "PAM module for two-factor authentication" homepage "https://github.com/google/google-authenticator-libpam" url "https://github.com/google/google-authenticator-libpam/archive/1.09.tar.gz" sha256 "ab1d7983413dc2f11de2efa903e5c326af8cb9ea37765dacb39949417f7cd037" bottle do cellar :any_skip_relocation sha256 "024679fc7963c416632e422af276ab10bb129740c7d081fadb9ee936695f57da" => :catalina sha256 "2317849932e770a926b427589058d6b552326d84376f714199e75aa9c922377d" => :mojave sha256 "b94306ade72a66cb67a8d3929f98349a01fd33b2b382a457bfecb8e1dde17380" => :high_sierra end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build depends_on "qrencode" def install system "./bootstrap.sh" system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "install" end def caveats <<~EOS Add 2-factor authentication for ssh: echo "auth required #{opt_lib}/security/pam_google_authenticator.so" \\ | sudo tee -a /etc/pam.d/sshd Add 2-factor authentication for ssh allowing users to log in without OTP: echo "auth required #{opt_lib}/security/pam_google_authenticator.so" \\ "nullok" | sudo tee -a /etc/pam.d/sshd (Or just manually edit /etc/pam.d/sshd) EOS end test do system "#{bin}/google-authenticator", "--force", "--time-based", "--disallow-reuse", "--rate-limit=3", "--rate-time=30", "--window-size=3", "--no-confirm" end end google-authenticator-libpam: update 1.09 bottle. class GoogleAuthenticatorLibpam < Formula desc "PAM module for two-factor authentication" homepage "https://github.com/google/google-authenticator-libpam" url "https://github.com/google/google-authenticator-libpam/archive/1.09.tar.gz" sha256 "ab1d7983413dc2f11de2efa903e5c326af8cb9ea37765dacb39949417f7cd037" bottle do cellar :any_skip_relocation sha256 "4ed85644559250923d4b21f5b99643cad08eb8bbb63afc3827d7ac225b4581d7" => :catalina sha256 "d62c1f21ec88406788b314bd7a06c0e37e7ab9dad4237f6832441f235723d3cb" => :mojave sha256 "33fa28d290cb0068a67c288d4889967180de64aa895f0ac1a3aedcc38d6a7d7a" => :high_sierra end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build depends_on "qrencode" def install system "./bootstrap.sh" system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "install" end def caveats <<~EOS Add 2-factor authentication for ssh: echo "auth required #{opt_lib}/security/pam_google_authenticator.so" \\ | sudo tee -a /etc/pam.d/sshd Add 2-factor authentication for ssh allowing users to log in without OTP: echo "auth required #{opt_lib}/security/pam_google_authenticator.so" \\ "nullok" | sudo tee -a /etc/pam.d/sshd (Or just manually edit /etc/pam.d/sshd) EOS end test do system "#{bin}/google-authenticator", "--force", "--time-based", "--disallow-reuse", "--rate-limit=3", "--rate-time=30", "--window-size=3", "--no-confirm" end end
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. require_relative 'spec_helper' module Selenium module WebDriver describe Window do after do sleep 1 if ENV['TRAVIS'] quit_driver end let(:window) { driver.manage.window } it 'gets the size of the current window' do size = window.size expect(size).to be_a(Dimension) expect(size.width).to be > 0 expect(size.height).to be > 0 end it 'sets the size of the current window' do size = window.size target_width = size.width - 20 target_height = size.height - 20 window.size = Dimension.new(target_width, target_height) new_size = window.size expect(new_size.width).to eq(target_width) expect(new_size.height).to eq(target_height) end it 'gets the position of the current window' do pos = window.position expect(pos).to be_a(Point) expect(pos.x).to be >= 0 expect(pos.y).to be >= 0 end it 'sets the position of the current window', except: {browser: :safari_preview} do pos = window.position target_x = pos.x + 10 target_y = pos.y + 10 window.position = Point.new(target_x, target_y) wait.until { window.position.x != pos.x && window.position.y != pos.y } new_pos = window.position expect(new_pos.x).to eq(target_x) expect(new_pos.y).to eq(target_y) end it 'gets the rect of the current window', only: {browser: %i[firefox ie]} do rect = window.rect expect(rect).to be_a(Rectangle) expect(rect.x).to be >= 0 expect(rect.y).to be >= 0 expect(rect.width).to be >= 0 expect(rect.height).to be >= 0 end it 'sets the rect of the current window', only: {browser: %i[firefox ie]} do rect = window.rect target_x = rect.x + 10 target_y = rect.y + 10 target_width = rect.width + 10 target_height = rect.height + 10 window.rect = Rectangle.new(target_x, target_y, target_width, target_height) wait.until { window.rect.x != rect.x && window.rect.y != rect.y } new_rect = window.rect expect(new_rect.x).to eq(target_x) expect(new_rect.y).to eq(target_y) expect(new_rect.width).to eq(target_width) expect(new_rect.height).to eq(target_height) end it 'can maximize the current window', except: {window_manager: false} do window.size = old_size = Dimension.new(200, 200) window.maximize wait.until { window.size != old_size } new_size = window.size expect(new_size.width).to be > old_size.width expect(new_size.height).to be > old_size.height end # Edge: Not Yet - https://dev.windows.com/en-us/microsoft-edge/platform/status/webdriver/details/ it 'can make window full screen', only: {window_manager: true, browser: [:ie, :firefox]} do window.maximize old_size = window.size window.full_screen wait.until { window.size != old_size } new_size = window.size expect(new_size.width).to be > old_size.width expect(new_size.height).to be > old_size.height end # Edge: Not Yet - https://dev.windows.com/en-us/microsoft-edge/platform/status/webdriver/details/ it 'can minimize the window', only: {window_manager: true, browser: [:ie, :firefox]} do window.minimize expect(driver.execute_script('return document.hidden;')).to be true end end end # WebDriver end # Selenium Stabilize full screen window tests # Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. require_relative 'spec_helper' module Selenium module WebDriver describe Window do after do sleep 1 if ENV['TRAVIS'] quit_driver end let(:window) { driver.manage.window } it 'gets the size of the current window' do size = window.size expect(size).to be_a(Dimension) expect(size.width).to be > 0 expect(size.height).to be > 0 end it 'sets the size of the current window' do size = window.size target_width = size.width - 20 target_height = size.height - 20 window.size = Dimension.new(target_width, target_height) new_size = window.size expect(new_size.width).to eq(target_width) expect(new_size.height).to eq(target_height) end it 'gets the position of the current window' do pos = window.position expect(pos).to be_a(Point) expect(pos.x).to be >= 0 expect(pos.y).to be >= 0 end it 'sets the position of the current window', except: {browser: :safari_preview} do pos = window.position target_x = pos.x + 10 target_y = pos.y + 10 window.position = Point.new(target_x, target_y) wait.until { window.position.x != pos.x && window.position.y != pos.y } new_pos = window.position expect(new_pos.x).to eq(target_x) expect(new_pos.y).to eq(target_y) end it 'gets the rect of the current window', only: {browser: %i[firefox ie]} do rect = window.rect expect(rect).to be_a(Rectangle) expect(rect.x).to be >= 0 expect(rect.y).to be >= 0 expect(rect.width).to be >= 0 expect(rect.height).to be >= 0 end it 'sets the rect of the current window', only: {browser: %i[firefox ie]} do rect = window.rect target_x = rect.x + 10 target_y = rect.y + 10 target_width = rect.width + 10 target_height = rect.height + 10 window.rect = Rectangle.new(target_x, target_y, target_width, target_height) wait.until { window.rect.x != rect.x && window.rect.y != rect.y } new_rect = window.rect expect(new_rect.x).to eq(target_x) expect(new_rect.y).to eq(target_y) expect(new_rect.width).to eq(target_width) expect(new_rect.height).to eq(target_height) end it 'can maximize the current window', except: {window_manager: false} do window.size = old_size = Dimension.new(200, 200) window.maximize wait.until { window.size != old_size } new_size = window.size expect(new_size.width).to be > old_size.width expect(new_size.height).to be > old_size.height end # Edge: Not Yet - https://dev.windows.com/en-us/microsoft-edge/platform/status/webdriver/details/ it 'can make window full screen', only: {window_manager: true, browser: [:ie, :firefox]} do window.size = old_size = Dimension.new(200, 200) window.full_screen wait.until { window.size != old_size } new_size = window.size expect(new_size.width).to be > old_size.width expect(new_size.height).to be > old_size.height end # Edge: Not Yet - https://dev.windows.com/en-us/microsoft-edge/platform/status/webdriver/details/ it 'can minimize the window', only: {window_manager: true, browser: [:ie, :firefox]} do window.minimize expect(driver.execute_script('return document.hidden;')).to be true end end end # WebDriver end # Selenium
# encoding: utf-8 # # Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. require File.expand_path('../../spec_helper', __FILE__) module Selenium module WebDriver module Remote describe Bridge do describe '.handshake' do let(:http) { WebDriver::Remote::Http::Default.new } it 'sends merged capabilities' do payload = JSON.generate( desiredCapabilities: { browserName: 'internet explorer', version: '', platform: 'WINDOWS', javascriptEnabled: false, cssSelectorsEnabled: true, takesScreenshot: true, nativeEvents: true, rotatable: false }, capabilities: { firstMatch: [{ browserName: 'internet explorer', platformName: 'windows' }] } ) expect(http).to receive(:request) .with(any_args, payload) .and_return('status' => 200, 'sessionId' => 'foo', 'value' => {}) Bridge.handshake(http_client: http, desired_capabilities: Capabilities.ie) end it 'uses OSS bridge when necessary' do allow(http).to receive(:request) .and_return('status' => 200, 'sessionId' => 'foo', 'value' => {}) bridge = Bridge.handshake(http_client: http, desired_capabilities: Capabilities.new) expect(bridge).to be_a(OSS::Bridge) expect(bridge.session_id).to eq('foo') end it 'uses W3C bridge when necessary' do allow(http).to receive(:request) .and_return('value' => {'sessionId' => 'foo', 'value' => {}}) bridge = Bridge.handshake(http_client: http, desired_capabilities: Capabilities.new) expect(bridge).to be_a(W3C::Bridge) expect(bridge.session_id).to eq('foo') end it 'supports responses with "value" capabilities' do allow(http).to receive(:request) .and_return({'status' => 200, 'sessionId' => '', 'value' => {'browserName' => 'firefox'}}) bridge = Bridge.handshake(http_client: http, desired_capabilities: Capabilities.new) expect(bridge.capabilities[:browser_name]).to eq('firefox') end it 'supports responses with "value" -> "value" capabilities' do allow(http).to receive(:request) .and_return('value' => {'sessionId' => '', 'value' => {'browserName' => 'firefox'}}) bridge = Bridge.handshake(http_client: http, desired_capabilities: Capabilities.new) expect(bridge.capabilities[:browser_name]).to eq('firefox') end it 'supports responses with "value" -> "capabilities" capabilities' do allow(http).to receive(:request) .and_return('value' => {'sessionId' => '', 'capabilities' => {'browserName' => 'firefox'}}) bridge = Bridge.handshake(http_client: http, desired_capabilities: Capabilities.new) expect(bridge.capabilities[:browser_name]).to eq('firefox') end end end end # Remote end # WebDriver end # Selenium Fix unit tests for recent changes in protocol handshake # encoding: utf-8 # # Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. require File.expand_path('../../spec_helper', __FILE__) module Selenium module WebDriver module Remote describe Bridge do describe '.handshake' do let(:http) { WebDriver::Remote::Http::Default.new } it 'sends merged capabilities' do payload = JSON.generate( desiredCapabilities: { browserName: 'internet explorer', version: '', platform: 'WINDOWS', javascriptEnabled: false, cssSelectorsEnabled: true, takesScreenshot: true, nativeEvents: true, rotatable: false }, capabilities: { firstMatch: [{ browserName: 'internet explorer' }] } ) expect(http).to receive(:request) .with(any_args, payload) .and_return('status' => 200, 'sessionId' => 'foo', 'value' => {}) Bridge.handshake(http_client: http, desired_capabilities: Capabilities.ie) end it 'uses OSS bridge when necessary' do allow(http).to receive(:request) .and_return('status' => 200, 'sessionId' => 'foo', 'value' => {}) bridge = Bridge.handshake(http_client: http, desired_capabilities: Capabilities.new) expect(bridge).to be_a(OSS::Bridge) expect(bridge.session_id).to eq('foo') end it 'uses W3C bridge when necessary' do allow(http).to receive(:request) .and_return('value' => {'sessionId' => 'foo', 'value' => {}}) bridge = Bridge.handshake(http_client: http, desired_capabilities: Capabilities.new) expect(bridge).to be_a(W3C::Bridge) expect(bridge.session_id).to eq('foo') end it 'supports responses with "value" capabilities' do allow(http).to receive(:request) .and_return({'status' => 200, 'sessionId' => '', 'value' => {'browserName' => 'firefox'}}) bridge = Bridge.handshake(http_client: http, desired_capabilities: Capabilities.new) expect(bridge.capabilities[:browser_name]).to eq('firefox') end it 'supports responses with "value" -> "value" capabilities' do allow(http).to receive(:request) .and_return('value' => {'sessionId' => '', 'value' => {'browserName' => 'firefox'}}) bridge = Bridge.handshake(http_client: http, desired_capabilities: Capabilities.new) expect(bridge.capabilities[:browser_name]).to eq('firefox') end it 'supports responses with "value" -> "capabilities" capabilities' do allow(http).to receive(:request) .and_return('value' => {'sessionId' => '', 'capabilities' => {'browserName' => 'firefox'}}) bridge = Bridge.handshake(http_client: http, desired_capabilities: Capabilities.new) expect(bridge.capabilities[:browser_name]).to eq('firefox') end end end end # Remote end # WebDriver end # Selenium
add default route
#!/usr/bin/ruby ################################################################# =begin =ObjectStore.rb == Name ObjectStore - An object persistance abstraction class == Synopsis require "mues/ObjectStore" require "mues/Config" oStore = MUES::ObjectStore.new( MUES::Config.new("MUES.cfg") ) objectIds = oStore.storeObjects( obj ) {|obj| $stderr.puts "Stored object #{obj}" } user = oStore.fetchUser( "login" ) == Description This class is a generic front end to various means of storing MUES objects. It uses one or more configurable back ends which serialize and store objects to some kind of storage medium (flat file, database, sub-atomic particle inference engine), and then later can restore and de-serialize them. == Classes === MUES::ObjectStore ==== Class Methods --- MUES::ObjectStore.hasAdapter?( name ) Returns true if the object store has an adapter class named ((|name|)). --- MUES::ObjectStore.getAdapter( driver, db, host, user, password ) Get a new back-end adapter object for the specified ((|driver|)), ((|db|)), ((|host|)), ((|user|)), and ((|password|)). ==== Protected Class Methods --- MUES::ObjectStore._getAdapterClass( name ) Returns the adapter class associated with the specified ((|name|)), or (({nil})) if the class is not registered with the ObjectStore. --- MUES::ObjectStore._loadAdapters Search for adapters in the subdir specified in the (({AdapterSubdir})) class constant, attempting to load each one. ==== Public Methods --- MUES::ObjectStore#createUser( username ) { |obj| block } -> User Returns a new MUES::User object for the given ((|username|)). If the optional ((|block|)) is given, it will be passed the user object as an argument. When the block exits, the user object will be automatically stored and de-allocated. In this case, (({ObjectStore.fetchUser})) returns (({true})). If no block is given, the new MUES::User object is returned. --- MUES::ObjectStore#deleteUser( username ) Deletes the user associated with the specified ((|username|)) from the objectstore. --- MUES::ObjectStore#fetchObjects( *objectIds ) { |obj| block } -> objects=Array Fetch the objects associated with the given ((|objectIds|)) from the objectstore and call (({awaken()})) on them if they respond to such a method. If the optional ((|block|)) is specified, it is used as an iterator, being called with each new object in turn. If the block is specified, this method returns the array of the results of each call; otherwise, the fetched objects are returned. --- MUES::ObjectStore#fetchUser( username ) { |obj| block } -> User Returns a user object for the username specified unless the optional code block is given, in which case it will be passed the user object as an argument. When the block exits, the user object will be automatically stored and de-allocated, and (({true})) is returned if storing the user object succeeded. If the user doesn^t exist, (({ObjectStore.fetchUser})) returns (({nil})). --- MUES::ObjectStore#getUserList() Returns an array of usernames that exist in the objectstore --- MUES::ObjectStore#hasObject?( id ) Return true if the ObjectStore contains an object associated with the specified ((|id|)). --- MUES::ObjectStore#storeObjects( *objects ) { |oid| block }-> oids=Array Store the given ((|objects|)) in the ObjectStore after calling (({lull()})) on each of them, if they respond to such a method. If the optional ((|block|)) is given, it is used as an iterator by calling it with each object id after the objects are stored, and then returning the results of each call in an Array. If no block is given, the object ids are returned. --- MUES::ObjectStore#storeUser( user=MUES::User ) -> true Store the given ((|user|)) in the datastore, returning (({true})) on success. ==== Protected Methods --- MUES::ObjectStore#initialize( config=MUES::Config ) Initialize a new ObjectStore based on the values in the specified configuration. If the specified ((|driver|)) cannot be loaded, an (({UnknownAdapterError})) exception is raised. == Author Michael Granger <((<ged@FaerieMUD.org|URL:mailto:ged@FaerieMUD.org>))> Copyright (c) 2000-2001 The FaerieMUD Consortium. All rights reserved. This module is free software. You may use, modify, and/or redistribute this software under the terms of the Perl Artistic License. (See http://language.perl.com/misc/Artistic.html) =end ################################################################# require "find" require "mues/Namespace" require "mues/Events" require "mues/Exceptions" require "mues/User" module MUES ### Exception classes def_exception :NoSuchObjectError, "No such object", Exception def_exception :UnknownAdapterError, "No such adapter", Exception ### Object store class class ObjectStore < Object ; implements Debuggable include Event::Handler autoload "MUES::ObjectStore::Adapter", "mues/adapters/Adapter" ### Class Constants Version = /([\d\.]+)/.match( %q$Revision: 1.10 $ )[1] Rcsid = %q$Id: ObjectStore.rb,v 1.10 2001/11/01 17:14:13 deveiant Exp $ AdapterSubdir = 'mues/adapters' AdapterPattern = /#{AdapterSubdir}\/(\w+Adapter).rb$/ #/ ### Class attributes @@AdaptersAreLoaded = false @@Adapters = nil ### Class methods class << self protected ### (PROTECTED CLASS) METHOD: _loadAdapters ### Search for adapters in the subdir specified in the AdapterSubdir ### class constant, attempting to load each one. def _loadAdapters return true if @@AdaptersAreLoaded @@Adapters = {} ### Iterate over each directory in the include path, looking for ### files which match the adapter class filename pattern. Add ### the ones we find to a hash. $:.collect {|dir| "#{dir}/#{AdapterSubdir}"}.each do |dir| unless FileTest.exists?( dir ) && FileTest.directory?( dir ) && FileTest.readable?( dir ) next end Find.find( dir ) {|f| next unless f =~ AdapterPattern @@Adapters[ $1 ] = false } end ### Now for each potential adapter class that we found above, ### try to require each one in turn. Mark those that load in the ### hash. @@Adapters.each_pair {|name,loaded| next if loaded begin require "#{AdapterSubdir}/#{name}" rescue ScriptError => e $stderr.puts "Failed to load adapter '#{name}': #{e.to_s}" next end @@Adapters[ name ] = true } @@AdaptersAreLoaded = true return @@Adapters end ### (PROTECTED CLASS) METHOD: _getAdapterClass( name ) ### Returns the adapter class associated with the specified ### ((|name|)), or (({nil})) if the class is not registered with the ### ObjectStore. def _getAdapterClass( name ) _loadAdapters() MUES::ObjectStore::Adapter.getAdapterClass( name ) end public ### (CLASS) METHOD: hasAdapter?( name ) ### Returns true if the object store has an adapter class named ### ((|name|)). def hasAdapter?( name ) return _getAdapterClass( name ).is_a?( Class ) end ### (CLASS) METHOD: getAdapter( config=MUES::Config ) ### Get a new back-end adapter object for the driver specified by the ((|config|)). def getAdapter( config ) _loadAdapters() driver = config["objectstore"]["driver"] klass = _getAdapterClass( driver ) raise UnknownAdapterError, "Could not fetch adapter class '#{driver}'" unless klass klass.new( config ) end end ### (PROTECTED) METHOD: initialize( config=MUES::Config ) ### Initialize a new ObjectStore based on the values in the specified ### configuration object. If the specified ((|driver|)) cannot be ### loaded, an (({UnknownAdapterError})) exception is raised. def initialize( config ) super() @dbAdapter = self.class.getAdapter( config ) end ### METHOD: fetchObjects( *objectIds ) { |obj| block } -> objects=Array ### Fetch the objects associated with the given ((|objectIds|)) from the ### objectstore and call (({awaken()})) on them if they respond to such ### a method. If the optional ((|block|)) is specified, it is used as an ### iterator, being called with each new object in turn. If the block is ### specified, this method returns the array of the results of each ### call; otherwise, the fetched objects are returned. def fetchObjects( *objectIds ) @dbAdapter.fetchObjects( *objectIds ).collect {|obj| obj.awaken if obj.respond_to?( :awaken ) obj = yield( obj ) if block_given? obj } end ### METHOD: storeObjects( *objects ) { |oid| block }-> oids=Array ### Store the given ((|objects|)) in the ObjectStore after calling ### (({lull()})) on each of them, if they respond to such a method. If ### the optional ((|block|)) is given, it is used as an iterator by ### calling it with each object id after the objects are stored, and ### then returning the results of each call in an Array. If no block is ### given, the object ids are returned. def storeObjects( *objects ) objects.each {|o| o.lull if o.respond_to?( :lull )} @dbAdapter.storeObjects( *objects ).collect {|oid| oid = yield( oid ) if block_given? oid } end ### METHOD: hasObject?( id ) ### Return true if the ObjectStore contains an object associated with ### the specified ((|id|)). def hasObject?( id ) return @dbAdapter.hasObject?( id ) end ### METHOD: fetchUser( username ) { |obj| block } -> User ### Returns a user object for the username specified unless the ### optional code block is given, in which case it will be passed the ### user object as an argument. When the block exits, the user ### object will be automatically stored and de-allocated, and (({true})) ### is returned if storing the user object succeeded. If the user ### doesn't exist, (({ObjectStore.fetchUser})) returns (({nil})). def fetchUser( username ) checkType( username, ::String ) userData = @dbAdapter.fetchUserData( username ) return nil if userData.nil? user = User.new( userData ) if block_given? yield( user ) storeUser( user ) return nil else return user end end ### METHOD: storeUser( user=MUES::User ) -> true ### Store the given ((|user|)) in the datastore, returning (({true})) on ### success. def storeUser( aUser ) checkType( aUser, MUES::User ) _debugMsg( 2, "Storing user: #{aUser.to_s}" ) newDbInfo = @dbAdapter.storeUserData( aUser.username, aUser.dbInfo ) _debugMsg( 2, "Done storing user: #{aUser.to_s}" ) aUser.dbInfo = newDbInfo return true end ### METHOD: createUser( username ) { |obj| block } -> User ### Returns a new MUES::User object with the given ((|username|)). If ### the optional ((|block|)) is given, it will be passed the user object ### as an argument. When the block exits, the user object will be ### automatically stored and de-allocated. In this case, ### (({ObjectStore.fetchUser})) returns (({true})).If no block is given, ### the new MUES::User object is returned. def createUser( username ) userData = @dbAdapter.createUserData( username ) user = User.new( userData ) user.username = username if block_given? yield( user ) storeUser( user ) return true else return user end end ### METHOD: deleteUser( username ) ### Deletes the user associated with the specified ((|username|)) from ### the objectstore. def deleteUser( username ) @dbAdapter.deleteUserData( username ) end ### METHOD: getUserList() ### Returns an array of usernames that exist in the objectstore def getUserList @dbAdapter.getUsernameList() end end end - Changed autoloads to work under ruby-1.7. - Fixed a bug in the initializer. --HG-- extra : convert_revision : svn%3A39a105f4-52d6-0310-bb1b-d6517044f2e4/trunk%40262 #!/usr/bin/ruby ################################################################# =begin =ObjectStore.rb == Name ObjectStore - An object persistance abstraction class == Synopsis require "mues/ObjectStore" require "mues/Config" oStore = MUES::ObjectStore.new( MUES::Config.new("MUES.cfg") ) objectIds = oStore.storeObjects( obj ) {|obj| $stderr.puts "Stored object #{obj}" } user = oStore.fetchUser( "login" ) == Description This class is a generic front end to various means of storing MUES objects. It uses one or more configurable back ends which serialize and store objects to some kind of storage medium (flat file, database, sub-atomic particle inference engine), and then later can restore and de-serialize them. == Classes === MUES::ObjectStore ==== Class Methods --- MUES::ObjectStore.hasAdapter?( name ) Returns true if the object store has an adapter class named ((|name|)). --- MUES::ObjectStore.getAdapter( driver, db, host, user, password ) Get a new back-end adapter object for the specified ((|driver|)), ((|db|)), ((|host|)), ((|user|)), and ((|password|)). ==== Protected Class Methods --- MUES::ObjectStore._getAdapterClass( name ) Returns the adapter class associated with the specified ((|name|)), or (({nil})) if the class is not registered with the ObjectStore. --- MUES::ObjectStore._loadAdapters Search for adapters in the subdir specified in the (({AdapterSubdir})) class constant, attempting to load each one. ==== Public Methods --- MUES::ObjectStore#createUser( username ) { |obj| block } -> User Returns a new MUES::User object for the given ((|username|)). If the optional ((|block|)) is given, it will be passed the user object as an argument. When the block exits, the user object will be automatically stored and de-allocated. In this case, (({ObjectStore.fetchUser})) returns (({true})). If no block is given, the new MUES::User object is returned. --- MUES::ObjectStore#deleteUser( username ) Deletes the user associated with the specified ((|username|)) from the objectstore. --- MUES::ObjectStore#fetchObjects( *objectIds ) { |obj| block } -> objects=Array Fetch the objects associated with the given ((|objectIds|)) from the objectstore and call (({awaken()})) on them if they respond to such a method. If the optional ((|block|)) is specified, it is used as an iterator, being called with each new object in turn. If the block is specified, this method returns the array of the results of each call; otherwise, the fetched objects are returned. --- MUES::ObjectStore#fetchUser( username ) { |obj| block } -> User Returns a user object for the username specified unless the optional code block is given, in which case it will be passed the user object as an argument. When the block exits, the user object will be automatically stored and de-allocated, and (({true})) is returned if storing the user object succeeded. If the user doesn^t exist, (({ObjectStore.fetchUser})) returns (({nil})). --- MUES::ObjectStore#getUserList() Returns an array of usernames that exist in the objectstore --- MUES::ObjectStore#hasObject?( id ) Return true if the ObjectStore contains an object associated with the specified ((|id|)). --- MUES::ObjectStore#storeObjects( *objects ) { |oid| block }-> oids=Array Store the given ((|objects|)) in the ObjectStore after calling (({lull()})) on each of them, if they respond to such a method. If the optional ((|block|)) is given, it is used as an iterator by calling it with each object id after the objects are stored, and then returning the results of each call in an Array. If no block is given, the object ids are returned. --- MUES::ObjectStore#storeUser( user=MUES::User ) -> true Store the given ((|user|)) in the datastore, returning (({true})) on success. ==== Protected Methods --- MUES::ObjectStore#initialize( config=MUES::Config ) Initialize a new ObjectStore based on the values in the specified configuration. If the specified ((|driver|)) cannot be loaded, an (({UnknownAdapterError})) exception is raised. == Author Michael Granger <((<ged@FaerieMUD.org|URL:mailto:ged@FaerieMUD.org>))> Copyright (c) 2000-2001 The FaerieMUD Consortium. All rights reserved. This module is free software. You may use, modify, and/or redistribute this software under the terms of the Perl Artistic License. (See http://language.perl.com/misc/Artistic.html) =end ################################################################# require "find" require "mues/Namespace" require "mues/Events" require "mues/Exceptions" require "mues/User" module MUES ### Exception classes def_exception :NoSuchObjectError, "No such object", Exception def_exception :UnknownAdapterError, "No such adapter", Exception ### Object store class class ObjectStore < Object ; implements Debuggable autoload :Adapter, "mues/adapters/Adapter" include Event::Handler ### Class Constants Version = /([\d\.]+)/.match( %q$Revision: 1.11 $ )[1] Rcsid = %q$Id: ObjectStore.rb,v 1.11 2001/12/05 18:07:41 deveiant Exp $ AdapterSubdir = 'mues/adapters' AdapterPattern = /#{AdapterSubdir}\/(\w+Adapter).rb$/ #/ ### Class attributes @@AdaptersAreLoaded = false @@Adapters = nil ### Class methods class << self protected ### (PROTECTED CLASS) METHOD: _loadAdapters ### Search for adapters in the subdir specified in the AdapterSubdir ### class constant, attempting to load each one. def _loadAdapters return true if @@AdaptersAreLoaded @@Adapters = {} ### Iterate over each directory in the include path, looking for ### files which match the adapter class filename pattern. Add ### the ones we find to a hash. $:.collect {|dir| "#{dir}/#{AdapterSubdir}"}.each do |dir| unless FileTest.exists?( dir ) && FileTest.directory?( dir ) && FileTest.readable?( dir ) next end Find.find( dir ) {|f| next unless f =~ AdapterPattern @@Adapters[ $1 ] = false } end ### Now for each potential adapter class that we found above, ### try to require each one in turn. Mark those that load in the ### hash. @@Adapters.each_pair {|name,loaded| next if loaded begin require "#{AdapterSubdir}/#{name}" rescue ScriptError => e $stderr.puts "Failed to load adapter '#{name}': #{e.to_s}" next end @@Adapters[ name ] = true } @@AdaptersAreLoaded = true return @@Adapters end ### (PROTECTED CLASS) METHOD: _getAdapterClass( name ) ### Returns the adapter class associated with the specified ### ((|name|)), or (({nil})) if the class is not registered with the ### ObjectStore. def _getAdapterClass( name ) _loadAdapters() MUES::ObjectStore::Adapter.getAdapterClass( name ) end public ### (CLASS) METHOD: hasAdapter?( name ) ### Returns true if the object store has an adapter class named ### ((|name|)). def hasAdapter?( name ) return _getAdapterClass( name ).is_a?( Class ) end ### (CLASS) METHOD: getAdapter( config=MUES::Config ) ### Get a new back-end adapter object for the driver specified by the ((|config|)). def getAdapter( config ) _loadAdapters() driver = config["objectstore"]["driver"] klass = _getAdapterClass( driver ) raise UnknownAdapterError, "Could not fetch adapter class '#{driver}'" unless klass klass.new( config ) end end ### (PROTECTED) METHOD: initialize( config=MUES::Config ) ### Initialize a new ObjectStore based on the values in the specified ### configuration object. If the specified ((|driver|)) cannot be ### loaded, an (({UnknownAdapterError})) exception is raised. def initialize( config ) super() @dbAdapter = ObjectStore::getAdapter( config ) end ### METHOD: fetchObjects( *objectIds ) { |obj| block } -> objects=Array ### Fetch the objects associated with the given ((|objectIds|)) from the ### objectstore and call (({awaken()})) on them if they respond to such ### a method. If the optional ((|block|)) is specified, it is used as an ### iterator, being called with each new object in turn. If the block is ### specified, this method returns the array of the results of each ### call; otherwise, the fetched objects are returned. def fetchObjects( *objectIds ) @dbAdapter.fetchObjects( *objectIds ).collect {|obj| obj.awaken if obj.respond_to?( :awaken ) obj = yield( obj ) if block_given? obj } end ### METHOD: storeObjects( *objects ) { |oid| block }-> oids=Array ### Store the given ((|objects|)) in the ObjectStore after calling ### (({lull()})) on each of them, if they respond to such a method. If ### the optional ((|block|)) is given, it is used as an iterator by ### calling it with each object id after the objects are stored, and ### then returning the results of each call in an Array. If no block is ### given, the object ids are returned. def storeObjects( *objects ) objects.each {|o| o.lull if o.respond_to?( :lull )} @dbAdapter.storeObjects( *objects ).collect {|oid| oid = yield( oid ) if block_given? oid } end ### METHOD: hasObject?( id ) ### Return true if the ObjectStore contains an object associated with ### the specified ((|id|)). def hasObject?( id ) return @dbAdapter.hasObject?( id ) end ### METHOD: fetchUser( username ) { |obj| block } -> User ### Returns a user object for the username specified unless the ### optional code block is given, in which case it will be passed the ### user object as an argument. When the block exits, the user ### object will be automatically stored and de-allocated, and (({true})) ### is returned if storing the user object succeeded. If the user ### doesn't exist, (({ObjectStore.fetchUser})) returns (({nil})). def fetchUser( username ) checkType( username, ::String ) userData = @dbAdapter.fetchUserData( username ) return nil if userData.nil? user = User.new( userData ) if block_given? yield( user ) storeUser( user ) return nil else return user end end ### METHOD: storeUser( user=MUES::User ) -> true ### Store the given ((|user|)) in the datastore, returning (({true})) on ### success. def storeUser( aUser ) checkType( aUser, MUES::User ) _debugMsg( 2, "Storing user: #{aUser.to_s}" ) newDbInfo = @dbAdapter.storeUserData( aUser.username, aUser.dbInfo ) _debugMsg( 2, "Done storing user: #{aUser.to_s}" ) aUser.dbInfo = newDbInfo return true end ### METHOD: createUser( username ) { |obj| block } -> User ### Returns a new MUES::User object with the given ((|username|)). If ### the optional ((|block|)) is given, it will be passed the user object ### as an argument. When the block exits, the user object will be ### automatically stored and de-allocated. In this case, ### (({ObjectStore.fetchUser})) returns (({true})).If no block is given, ### the new MUES::User object is returned. def createUser( username ) userData = @dbAdapter.createUserData( username ) user = User.new( userData ) user.username = username if block_given? yield( user ) storeUser( user ) return true else return user end end ### METHOD: deleteUser( username ) ### Deletes the user associated with the specified ((|username|)) from ### the objectstore. def deleteUser( username ) @dbAdapter.deleteUserData( username ) end ### METHOD: getUserList() ### Returns an array of usernames that exist in the objectstore def getUserList @dbAdapter.getUsernameList() end end end
module MyFeeds VERSION = "0.0.1" end version 0.1.0 module MyFeeds VERSION = "0.1.0" end
# encoding: utf-8 module NessusDB module Parsers end end require 'nessusdb/parsers/' Commented out future stuff # encoding: utf-8 module NessusDB module Parsers end end #require 'nessusdb/parsers/'
# coding: utf-8 require 'open-uri' require 'rexml/document' require 'lambda_driver' require 'nico_util/attr_setter' require 'nico_util/hashable' module NicoUtil class Mylist include NicoUtil::AttrSetter include NicoUtil::Hashable URL = /(http:\/\/www\.nicovideo\.jp\/mylist\/)?(\d+)(\?rss=2\.0)?/ def initialize(group_id) builder = method(:build_url) >> method(:open) >> :read >> REXML::Document._.new >> (:get_elements & "rss/channel") >> :first doc = if URL =~ group_id builder < $2 else raise "not mylist url or unexist mylist" end assignee_meta(doc) assignee_item(doc) end def to_h end private def build_url(mylist_id) "http://www.nicovideo.jp/mylist/#{mylist_id}?rss=2.0" end def assignee_meta doc [ :title, :link, :description, :pubDate, :lastBuildDate ].each do |sym| attr_setter(sym, :to_s >> doc._.text < sym) end attr_setter(:creator, doc._.text < "dc:creator") end def assignee_item doc attr_setter(:items) do doc.get_elements("item").map do |item| [:title, :link, :pubDate, :description].map {|sym| [sym, :to_s >> item._.text < sym] }.to_h end end end end end nil guard # coding: utf-8 require 'open-uri' require 'rexml/document' require 'lambda_driver' require 'nico_util/attr_setter' require 'nico_util/hashable' module NicoUtil class Mylist include NicoUtil::AttrSetter include NicoUtil::Hashable URL = /(http:\/\/www\.nicovideo\.jp\/mylist\/)?(\d+)(\?rss=2\.0)?/ def initialize(group_id) builder = method(:build_url) >> method(:open) >> :read >> REXML::Document._.new >> (:get_elements & "rss/channel") >> :first doc = if URL =~ group_id builder < $2 else raise "not mylist url or unexist mylist" end assignee_meta(doc) assignee_item(doc) end def to_h end private def build_url(mylist_id) "http://www.nicovideo.jp/mylist/#{mylist_id}?rss=2.0" end def assignee_meta doc [ :title, :link, :description, :pubDate, :lastBuildDate ].each do |sym| attr_setter(sym, :to_s >> doc._.text < sym || "") end attr_setter(:creator, doc._.text < "dc:creator" || "") end def assignee_item doc attr_setter(:items) do doc.get_elements("item").map do |item| [:title, :link, :pubDate, :description].map {|sym| [sym, :to_s >> item._.text < sym || ""] }.to_h end end end end end
require 'forwardable' require 'tempfile' module NpSearch # A class to hold sequence data class Signalp class << self extend Forwardable def_delegators NpSearch, :opt def analyse_sequence(seq) sp_headers = %w(name cmax cmax_pos ymax ymax_pos smax smax_pos smean d sp dmaxcut networks) f = Tempfile.new('signalp') f.write(">seq\n#{seq}") f.close s = `#{opt[:signalp_path]} -t euk -f short -U 0.3 -u 0.3 '#{f.path}' | \ sed -n '3 p'` Hash[sp_headers.map(&:to_sym).zip(s.split)] ensure f.unlink end end end end remove the usage of tempfiles in running signalp require 'forwardable' module NpSearch # A class to hold sequence data class Signalp class << self extend Forwardable def_delegators NpSearch, :opt def analyse_sequence(seq) sp_headers = %w(name cmax cmax_pos ymax ymax_pos smax smax_pos smean d sp dmaxcut networks) s = `echo ">seq\n#{seq}\n" | #{opt[:signalp_path]} -t euk -f short \ -U 0.3 -u 0.3 | sed -n '3 p'` Hash[sp_headers.map(&:to_sym).zip(s.split)] end end end end
# Top level module / namespace. module NpSearch VERSION = '2.0.0' end bump version to 2.0.1 # Top level module / namespace. module NpSearch VERSION = '2.0.1' end
require 'json' require 'multi_json' require 'addressable/uri' module Crichton module ALPS ## # Manages serialization to the Application-Level Profile Semantics (ALPS) specification JSON and XML formats. module Serialization ## # ALPS specification attributes that can be serialized. ALPS_ATTRIBUTES = %w(id name type href rt) ## # ALPS specification doc element. DOC_ELEMENT = 'doc' ## # ALPS specification ext element. EXT_ELEMENT = 'ext' ## # ALPS specification link element. LINK_ELEMENT = 'link' ## # ALPS specification elements that can be serialized. ALPS_ELEMENTS = [DOC_ELEMENT, EXT_ELEMENT, LINK_ELEMENT] ## # The ALPS attributes for the descriptor. # # @return [Hash] The attributes. def alps_attributes @alps_attributes ||= ALPS_ATTRIBUTES.inject({}) do |hash, attribute| alps_attribute = if attribute == 'name' alps_name else send(attribute) if respond_to?(attribute) end hash.tap { |h| h[attribute] = alps_attribute if alps_attribute } end end ## # The ALPS semantic and transition descriptors nested in the descriptor. # # @return [Array] The descriptors. def alps_descriptors @alps_descriptors ||= descriptors.map { |descriptor| descriptor.to_alps_hash(top_level: false) } end ## # The ALPS elements for the descriptor. # # @return [Hash] The elements. def alps_elements @alps_elements ||= ALPS_ELEMENTS.inject({}) do |hash, element| alps_value = send(element) if respond_to?(element) next hash unless alps_value alps_element = case element when DOC_ELEMENT if alps_value.is_a?(Hash) format = alps_value.keys.first {'format' => format, 'value' => alps_value[format]} else {'value' => alps_value } end when EXT_ELEMENT convert_ext_element_hrefs(alps_value) when LINK_ELEMENT unless alps_value.empty? alps_value.values.map do |link| {'rel' => link.rel, 'href' => absolute_link(link.href, link.rel)} end end end hash.tap { |h| h[element] = alps_element if alps_element } end end ## # Returns an ALPS profile or descriptor as a hash. # # @param [Hash] options Optional configurations. # @option options [Symbol] :top_level <tt>false</tt>, if the descriptor should not be wrapped in an 'alps' # element. Default is <tt>true</tt>. # # @return [Hash] The hash. def to_alps_hash(options = {}) hash = {} hash.merge!(alps_elements.dup) hash.merge!(alps_attributes.dup) hash['descriptor'] = alps_descriptors unless alps_descriptors.empty? if options[:top_level] != false hash.delete('id') {'alps' => hash} else hash end end ## # Returns an ALPS profile or descriptor as JSON. # # @param [Hash] options Optional configurations. # @option options [Boolean] :pretty <tt>true</tt> to pretty-print the json. # # @return [Hash] The JSON string. def to_json(options = {}) MultiJson.dump(to_alps_hash(options), :pretty => !!options.delete(:pretty)) end ## # Returns an ALPS profile or descriptor as XML. # # @param [Hash] options Optional configurations. # @option options [Integer] :indent Sets indentation of the tags. Default is 2. # # @return [Hash] The JSON string. def to_xml(options = {}) require 'builder' unless defined?(::Builder) options[:indent] ||= 2 options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent]) builder = options[:builder] builder.instruct! unless options[:skip_instruct] args = options[:top_level] != false ? ['alps'] : ['descriptor', alps_attributes] builder.tag!(*args) do add_xml_elements(builder) add_xml_descriptors(builder) end end private # Access specified name vs. id overloaded name. def alps_name descriptor_document['name'] end def add_xml_elements(builder) alps_elements.each do |alps_element, properties| case alps_element when DOC_ELEMENT format = {'format' => properties['format']} if properties['format'] builder.doc(format) { |doc| doc << properties['value'] } when EXT_ELEMENT, LINK_ELEMENT properties.each { |element_attributes| builder.tag!(alps_element, element_attributes) } end end end def config @config ||= Crichton.config end def absolute_link(orig_link, rel) if Addressable::URI.parse(orig_link).absolute? return orig_link end base_uri = rel == 'help' ? config.documentation_base_uri : config.alps_base_uri return "#{base_uri}/#{orig_link}" end def convert_ext_element_hrefs(ext_elem) if ext_elem.is_a?(Array) ext_elem.each {|eae| convert_ext_element_hash_hrefs(eae) } end convert_ext_element_hash_hrefs(ext_elem) ext_elem end def convert_ext_element_hash_hrefs(ext_elem) if ext_elem.is_a?(Hash) && ext_elem.include?('href') ext_elem['href'] = absolute_link(ext_elem['href'], nil) end end def add_xml_descriptors(builder) descriptors.each { |descriptor| descriptor.to_xml({top_level: false, builder: builder, skip_instruct: true}) } end end end end Changed condition structure require 'json' require 'multi_json' require 'addressable/uri' module Crichton module ALPS ## # Manages serialization to the Application-Level Profile Semantics (ALPS) specification JSON and XML formats. module Serialization ## # ALPS specification attributes that can be serialized. ALPS_ATTRIBUTES = %w(id name type href rt) ## # ALPS specification doc element. DOC_ELEMENT = 'doc' ## # ALPS specification ext element. EXT_ELEMENT = 'ext' ## # ALPS specification link element. LINK_ELEMENT = 'link' ## # ALPS specification elements that can be serialized. ALPS_ELEMENTS = [DOC_ELEMENT, EXT_ELEMENT, LINK_ELEMENT] ## # The ALPS attributes for the descriptor. # # @return [Hash] The attributes. def alps_attributes @alps_attributes ||= ALPS_ATTRIBUTES.inject({}) do |hash, attribute| alps_attribute = if attribute == 'name' alps_name else send(attribute) if respond_to?(attribute) end hash.tap { |h| h[attribute] = alps_attribute if alps_attribute } end end ## # The ALPS semantic and transition descriptors nested in the descriptor. # # @return [Array] The descriptors. def alps_descriptors @alps_descriptors ||= descriptors.map { |descriptor| descriptor.to_alps_hash(top_level: false) } end ## # The ALPS elements for the descriptor. # # @return [Hash] The elements. def alps_elements @alps_elements ||= ALPS_ELEMENTS.inject({}) do |hash, element| alps_value = send(element) if respond_to?(element) next hash unless alps_value alps_element = case element when DOC_ELEMENT if alps_value.is_a?(Hash) format = alps_value.keys.first {'format' => format, 'value' => alps_value[format]} else {'value' => alps_value } end when EXT_ELEMENT convert_ext_element_hrefs(alps_value) when LINK_ELEMENT unless alps_value.empty? alps_value.values.map do |link| {'rel' => link.rel, 'href' => absolute_link(link.href, link.rel)} end end end hash.tap { |h| h[element] = alps_element if alps_element } end end ## # Returns an ALPS profile or descriptor as a hash. # # @param [Hash] options Optional configurations. # @option options [Symbol] :top_level <tt>false</tt>, if the descriptor should not be wrapped in an 'alps' # element. Default is <tt>true</tt>. # # @return [Hash] The hash. def to_alps_hash(options = {}) hash = {} hash.merge!(alps_elements.dup) hash.merge!(alps_attributes.dup) hash['descriptor'] = alps_descriptors unless alps_descriptors.empty? if options[:top_level] != false hash.delete('id') {'alps' => hash} else hash end end ## # Returns an ALPS profile or descriptor as JSON. # # @param [Hash] options Optional configurations. # @option options [Boolean] :pretty <tt>true</tt> to pretty-print the json. # # @return [Hash] The JSON string. def to_json(options = {}) MultiJson.dump(to_alps_hash(options), :pretty => !!options.delete(:pretty)) end ## # Returns an ALPS profile or descriptor as XML. # # @param [Hash] options Optional configurations. # @option options [Integer] :indent Sets indentation of the tags. Default is 2. # # @return [Hash] The JSON string. def to_xml(options = {}) require 'builder' unless defined?(::Builder) options[:indent] ||= 2 options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent]) builder = options[:builder] builder.instruct! unless options[:skip_instruct] args = options[:top_level] != false ? ['alps'] : ['descriptor', alps_attributes] builder.tag!(*args) do add_xml_elements(builder) add_xml_descriptors(builder) end end private # Access specified name vs. id overloaded name. def alps_name descriptor_document['name'] end def add_xml_elements(builder) alps_elements.each do |alps_element, properties| case alps_element when DOC_ELEMENT format = {'format' => properties['format']} if properties['format'] builder.doc(format) { |doc| doc << properties['value'] } when EXT_ELEMENT, LINK_ELEMENT properties.each { |element_attributes| builder.tag!(alps_element, element_attributes) } end end end def config @config ||= Crichton.config end def absolute_link(orig_link, rel) if Addressable::URI.parse(orig_link).absolute? orig_link else "#{rel == 'help' ? config.documentation_base_uri : config.alps_base_uri}/#{orig_link}" end end def convert_ext_element_hrefs(ext_elem) if ext_elem.is_a?(Array) ext_elem.each {|eae| convert_ext_element_hash_hrefs(eae) } end convert_ext_element_hash_hrefs(ext_elem) ext_elem end def convert_ext_element_hash_hrefs(ext_elem) if ext_elem.is_a?(Hash) && ext_elem.include?('href') ext_elem['href'] = absolute_link(ext_elem['href'], nil) end end def add_xml_descriptors(builder) descriptors.each { |descriptor| descriptor.to_xml({top_level: false, builder: builder, skip_instruct: true}) } end end end end
module Cucumber module Salad module Widgets class Form < Widget def self.default_locator(type = nil, &block) alias_method :name_to_locator, type if type define_method :name_to_locator, &block if block end def self.check_box(name, label = nil) define_method "#{name}=" do |val| l = label || name_to_locator(name) if val root.check l else root.uncheck l end end end def self.select(name, *args) opts = args.extract_options! label, = args define_method "#{name}=" do |val| l = label || name_to_locator(name) w = opts.fetch(:writer) { ->(v) { v } } root.select w.(val).to_s, from: l end end def self.text_field(name, label = nil) define_method "#{name}=" do |val| l = label || name_to_locator(name) root.fill_in l, with: val.to_s end end def initialize(settings = {}) s = settings.dup data = s.delete(:data) || {} super s fill_all data if block_given? yield self submit end end def fill_all(attrs) attrs.each do |k, v| send "#{k}=", v end self end def submit root.find('[type = "submit"]').click self end # Submit form with +attrs+. # # @param attrs [Hash] the form fields and their values # # @return self def submit_with(attrs) fill_all attrs submit end private def label(name) name.to_s.humanize end def name_to_locator(name) label(name) end end end end end [form] Delete custom initialization. The behavior can be replicated using other instance methods. module Cucumber module Salad module Widgets class Form < Widget def self.default_locator(type = nil, &block) alias_method :name_to_locator, type if type define_method :name_to_locator, &block if block end def self.check_box(name, label = nil) define_method "#{name}=" do |val| l = label || name_to_locator(name) if val root.check l else root.uncheck l end end end def self.select(name, *args) opts = args.extract_options! label, = args define_method "#{name}=" do |val| l = label || name_to_locator(name) w = opts.fetch(:writer) { ->(v) { v } } root.select w.(val).to_s, from: l end end def self.text_field(name, label = nil) define_method "#{name}=" do |val| l = label || name_to_locator(name) root.fill_in l, with: val.to_s end end def fill_all(attrs) attrs.each do |k, v| send "#{k}=", v end self end def submit root.find('[type = "submit"]').click self end # Submit form with +attrs+. # # @param attrs [Hash] the form fields and their values # # @return self def submit_with(attrs) fill_all attrs submit end private def label(name) name.to_s.humanize end def name_to_locator(name) label(name) end end end end end
module Dapp module Dimg class Dimg module GitArtifact def git_artifacts [*local_git_artifacts, *remote_git_artifacts].compact end def local_git_artifacts @local_git_artifact_list ||= Array(config._git_artifact._local).map do |ga_config| repo = GitRepo::Own.new(self) ::Dapp::Dimg::GitArtifact.new(repo, **ga_config._artifact_options) end end def remote_git_artifacts @remote_git_artifact_list ||= Array(config._git_artifact._remote).map do |ga_config| repo = GitRepo::Remote.new(self, ga_config._name, url: ga_config._url) repo.fetch!(ga_config._branch) ::Dapp::Dimg::GitArtifact.new(repo, **ga_config._artifact_options) end end end # GitArtifact end # Mod end # Dimg end # Dapp git artifact: reusing git repo module Dapp module Dimg class Dimg module GitArtifact def git_artifacts [*local_git_artifacts, *remote_git_artifacts].compact end def local_git_artifacts @local_git_artifact_list ||= begin repo = GitRepo::Own.new(self) Array(config._git_artifact._local).map do |ga_config| ::Dapp::Dimg::GitArtifact.new(repo, **ga_config._artifact_options) end end end def remote_git_artifacts @remote_git_artifact_list ||= begin repos = {} Array(config._git_artifact._remote).map do |ga_config| repo_key = [ga_config._url, ga_config._branch] repos[repo_key] ||= GitRepo::Remote.new(self, ga_config._name, url: ga_config._url).tap { |repo| repo.fetch!(ga_config._branch) } ::Dapp::Dimg::GitArtifact.new(repos[repo_key], **ga_config._artifact_options) end end end end # GitArtifact end # Mod end # Dimg end # Dapp
module DataMapper module Relation # Relation # # @api public class Mapper < DataMapper::Mapper include Equalizer.new(:environment, :model, :attributes, :relationships, :relation) DEFAULT_LIMIT_FOR_ONE = 2 alias_method :all, :to_a accept_options :relation_name, :repository # Return the mapper's environment object # # @return [Environment] # # @api private attr_reader :environment # The relation backing this mapper # # @example # # mapper = env[Person] # mapper.relation # # @return [Graph::Node] # # @api public attr_reader :relation # This mapper's set of relationships to map # # @example # # mapper = env[User] # mapper.relationships # # @return [RelationshipSet] # # @api public attr_reader :relationships # Return a new mapper class derived from the given one # # @see Mapper.from # # @example # # other = env[Person].class # DataMapper::Relation::Mapper.from(other, 'AdminMapper') # # @return [Mapper] # # @api public def self.from(other, _name = nil) klass = super klass.repository(other.repository) klass.relation_name(other.relation_name) other.relationships.each do |relationship| klass.relationships << relationship end klass end # Returns relation for this mapper class # # @example # # DataMapper::Relation::Mapper.relation # # @return [Object] # # @api public def self.relation end # Mark the given attribute names as (part of) the key # # @example # # class Person # include DataMapper::Model # attribute :id, Integer # end # # env.build(Person, :postgres) do # key :id # end # # @param [(Symbol)] *names # the attribute names that together consitute the key # # @return [self] # # @api public def self.key(*names) attribute_set = attributes names.each do |name| attribute_set << attribute_set[name].clone(:key => true) end self end # Establishes a relationship with the given cardinality and name # # @example # # class UserMapper < DataMapper::Relation::Mapper # has 1, :address, Address # has 0..n, :orders, Order # end # # @param [Fixnum,Range] # @param [Symbol] name for the relationship # @param [*args] # @param [Proc] optional operation that should be evaluated on the relation # # @return [self] # # @api public def self.has(cardinality, name, *args, &op) relationship = Relationship::Builder::Has.build( self, cardinality, name, *args, &op ) relationships << relationship self end # Establishes a one-to-many relationship # # @example # # class UserMapper < DataMapper::Relation::Mapper # belongs_to :group, Group # end # # @param [Symbol] # @param [*args] # @param [Proc] optional operation that should be evaluated on the relation # # @return [self] # # @api public def self.belongs_to(name, *args, &op) relationship = Relationship::Builder::BelongsTo.build( self, name, *args, &op ) relationships << relationship self end # Returns infinity constant # # @example # # class UserMapper < DataMapper::Relation::Mapper # has n, :orders, Order # end # # @return [Float] # # @api public def self.n Infinity end # Returns relationship set for this mapper class # # @return [RelationshipSet] # # @api private def self.relationships @relationships ||= RelationshipSet.new end def self.default_relation(environment) relation || environment.repository(repository).get(relation_name) end # Initialize a relation mapper instance # # @param [Environment] environment # the new mapper's environment # # @param [Veritas::Relation] relation # the relation to map from # # @param [DataMapper::Mapper::AttributeSet] attributes # the set of attributes to map # # @return [undefined] # # @api private def initialize(environment, relation = default_relation(environment), attributes = self.class.attributes) super(relation) @environment = environment @relation = relation @attributes = attributes @relationships = self.class.relationships end # Shortcut for self.class.relations # # @see Engine#relations # # @example # mapper = env[User] # mapper.relations # # @return [Graph] # # @api public def relations environment.relations end # The mapped relation's name # # @see Relation::Mapper.relation_name # # @example # # mapper = env[Person] # mapper.relation_name # # @return [Symbol] # # @api public def relation_name self.class.relation_name end # Return a mapper for iterating over the relation restricted with options # # @see Veritas::Relation#restrict # # @example # # mapper = env[Person] # mapper.find(:name => 'John').all # # @param [Hash] conditions # the options to restrict the relation # # @return [Relation::Mapper] # # @api public def find(conditions = EMPTY_HASH) new(restricted_relation(conditions)) end # Return a mapper for iterating over the relation ordered by *order # # @example # # mapper = env[Person] # mapper.one(:name => 'John') # # @param [Hash] conditions # the options to restrict the relation # # @raise [NoTuplesError] # raised if no tuples are returned # @raise [ManyTuplesError] # raised if more than one tuple is returned # # @return [Object] # a domain object # # @api public def one(conditions = EMPTY_HASH) results = new(limited_relation(conditions, DEFAULT_LIMIT_FOR_ONE)).to_a assert_exactly_one_tuple(results.size) results.first end # Return a mapper for iterating over a restricted set of domain objects # # @example # # env[Person].restrict { |r| r.name.eq('John') }.each do |person| # puts person.name # end # # @param [Proc] &block # the block to restrict the relation with # # @return [Relation::Mapper] # # @api public def restrict(&block) new(relation.restrict(&block)) end # Return a mapper for iterating over the relation ordered by *order # # @see Veritas::Relation#sort_by # # @example # # mapper = env[Person] # mapper.order(:name).to_a # # @param [(Symbol)] *order # the attribute names to order by # # @return [Relation::Mapper] # # @api public def order(*names) attribute_set = attributes order_attributes = names.map { |attribute| attribute_set.field_name(attribute) } order_attributes.concat(attribute_set.fields).uniq! new(relation.order(*order_attributes)) end # Return a mapper for iterating over a sorted set of domain objects # # @see Veritas::Relation#sort_by # # @example with directions # # env[Person].sort_by(:name).each do |person| # puts person.name # end # # @example with a block # # mappers[Person].sort_by { |r| [ r.name.desc ] }.each do |person| # puts person.name # end # # @param [(Symbol)] *args # the sort directions # # @param [Proc] &block # the block to evaluate for the sort directions # # @return [Relation::Mapper] # # @api public def sort_by(*args, &block) new(relation.sort_by(*args, &block)) end # Limit the underlying ordered relation to the first +limit+ tuples # # @example # # people = env[Person].sort_by { |r| [ r.id.asc ] } # people.take(7) # # @param [Integer] limit # the maximum number of tuples in the limited relation # # @return [Mapper] # a new mapper backed by a relation with the first +limit+ tuples # # @raise [Veritas::OrderedRelationRequiredError] # raised if the operand is unordered # # @api public def take(limit) new(relation.take(limit)) end # Limit the underlying ordered relation to the first +limit+ tuples # # @example with no limit # # people = env[Person].sort_by { |r| [ r.id.asc ] } # people.first # # @example with a limit # # people = env[Person].sort_by { |r| [ r.id.asc ] } # people.first(7) # # @param [Integer] limit # optional number of tuples from the beginning of the relation # # @return [Mapper] # a new mapper backed by a relation with the first +limit+ tuples # # @api public def first(limit = 1) new(relation.first(limit)) end # Limit the underlying ordered relation to the last +limit+ tuples # # @example with no limit # limited_relation = relation.last # # @example with a limit # limited_relation = relation.last(7) # # @param [Integer] limit # optional number of tuples from the end of the relation # # @return [Mapper] # a new mapper backed by a relation with the last +limit+ tuples # # @api public def last(limit = 1) new(relation.last(limit)) end # Drop tuples before +offset+ in an ordered relation # # @example # # people = env[Person].sort_by { |r| [ r.id.asc ] } # people.drop(7) # # @param [Integer] offset # the offset of the relation to drop # # @return [Relation::Mapper] # a new mapper backed by the offset relation # # @raise [Veritas::OrderedRelationRequiredError] # raised if the operand is unordered # # @api public def drop(offset) new(relation.drop(offset)) end # Return a mapper for iterating over domain objects with renamed attributes # # @example # # env[Person].rename(:name => :nickname).each do |person| # puts person.nickname # end # # @param [Hash] aliases # the old and new attribute names as alias pairs # # @return [Relation::Mapper] # # @api public def rename(aliases) new(relation.rename(aliases)) end # Return a mapper for iterating over the result of joining other with self # # TODO investigate if the following example works # # @example # # env[Person].join(env[Task]).each do |person| # puts person.tasks.size # end # # @param [Relation::Mapper] other # the other mapper to join with self # # @return [Relation::Mapper] # # @api public def join(other) new(relation.join(other.relation)) end # Return a new instance with mapping that corresponds to aliases # # TODO find a better name # # @param [Graph::Node::Aliases, Hash] aliases # the aliases to use in the returned instance # # @return [Relation::Mapper] # # @api private def remap(aliases) new(relation, attributes.remap(aliases)) end # Return a mapper for iterating over domain objects with loaded relationships # # @example # # env[Person].include(:tasks).each do |person| # person.tasks.each do |task| # puts task.name # end # end # # @param [Symbol] name # the name of the relationship to include # # @return [Relation::Mapper] # # @api public def include(name) environment.registry[model, relationships[name]] end # Insert +tuples+ into the underlying relation # # @example # # person = Person.new(:id => 1, :name => 'John') # env[Person].insert([ person ]) # # @param [Enumerable] object # an enumerable coercible by {Veritas::Relation.coerce} # # @return [Mapper] # a new mapper backed by a relation containing +object+ # # @api public def insert(object) new(relation.insert(dump(object))) end # Update +tuples+ in the underlying relation # # @example # # person = Person.new(:id => 1, :name => 'John') # env[Person].update([ person ]) # # @param [Enumerable] tuples # an enumerable coercible by {Veritas::Relation.coerce} # # @return [Node] # a new node backed by a relation including +tuples+ # # @raise [NotImplementedError] # this method is not yet implemented # # @api public def update(object) new(relation.update(dump(object))) end # Delete +object+ from the underlying relation # # @example # # person = Person.new(:id => 1, :name => 'John') # mapper = env[Person] # mapper.insert([ person ]) # mapper.delete([ person ]) # # @param [Enumerable] object # an enumerable coercible by {Veritas::Relation.coerce} # # @return [Mapper] # a new mapper backed by a relation excluding +object+ # # @api public def delete(object) new(relation.delete(dump(object))) end # Replace the underlying relation with +object+ # # @example # # john = Person.new(:id => 1, :name => 'John') # jane = Person.new(:id => 2, :name => 'Jane') # alice = Person.new(:id => 1, :name => 'Jane') # # mapper = env[Person] # mapper.insert([ john, jane ]) # mapper.replace([ alice ]) # # @param [Enumerable] object # an enumerable coercible by {Veritas::Relation.coerce} # # @return [Mapper] # a new mapper backed by a relation only including +object+ # # @api public def replace(object) new(relation.replace(dump(object))) end # The mapper's human readable representation # # @example # # mapper = env[Person] # puts mapper.inspect # # @return [String] # # @api public def inspect klass = self.class "#<#{klass.name} @model=#{model.name} @relation_name=#{relation_name} @repository=#{klass.repository}>" end private def default_relation(environment) self.class.default_relation(environment) end def restricted_relation(conditions) relation.restrict(Query.new(conditions, attributes)) end def limited_relation(conditions, limit) restricted_relation(conditions).ordered.take(limit) end # Assert exactly one tuple is returned # # @return [undefined] # # @raise [NoTuplesError] # raised if no tuples are returned # @raise [ManyTuplesError] # raised if more than one tuple is returned # # @api private def assert_exactly_one_tuple(size) if size.zero? raise NoTuplesError, 'one tuple expected, but none was returned' elsif size > 1 raise ManyTuplesError, "one tuple expected, but #{size} were returned" end end # Return a new mapper instance # # @param [Graph::Node] # # @api private def new(relation, attributes = self.attributes) self.class.new(environment, relation, attributes) end end # class Mapper end # module Relation end # module DataMapper Extract private Relation::Mapper#default_attributes This also tricks reek into thinking that we're not calling 'self.class' two times. module DataMapper module Relation # Relation # # @api public class Mapper < DataMapper::Mapper include Equalizer.new(:environment, :model, :attributes, :relationships, :relation) DEFAULT_LIMIT_FOR_ONE = 2 alias_method :all, :to_a accept_options :relation_name, :repository # Return the mapper's environment object # # @return [Environment] # # @api private attr_reader :environment # The relation backing this mapper # # @example # # mapper = env[Person] # mapper.relation # # @return [Graph::Node] # # @api public attr_reader :relation # This mapper's set of relationships to map # # @example # # mapper = env[User] # mapper.relationships # # @return [RelationshipSet] # # @api public attr_reader :relationships # Return a new mapper class derived from the given one # # @see Mapper.from # # @example # # other = env[Person].class # DataMapper::Relation::Mapper.from(other, 'AdminMapper') # # @return [Mapper] # # @api public def self.from(other, _name = nil) klass = super klass.repository(other.repository) klass.relation_name(other.relation_name) other.relationships.each do |relationship| klass.relationships << relationship end klass end # Returns relation for this mapper class # # @example # # DataMapper::Relation::Mapper.relation # # @return [Object] # # @api public def self.relation end # Mark the given attribute names as (part of) the key # # @example # # class Person # include DataMapper::Model # attribute :id, Integer # end # # env.build(Person, :postgres) do # key :id # end # # @param [(Symbol)] *names # the attribute names that together consitute the key # # @return [self] # # @api public def self.key(*names) attribute_set = attributes names.each do |name| attribute_set << attribute_set[name].clone(:key => true) end self end # Establishes a relationship with the given cardinality and name # # @example # # class UserMapper < DataMapper::Relation::Mapper # has 1, :address, Address # has 0..n, :orders, Order # end # # @param [Fixnum,Range] # @param [Symbol] name for the relationship # @param [*args] # @param [Proc] optional operation that should be evaluated on the relation # # @return [self] # # @api public def self.has(cardinality, name, *args, &op) relationship = Relationship::Builder::Has.build( self, cardinality, name, *args, &op ) relationships << relationship self end # Establishes a one-to-many relationship # # @example # # class UserMapper < DataMapper::Relation::Mapper # belongs_to :group, Group # end # # @param [Symbol] # @param [*args] # @param [Proc] optional operation that should be evaluated on the relation # # @return [self] # # @api public def self.belongs_to(name, *args, &op) relationship = Relationship::Builder::BelongsTo.build( self, name, *args, &op ) relationships << relationship self end # Returns infinity constant # # @example # # class UserMapper < DataMapper::Relation::Mapper # has n, :orders, Order # end # # @return [Float] # # @api public def self.n Infinity end # Returns relationship set for this mapper class # # @return [RelationshipSet] # # @api private def self.relationships @relationships ||= RelationshipSet.new end def self.default_relation(environment) relation || environment.repository(repository).get(relation_name) end # Initialize a relation mapper instance # # @param [Environment] environment # the new mapper's environment # # @param [Veritas::Relation] relation # the relation to map from # # @param [DataMapper::Mapper::AttributeSet] attributes # the set of attributes to map # # @return [undefined] # # @api private def initialize(environment, relation = default_relation(environment), attributes = default_attributes) super(relation) @environment = environment @relation = relation @attributes = attributes @relationships = self.class.relationships end # Shortcut for self.class.relations # # @see Engine#relations # # @example # mapper = env[User] # mapper.relations # # @return [Graph] # # @api public def relations environment.relations end # The mapped relation's name # # @see Relation::Mapper.relation_name # # @example # # mapper = env[Person] # mapper.relation_name # # @return [Symbol] # # @api public def relation_name self.class.relation_name end # Return a mapper for iterating over the relation restricted with options # # @see Veritas::Relation#restrict # # @example # # mapper = env[Person] # mapper.find(:name => 'John').all # # @param [Hash] conditions # the options to restrict the relation # # @return [Relation::Mapper] # # @api public def find(conditions = EMPTY_HASH) new(restricted_relation(conditions)) end # Return a mapper for iterating over the relation ordered by *order # # @example # # mapper = env[Person] # mapper.one(:name => 'John') # # @param [Hash] conditions # the options to restrict the relation # # @raise [NoTuplesError] # raised if no tuples are returned # @raise [ManyTuplesError] # raised if more than one tuple is returned # # @return [Object] # a domain object # # @api public def one(conditions = EMPTY_HASH) results = new(limited_relation(conditions, DEFAULT_LIMIT_FOR_ONE)).to_a assert_exactly_one_tuple(results.size) results.first end # Return a mapper for iterating over a restricted set of domain objects # # @example # # env[Person].restrict { |r| r.name.eq('John') }.each do |person| # puts person.name # end # # @param [Proc] &block # the block to restrict the relation with # # @return [Relation::Mapper] # # @api public def restrict(&block) new(relation.restrict(&block)) end # Return a mapper for iterating over the relation ordered by *order # # @see Veritas::Relation#sort_by # # @example # # mapper = env[Person] # mapper.order(:name).to_a # # @param [(Symbol)] *order # the attribute names to order by # # @return [Relation::Mapper] # # @api public def order(*names) attribute_set = attributes order_attributes = names.map { |attribute| attribute_set.field_name(attribute) } order_attributes.concat(attribute_set.fields).uniq! new(relation.order(*order_attributes)) end # Return a mapper for iterating over a sorted set of domain objects # # @see Veritas::Relation#sort_by # # @example with directions # # env[Person].sort_by(:name).each do |person| # puts person.name # end # # @example with a block # # mappers[Person].sort_by { |r| [ r.name.desc ] }.each do |person| # puts person.name # end # # @param [(Symbol)] *args # the sort directions # # @param [Proc] &block # the block to evaluate for the sort directions # # @return [Relation::Mapper] # # @api public def sort_by(*args, &block) new(relation.sort_by(*args, &block)) end # Limit the underlying ordered relation to the first +limit+ tuples # # @example # # people = env[Person].sort_by { |r| [ r.id.asc ] } # people.take(7) # # @param [Integer] limit # the maximum number of tuples in the limited relation # # @return [Mapper] # a new mapper backed by a relation with the first +limit+ tuples # # @raise [Veritas::OrderedRelationRequiredError] # raised if the operand is unordered # # @api public def take(limit) new(relation.take(limit)) end # Limit the underlying ordered relation to the first +limit+ tuples # # @example with no limit # # people = env[Person].sort_by { |r| [ r.id.asc ] } # people.first # # @example with a limit # # people = env[Person].sort_by { |r| [ r.id.asc ] } # people.first(7) # # @param [Integer] limit # optional number of tuples from the beginning of the relation # # @return [Mapper] # a new mapper backed by a relation with the first +limit+ tuples # # @api public def first(limit = 1) new(relation.first(limit)) end # Limit the underlying ordered relation to the last +limit+ tuples # # @example with no limit # limited_relation = relation.last # # @example with a limit # limited_relation = relation.last(7) # # @param [Integer] limit # optional number of tuples from the end of the relation # # @return [Mapper] # a new mapper backed by a relation with the last +limit+ tuples # # @api public def last(limit = 1) new(relation.last(limit)) end # Drop tuples before +offset+ in an ordered relation # # @example # # people = env[Person].sort_by { |r| [ r.id.asc ] } # people.drop(7) # # @param [Integer] offset # the offset of the relation to drop # # @return [Relation::Mapper] # a new mapper backed by the offset relation # # @raise [Veritas::OrderedRelationRequiredError] # raised if the operand is unordered # # @api public def drop(offset) new(relation.drop(offset)) end # Return a mapper for iterating over domain objects with renamed attributes # # @example # # env[Person].rename(:name => :nickname).each do |person| # puts person.nickname # end # # @param [Hash] aliases # the old and new attribute names as alias pairs # # @return [Relation::Mapper] # # @api public def rename(aliases) new(relation.rename(aliases)) end # Return a mapper for iterating over the result of joining other with self # # TODO investigate if the following example works # # @example # # env[Person].join(env[Task]).each do |person| # puts person.tasks.size # end # # @param [Relation::Mapper] other # the other mapper to join with self # # @return [Relation::Mapper] # # @api public def join(other) new(relation.join(other.relation)) end # Return a new instance with mapping that corresponds to aliases # # TODO find a better name # # @param [Graph::Node::Aliases, Hash] aliases # the aliases to use in the returned instance # # @return [Relation::Mapper] # # @api private def remap(aliases) new(relation, attributes.remap(aliases)) end # Return a mapper for iterating over domain objects with loaded relationships # # @example # # env[Person].include(:tasks).each do |person| # person.tasks.each do |task| # puts task.name # end # end # # @param [Symbol] name # the name of the relationship to include # # @return [Relation::Mapper] # # @api public def include(name) environment.registry[model, relationships[name]] end # Insert +tuples+ into the underlying relation # # @example # # person = Person.new(:id => 1, :name => 'John') # env[Person].insert([ person ]) # # @param [Enumerable] object # an enumerable coercible by {Veritas::Relation.coerce} # # @return [Mapper] # a new mapper backed by a relation containing +object+ # # @api public def insert(object) new(relation.insert(dump(object))) end # Update +tuples+ in the underlying relation # # @example # # person = Person.new(:id => 1, :name => 'John') # env[Person].update([ person ]) # # @param [Enumerable] tuples # an enumerable coercible by {Veritas::Relation.coerce} # # @return [Node] # a new node backed by a relation including +tuples+ # # @raise [NotImplementedError] # this method is not yet implemented # # @api public def update(object) new(relation.update(dump(object))) end # Delete +object+ from the underlying relation # # @example # # person = Person.new(:id => 1, :name => 'John') # mapper = env[Person] # mapper.insert([ person ]) # mapper.delete([ person ]) # # @param [Enumerable] object # an enumerable coercible by {Veritas::Relation.coerce} # # @return [Mapper] # a new mapper backed by a relation excluding +object+ # # @api public def delete(object) new(relation.delete(dump(object))) end # Replace the underlying relation with +object+ # # @example # # john = Person.new(:id => 1, :name => 'John') # jane = Person.new(:id => 2, :name => 'Jane') # alice = Person.new(:id => 1, :name => 'Jane') # # mapper = env[Person] # mapper.insert([ john, jane ]) # mapper.replace([ alice ]) # # @param [Enumerable] object # an enumerable coercible by {Veritas::Relation.coerce} # # @return [Mapper] # a new mapper backed by a relation only including +object+ # # @api public def replace(object) new(relation.replace(dump(object))) end # The mapper's human readable representation # # @example # # mapper = env[Person] # puts mapper.inspect # # @return [String] # # @api public def inspect klass = self.class "#<#{klass.name} @model=#{model.name} @relation_name=#{relation_name} @repository=#{klass.repository}>" end private def default_relation(environment) self.class.default_relation(environment) end def default_attributes self.class.attributes end def restricted_relation(conditions) relation.restrict(Query.new(conditions, attributes)) end def limited_relation(conditions, limit) restricted_relation(conditions).ordered.take(limit) end # Assert exactly one tuple is returned # # @return [undefined] # # @raise [NoTuplesError] # raised if no tuples are returned # @raise [ManyTuplesError] # raised if more than one tuple is returned # # @api private def assert_exactly_one_tuple(size) if size.zero? raise NoTuplesError, 'one tuple expected, but none was returned' elsif size > 1 raise ManyTuplesError, "one tuple expected, but #{size} were returned" end end # Return a new mapper instance # # @param [Graph::Node] # # @api private def new(relation, attributes = self.attributes) self.class.new(environment, relation, attributes) end end # class Mapper end # module Relation end # module DataMapper
module DatabaseCleaner module Mongo def self.available_strategies %w[truncation] end module Base def db=(desired_db) @db = desired_db end def db @db || raise("You have not specified a database. (see Mongo::Database)") end end end end Added require mongoid. require 'mongoid' module DatabaseCleaner module Mongo def self.available_strategies %w[truncation] end module Base def db=(desired_db) @db = desired_db end def db @db || raise("You have not specified a database. (see Mongo::Database)") end end end end
# # Be sure to run `pod lib lint HFTableCollectionBindingHelper.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # Any lines starting with a # are optional, but encouraged # # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = "HFTableCollectionBindingHelper" s.version = "0.5.0" s.summary = "iOS table view and collection view binding helper for MVVM." s.description = <<-DESC helper functions to bind UITableView or UICollectionView instances to ViewModels in MVVM architecture * Markdown format. * Don't worry about the indent, we strip it! DESC s.homepage = "https://github.com/haifengkao/HFTableCollectionBindingHelper" s.license = 'MIT' s.author = { "Hai Feng Kao" => "haifeng@cocoaspice.in" } s.source = { :git => "https://github.com/haifengkao/HFTableCollectionBindingHelper.git", :tag => s.version.to_s } s.platform = :ios, '7.0' s.requires_arc = true s.source_files = 'Pod/Classes/**/*' # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' s.dependency 'KVOMutableArray/ReactiveCocoaSupport' s.dependency 'ReactiveCocoa/Core' s.dependency 'WZProtocolInterceptor' end - bump to 0.7 # # Be sure to run `pod lib lint HFTableCollectionBindingHelper.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # Any lines starting with a # are optional, but encouraged # # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = "HFTableCollectionBindingHelper" s.version = "0.7.0" s.summary = "iOS table view and collection view binding helper for MVVM." s.description = <<-DESC helper functions to bind UITableView or UICollectionView instances to ViewModels in MVVM architecture * Markdown format. * Don't worry about the indent, we strip it! DESC s.homepage = "https://github.com/haifengkao/HFTableCollectionBindingHelper" s.license = 'MIT' s.author = { "Hai Feng Kao" => "haifeng@cocoaspice.in" } s.source = { :git => "https://github.com/haifengkao/HFTableCollectionBindingHelper.git", :tag => s.version.to_s } s.platform = :ios, '7.0' s.requires_arc = true s.source_files = 'Pod/Classes/**/*' # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' s.dependency 'KVOMutableArray/ReactiveCocoaSupport' s.dependency 'ReactiveCocoa/Core' s.dependency 'WZProtocolInterceptor' end
module ODLifier VERSION = "0.0.1" end Update version file module Odlifier VERSION = "0.0.1" end
module OkGntpd VERSION = "0.0.1" end bumped version to 0.0.2 module OkGntpd VERSION = "0.0.2" end
module Omniship VERSION = "0.3.2" end Changed version module Omniship VERSION = "0.3.2.1" end
module Overcommit module Utils class << self include ConsoleMethods def hook_name File.basename($0).gsub('-', '_') end def load_hooks require File.expand_path("../hooks/#{hook_name}", __FILE__) rescue LoadError error "No hook definition found for #{hook_name}" exit 1 end def script_path(script) File.join(File.expand_path('../../hooks/scripts', $0), script) end # Shamelessly stolen from: # http://stackoverflow.com/questions/1509915/converting-camel-case-to-underscore-case-in-ruby def underscorize(str) str.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end end end end Address style cleanups in Utils As pointed out by Joe on https://gerrit.causes.com/#/c/22332/2/lib/overcommit/utils.rb Change-Id: I5cc01a344f2b9ca9098969b72ff21ad3c91eb430 Reviewed-on: https://gerrit.causes.com/22356 Reviewed-by: Aiden Scandella <1faf1e8390cdac9204f160c35828cc423b7acd7b@causes.com> Tested-by: Aiden Scandella <1faf1e8390cdac9204f160c35828cc423b7acd7b@causes.com> module Overcommit module Utils class << self include ConsoleMethods def hook_name File.basename($0).tr('-', '_') end def load_hooks require File.expand_path("../hooks/#{hook_name}", __FILE__) rescue LoadError error "No hook definition found for #{hook_name}" exit 1 end def script_path(script) File.join(File.expand_path('../../hooks/scripts', $0), script) end # Shamelessly stolen from: # http://stackoverflow.com/questions/1509915/converting-camel-case-to-underscore-case-in-ruby def underscorize(str) str.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2'). gsub(/([a-z\d])([A-Z])/, '\1_\2'). tr('-', '_'). downcase end end end end
module Parsable VERSION = "0.2.5" end Version bump to v0.2.6 module Parsable VERSION = "0.2.6" end