query
stringlengths
7
9.5k
document
stringlengths
10
1.07M
negatives
listlengths
19
19
metadata
dict
End of is_plural? Method: walk_association Purpose: Walks the association into the object passed to it Arguments: object_string : friendly text string name for the object association : friendly text string name for the association associated_objects : the list of objects in the association Returns: None
def walk_association(object_string, association, associated_objects) begin # # Assemble some fake code to make it look like we're iterating though associations (plural) # number_of_associated_objects = associated_objects.length if is_plural?(association) assignment_string = "#{object_string}.#{association}.each do |#{association.singularize}|" else assignment_string = "#{association} = #{object_string}.#{association}" end print_line($recursion_level, "#{assignment_string}") associated_objects.each do |associated_object| associated_object_class = "#{associated_object.method_missing(:class)}".demodulize associated_object_id = associated_object.id rescue associated_object.object_id print_line($recursion_level, "(object type: #{associated_object_class}, object ID: #{associated_object_id})") if is_plural?(association) walk_object("#{association.singularize}", associated_object) if number_of_associated_objects > 1 print_line($recursion_level, "--- next #{association.singularize} ---") number_of_associated_objects -= 1 else print_line($recursion_level, "--- end of #{object_string}.#{association}.each do |#{association.singularize}| ---") end else walk_object("#{association}", associated_object) end end rescue => err $evm.log("error", "#{$method} (walk_association) - [#{err}]\n#{err.backtrace.join("\n")}") end end
[ "def dump_association(object_string, association, associated_objects, indent_string)\n begin\n #\n # Assemble some fake code to make it look like we're iterating though associations (plural)\n #\n number_of_associated_objects = associated_objects.length\n if is_plural?(association)\n assignment_string = \"#{object_string}.#{association}.each do |#{association.singularize}|\"\n else\n assignment_string = \"#{association} = #{object_string}.#{association}\"\n end\n log(:info, \"#{indent_string}#{@method}: #{assignment_string}\")\n associated_objects.each do |associated_object|\n associated_object_class = \"#{associated_object.method_missing(:class)}\".demodulize\n associated_object_id = associated_object.id rescue associated_object.object_id\n log(:info, \"#{indent_string}| #{@method}: (object type: #{associated_object_class}, object ID: #{associated_object_id})\")\n if is_plural?(association)\n dump_object(\"#{association.singularize}\", associated_object, indent_string)\n if number_of_associated_objects > 1\n log(:info, \"#{indent_string}#{@method}: --- next #{association.singularize} ---\")\n number_of_associated_objects -= 1\n else\n log(:info, \"#{indent_string}#{@method}: --- end of #{object_string}.#{association}.each do |#{association.singularize}| ---\")\n end\n else\n dump_object(\"#{association}\", associated_object, indent_string)\n end\n end\n rescue => err\n log(:error, \"#{@method} (dump_association) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def dump_association(object_string, association, associated_objects, spaces)\n begin\n #\n # Assemble some fake code to make it look like we're iterating though associations (plural)\n #\n number_of_associated_objects = associated_objects.length\n if (association =~ /.*s$/)\n assignment_string = \"#{object_string}.#{association}.each do |#{association.chop}|\"\n else\n assignment_string = \"#{association} = #{object_string}.#{association}\"\n end\n $evm.log(\"info\", \"#{spaces}#{@method}: #{assignment_string}\")\n associated_objects.each do |associated_object|\n associated_object_class = \"#{associated_object.method_missing(:class)}\".demodulize\n associated_object_id = associated_object.id rescue associated_object.object_id\n $evm.log(\"info\", \"#{spaces}| #{@method}: (object type: #{associated_object_class}, object ID: #{associated_object_id})\")\n if (association =~ /.*s$/)\n dump_object(\"#{association.chop}\", associated_object, spaces)\n if number_of_associated_objects > 1\n $evm.log(\"info\", \"#{spaces}#{@method}: --- next #{association.chop} ---\")\n number_of_associated_objects -= 1\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: --- end of #{object_string}.#{association}.each do |#{association.chop}| ---\")\n end\n else\n dump_object(\"#{association}\", associated_object, spaces)\n end\n end\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_association) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend", "def dump_associations(object_string, this_object, this_object_class, indent_string)\n begin\n #\n # Print the associations of this object according to the @walk_associations_whitelist & @walk_associations_blacklist hashes\n #\n object_associations = []\n associated_objects = []\n duplicates = []\n if this_object.respond_to?(:associations)\n log(:info, \"#{indent_string}#{@method}: --- associations follow ---\")\n object_associations = Array(this_object.associations)\n duplicates = object_associations.select{|item| object_associations.count(item) > 1}\n if duplicates.length > 0\n log(:info, \"#{indent_string}#{@method}: *** De-duplicating the following associations: #{duplicates.inspect} (product bug?) ***\")\n end\n object_associations.uniq.sort.each do |association|\n begin\n associated_objects = Array(this_object.send(association))\n if associated_objects.length == 0\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{association} (type: Association (empty))\")\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{association} (type: Association)\")\n #\n # See if we need to walk this association according to the @walk_association_policy variable, and the @walk_association_{whitelist,blacklist} hashes\n #\n if @walk_association_policy == :whitelist\n if @walk_association_whitelist.has_key?(this_object_class) &&\n (@walk_association_whitelist[this_object_class].include?(:ALL) || @walk_association_whitelist[this_object_class].include?(association.to_s))\n dump_association(object_string, association, associated_objects, indent_string)\n else\n log(:info, \"#{indent_string}#{@method}: *** not walking: \\'#{association}\\' isn't in the @walk_association_whitelist hash for #{this_object_class} ***\")\n end\n elsif @walk_association_policy == :blacklist\n if @walk_association_blacklist.has_key?(this_object_class) &&\n (@walk_association_blacklist[this_object_class].include?(:ALL) || @walk_association_blacklist[this_object_class].include?(association.to_s))\n log(:info, \"#{indent_string}#{@method}: *** not walking: \\'#{association}\\' is in the @walk_association_blacklist hash for #{this_object_class} ***\")\n else\n dump_association(object_string, association, associated_objects, indent_string)\n end\n else\n log(:info, \"#{indent_string}#{@method}: *** Invalid @walk_association_policy: #{@walk_association_policy} ***\")\n return\n end\n end\n rescue NoMethodError\n log(:info, \"#{indent_string}#{@method}: *** #{this_object_class} association: \\'#{association}\\', gives a NoMethodError when accessed (product bug?) ***\")\n end\n end\n log(:info, \"#{indent_string}#{@method}: --- end of associations ---\")\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no associations\")\n end\n rescue => err\n log(:error, \"#{@method} (dump_associations) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def print_associations(object_string, this_object, this_object_class)\n begin\n #\n # Only dump the associations of an MiqAeMethodService::* class\n #\n if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n #\n # Print the associations of this object according to the\n # $walk_associations_whitelist & $walk_associations_blacklist hashes\n #\n associations = []\n associated_objects = []\n duplicates = []\n if this_object.respond_to?(:associations)\n associations = Array.wrap(this_object.associations)\n if associations.length.zero?\n print_line($recursion_level, \"--- no associations ---\")\n else\n print_line($recursion_level, \"--- associations follow ---\")\n duplicates = associations.select{|item| associations.count(item) > 1}\n if duplicates.length > 0\n print_line($recursion_level,\n \"*** De-duplicating the following associations: #{duplicates.inspect} ***\")\n end\n associations.uniq.sort.each do |association|\n begin\n associated_objects = Array.wrap(this_object.method_missing(:send, association))\n if associated_objects.length == 0\n print_line($recursion_level,\n \"#{object_string}.#{association} (type: Association (empty))\")\n else\n print_line($recursion_level, \"#{object_string}.#{association} (type: Association)\")\n #\n # See if we need to walk this association according to the walk_association_policy\n # variable, and the walk_association_{whitelist,blacklist} hashes\n #\n if $walk_association_policy == 'whitelist'\n if $walk_association_whitelist.has_key?(this_object_class) &&\n ($walk_association_whitelist[this_object_class].include?('ALL') ||\n $walk_association_whitelist[this_object_class].include?(association.to_s))\n walk_association(object_string, association, associated_objects)\n else\n print_line($recursion_level,\n \"*** not walking: \\'#{association}\\' isn't in the walk_association_whitelist \" \\\n \"hash for #{this_object_class} ***\")\n end\n elsif $walk_association_policy == 'blacklist'\n if $walk_association_blacklist.has_key?(this_object_class) &&\n ($walk_association_blacklist[this_object_class].include?('ALL') ||\n $walk_association_blacklist[this_object_class].include?(association.to_s))\n print_line($recursion_level,\n \"*** not walking: \\'#{association}\\' is in the walk_association_blacklist \" \\\n \"hash for #{this_object_class} ***\")\n else\n walk_association(object_string, association, associated_objects)\n end\n else\n print_line($recursion_level,\n \"*** Invalid $walk_association_policy: #{$walk_association_policy} ***\")\n exit MIQ_ABORT\n end\n end\n rescue NoMethodError\n print_line($recursion_level,\n \"*** #{this_object_class} association: \\'#{association}\\', gives a \" \\\n \"NoMethodError when accessed (product bug?) ***\")\n next\n end\n end\n print_line($recursion_level, \"--- end of associations ---\")\n end\n else\n print_line($recursion_level, \"--- no associations ---\")\n end\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_associations) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend", "def process_association(object, attribute, association)\n # This currently happens after translation, which converts deleted records\n # into blank records. We need to be able to prevent both from causing\n # errors when we try to create RDF objects below.\n return if association.marked_for_destruction? || association.blank?\n\n rdf_class = get_rdf_class(object, attribute)\n return if !rdf_class\n\n label = association.value\n uri = association.internal\n uri = association.value if uri.blank?\n\n begin\n vocab_object = rdf_class.from_uri(uri)\n # Support for objects which HAVE resources (AF::Base objects)\n vocab_object = vocab_object.resource if vocab_object.respond_to?(:resource)\n uri = vocab_object.rdf_subject.to_s\n rescue OregonDigital::RDF::Controlled::ControlledVocabularyError => error\n association.manual_errors.add(:value, error.message)\n return\n end\n\n association.internal = RDF::URI.new(uri)\n\n # Cache the label so show/edit work even if we have never seen this term\n # before (and don't want to refresh our internal terms all the time)\n vocab_object.set_value(RDF::SKOS.hiddenLabel, label)\n vocab_object.persist!\n end", "def format_has_many(obj, assoc)\n values = obj.send(assoc.name)\n if values.size == 1\n assoc_link(assoc, values.first)\n elsif values.present?\n simple_list(values) { |val| assoc_link(assoc, val) }\n else\n ta(:no_entry, assoc)\n end\n end", "def scaffold_associated_objects(association, object, options)\n assoc = object.send(association)\n reflection = association_reflection(association)\n reflection[:cache] || reflection[:type] == :many_to_one ? assoc : assoc.all\n end", "def scaffold_add_associated_object(association, object, associated_object)\n association_proxy = object.send(association)\n next if association_proxy.include?(associated_object)\n association_proxy << associated_object\n end", "def handle_noun_object(word, object_spec,allow_recur=MAX_ATTR_RECUR)\n\t\tobject = nil\n\t\t12.times do\n\t\t\tsemantic_counter = @dictionary.semantic_chooser(word)\n\t\t\tfreq_counter = lambda do |freq,candidate_word|\n\t\t\t\tif word.text == candidate_word.text\n\t\t\t\t\t0\n\t\t\t\telsif word.class == Noun && noun_noun_forbidden?(word, candidate_word)\n\t\t\t\t\t0\n\t\t\t\telse\n\t\t\t\t\tsemantic_counter.call(freq,candidate_word)\n\t\t\t\tend\n\t\t\tend\n\t\t\tobject = @dictionary.get_random_object(&freq_counter)\n\t\t\tnext if (object && @nouns.find { |n| n.text == object.text})\n\t\t\tbreak\n\t\tend\n\t\tunless object\n\t\t\t@conf.logger.debug \"Could not find matching object for #{word} with #{object_spec}\"\n\t\t\treturn ''\n\t\tend\n\n\t\t# resolve adjective before inflecting object\n\t\t# in order to avoid assigning first object adjective to the\n\t\t# noun attribute added to the object\n\t\tadj_text = nil\n\t\tadj_chance = @adjectives.empty? ? @conf.object_adj_chance : @conf.object_adj_chance/2\n\t\tif check_chance(adj_chance)\n\t\t\tadj_text = _handle_adjective(object, {:case=>object_spec.case})\n\t\tend\n\n\t\tform = {:case=>object_spec.case}\n\t\tform[:preposition] = object_spec.preposition if object_spec.preposition\n\t\tinflected_object = _common_handle_noun(object, form, allow_recur-1) # -1 to prevent infinite loop danger?\n\n\t\tinflected_object = adj_text + ' ' + inflected_object if adj_text && !adj_text.empty?\n\n\t\tobject_spec.preposition ?\n\t\t\t@grammar.join_preposition_object(object_spec.preposition,inflected_object) :\n\t\t\tinflected_object\n\tend", "def prepare_to_change_association(object)\n name = association_name(object)\n send(\"#{name}_will_change!\")\n end", "def _reflect_on_association(association)\n val = reflections[association].is_a?(AssociationReflection) ? reflections[association] : nil\n unless val\n # When a has_many is paired with a has_and_belongs_to_many the assocation will have a plural name\n association = association.to_s.pluralize.to_sym\n val = reflections[association].is_a?(AssociationReflection) ? reflections[association] : nil\n end\n val\n end", "def fetch_related_objects(subject,association_name,*indices)\n check_subject_and_association(subject,association_name)\n __send__(plural_association_method(subject.type,association_name),subject.rod_id,*indices)\n end", "def associate(object)\n\t\t\t\n\t\t\t # grab the class\n\t\t\t c = object.class.to_s.downcase\n\t\t\t \n # see if we have a collection of these things\n if eval(\"self.#{c}s\")\n eval \"self.#{c}s << object\"\n map_child(:child=>object) \n #if not, try to associate a singular object\n elsif eval(\"self.#{c}\")\n eval \"self.#{c}.id=object.id\"\n map_child(:child=>object)\n else\n raise \"I don't know how to associate that!\"\n\t\t end\n\t\t \n\t\t end", "def presents_many(association)\n define_method association do\n present_many(__getobj__.__send__(association))\n end\n\n association\n end", "def sub_object\n splits= @field.split('.')\n object_name = splits.first\n field_names = splits[1..-1] # all but the first\n return unless object_name && obj.respond_to?(object_name)\n object = obj.send(object_name)\n # Its a collection => invoice.items and access is done by ary index:\n # first item => [items.1.name]\n if object.nil?\n # empty relation\n @result.gsub!(@placeholder, '')\n elsif object.is_a?(Array) && ary_index = field_names.first[/\\A\\d*\\z/]\n field_names.delete_at(0) # remove entry from field_names ary\n # replace with empty string if the index does not exist or obj is empty\n @result.gsub!(@placeholder, '') unless object = object[ary_index.to_i-1]\n end\n\n # Recurse and let the referenced object do the expanding\n if object.respond_to?(:expand_placeholders)\n value = object.expand_placeholders(\"[#{field_names.join('.')}]\")\n @result.gsub!(@placeholder, value)\n end\n end", "def scaffold_add_associated_object(association, object, associated_object)\n ap = object.send(association)\n ap << associated_object unless ap.include?(associated_object)\n object.save\n end", "def walk_object(object_string, this_object)\n begin\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n $recursion_level += 1\n if $recursion_level > $max_recursion_level\n print_line($recursion_level, \"*** exceeded maximum recursion level ***\")\n $recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n print_line($recursion_level,\n \"Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}\") if $debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n print_line($recursion_level, \"Debug: this_object_class = #{this_object_class}\") if $debug\n if $object_recorder.key?(this_object_class)\n if $object_recorder[this_object_class].include?(this_object_id)\n print_line($recursion_level,\n \"Object #{this_object_class} with ID #{this_object_id} has already been printed...\")\n $recursion_level -= 1\n return\n else\n $object_recorder[this_object_class] << this_object_id\n end\n else\n $object_recorder[this_object_class] = []\n $object_recorder[this_object_class] << this_object_id\n end\n #\n # Dump out the things of interest\n #\n print_attributes(object_string, this_object)\n print_virtual_columns(object_string, this_object, this_object_class)\n print_associations(object_string, this_object, this_object_class)\n print_methods(object_string, this_object) if $print_methods\n print_tags(this_object, this_object_class) if $service_model_base_supports_taggable\n print_custom_attributes(object_string, this_object)\n \n $recursion_level -= 1\n rescue => err\n $evm.log(\"error\", \"#{$method} (walk_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n $recursion_level -= 1\n end\nend", "def awesome_mongo_mapper_association(object)\n return object.inspect unless defined?(::ActiveSupport::OrderedHash)\n return awesome_object(object) if @options[:raw]\n\n association = object.class.name.split('::').last.titleize.downcase.sub(/ association$/, '')\n association = \"embeds #{association}\" if object.embeddable?\n class_name = object.class_name\n\n \"#{colorize(association, :assoc)} #{colorize(class_name, :class)}\"\n end", "def _load_associated_objects(opts, dynamic_opts=OPTS)\n db.with_comments(:model=>model, :method_type=>:association_load, :association=>opts[:name]) do\n super\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
End of walk_association Method: print_associations Purpose: Prints the associations (if any) of the object passed to it Arguments: object_string : friendly text string name for the object this_object : the Ruby object whose associations are to be dumped this_object_class : the class of the object whose associations are to be dumped Returns: None
def print_associations(object_string, this_object, this_object_class) begin # # Only dump the associations of an MiqAeMethodService::* class # if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/ # # Print the associations of this object according to the # $walk_associations_whitelist & $walk_associations_blacklist hashes # associations = [] associated_objects = [] duplicates = [] if this_object.respond_to?(:associations) associations = Array.wrap(this_object.associations) if associations.length.zero? print_line($recursion_level, "--- no associations ---") else print_line($recursion_level, "--- associations follow ---") duplicates = associations.select{|item| associations.count(item) > 1} if duplicates.length > 0 print_line($recursion_level, "*** De-duplicating the following associations: #{duplicates.inspect} ***") end associations.uniq.sort.each do |association| begin associated_objects = Array.wrap(this_object.method_missing(:send, association)) if associated_objects.length == 0 print_line($recursion_level, "#{object_string}.#{association} (type: Association (empty))") else print_line($recursion_level, "#{object_string}.#{association} (type: Association)") # # See if we need to walk this association according to the walk_association_policy # variable, and the walk_association_{whitelist,blacklist} hashes # if $walk_association_policy == 'whitelist' if $walk_association_whitelist.has_key?(this_object_class) && ($walk_association_whitelist[this_object_class].include?('ALL') || $walk_association_whitelist[this_object_class].include?(association.to_s)) walk_association(object_string, association, associated_objects) else print_line($recursion_level, "*** not walking: \'#{association}\' isn't in the walk_association_whitelist " \ "hash for #{this_object_class} ***") end elsif $walk_association_policy == 'blacklist' if $walk_association_blacklist.has_key?(this_object_class) && ($walk_association_blacklist[this_object_class].include?('ALL') || $walk_association_blacklist[this_object_class].include?(association.to_s)) print_line($recursion_level, "*** not walking: \'#{association}\' is in the walk_association_blacklist " \ "hash for #{this_object_class} ***") else walk_association(object_string, association, associated_objects) end else print_line($recursion_level, "*** Invalid $walk_association_policy: #{$walk_association_policy} ***") exit MIQ_ABORT end end rescue NoMethodError print_line($recursion_level, "*** #{this_object_class} association: \'#{association}\', gives a " \ "NoMethodError when accessed (product bug?) ***") next end end print_line($recursion_level, "--- end of associations ---") end else print_line($recursion_level, "--- no associations ---") end end rescue => err $evm.log("error", "#{$method} (print_associations) - [#{err}]\n#{err.backtrace.join("\n")}") end end
[ "def dump_association(object_string, association, associated_objects, indent_string)\n begin\n #\n # Assemble some fake code to make it look like we're iterating though associations (plural)\n #\n number_of_associated_objects = associated_objects.length\n if is_plural?(association)\n assignment_string = \"#{object_string}.#{association}.each do |#{association.singularize}|\"\n else\n assignment_string = \"#{association} = #{object_string}.#{association}\"\n end\n log(:info, \"#{indent_string}#{@method}: #{assignment_string}\")\n associated_objects.each do |associated_object|\n associated_object_class = \"#{associated_object.method_missing(:class)}\".demodulize\n associated_object_id = associated_object.id rescue associated_object.object_id\n log(:info, \"#{indent_string}| #{@method}: (object type: #{associated_object_class}, object ID: #{associated_object_id})\")\n if is_plural?(association)\n dump_object(\"#{association.singularize}\", associated_object, indent_string)\n if number_of_associated_objects > 1\n log(:info, \"#{indent_string}#{@method}: --- next #{association.singularize} ---\")\n number_of_associated_objects -= 1\n else\n log(:info, \"#{indent_string}#{@method}: --- end of #{object_string}.#{association}.each do |#{association.singularize}| ---\")\n end\n else\n dump_object(\"#{association}\", associated_object, indent_string)\n end\n end\n rescue => err\n log(:error, \"#{@method} (dump_association) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def dump_associations(object_string, this_object, this_object_class, indent_string)\n begin\n #\n # Print the associations of this object according to the @walk_associations_whitelist & @walk_associations_blacklist hashes\n #\n object_associations = []\n associated_objects = []\n duplicates = []\n if this_object.respond_to?(:associations)\n log(:info, \"#{indent_string}#{@method}: --- associations follow ---\")\n object_associations = Array(this_object.associations)\n duplicates = object_associations.select{|item| object_associations.count(item) > 1}\n if duplicates.length > 0\n log(:info, \"#{indent_string}#{@method}: *** De-duplicating the following associations: #{duplicates.inspect} (product bug?) ***\")\n end\n object_associations.uniq.sort.each do |association|\n begin\n associated_objects = Array(this_object.send(association))\n if associated_objects.length == 0\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{association} (type: Association (empty))\")\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{association} (type: Association)\")\n #\n # See if we need to walk this association according to the @walk_association_policy variable, and the @walk_association_{whitelist,blacklist} hashes\n #\n if @walk_association_policy == :whitelist\n if @walk_association_whitelist.has_key?(this_object_class) &&\n (@walk_association_whitelist[this_object_class].include?(:ALL) || @walk_association_whitelist[this_object_class].include?(association.to_s))\n dump_association(object_string, association, associated_objects, indent_string)\n else\n log(:info, \"#{indent_string}#{@method}: *** not walking: \\'#{association}\\' isn't in the @walk_association_whitelist hash for #{this_object_class} ***\")\n end\n elsif @walk_association_policy == :blacklist\n if @walk_association_blacklist.has_key?(this_object_class) &&\n (@walk_association_blacklist[this_object_class].include?(:ALL) || @walk_association_blacklist[this_object_class].include?(association.to_s))\n log(:info, \"#{indent_string}#{@method}: *** not walking: \\'#{association}\\' is in the @walk_association_blacklist hash for #{this_object_class} ***\")\n else\n dump_association(object_string, association, associated_objects, indent_string)\n end\n else\n log(:info, \"#{indent_string}#{@method}: *** Invalid @walk_association_policy: #{@walk_association_policy} ***\")\n return\n end\n end\n rescue NoMethodError\n log(:info, \"#{indent_string}#{@method}: *** #{this_object_class} association: \\'#{association}\\', gives a NoMethodError when accessed (product bug?) ***\")\n end\n end\n log(:info, \"#{indent_string}#{@method}: --- end of associations ---\")\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no associations\")\n end\n rescue => err\n log(:error, \"#{@method} (dump_associations) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def dump_association(object_string, association, associated_objects, spaces)\n begin\n #\n # Assemble some fake code to make it look like we're iterating though associations (plural)\n #\n number_of_associated_objects = associated_objects.length\n if (association =~ /.*s$/)\n assignment_string = \"#{object_string}.#{association}.each do |#{association.chop}|\"\n else\n assignment_string = \"#{association} = #{object_string}.#{association}\"\n end\n $evm.log(\"info\", \"#{spaces}#{@method}: #{assignment_string}\")\n associated_objects.each do |associated_object|\n associated_object_class = \"#{associated_object.method_missing(:class)}\".demodulize\n associated_object_id = associated_object.id rescue associated_object.object_id\n $evm.log(\"info\", \"#{spaces}| #{@method}: (object type: #{associated_object_class}, object ID: #{associated_object_id})\")\n if (association =~ /.*s$/)\n dump_object(\"#{association.chop}\", associated_object, spaces)\n if number_of_associated_objects > 1\n $evm.log(\"info\", \"#{spaces}#{@method}: --- next #{association.chop} ---\")\n number_of_associated_objects -= 1\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: --- end of #{object_string}.#{association}.each do |#{association.chop}| ---\")\n end\n else\n dump_object(\"#{association}\", associated_object, spaces)\n end\n end\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_association) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend", "def walk_association(object_string, association, associated_objects)\n begin\n #\n # Assemble some fake code to make it look like we're iterating though associations (plural)\n #\n number_of_associated_objects = associated_objects.length\n if is_plural?(association)\n assignment_string = \"#{object_string}.#{association}.each do |#{association.singularize}|\"\n else\n assignment_string = \"#{association} = #{object_string}.#{association}\"\n end\n print_line($recursion_level, \"#{assignment_string}\")\n associated_objects.each do |associated_object|\n associated_object_class = \"#{associated_object.method_missing(:class)}\".demodulize\n associated_object_id = associated_object.id rescue associated_object.object_id\n print_line($recursion_level, \"(object type: #{associated_object_class}, object ID: #{associated_object_id})\")\n if is_plural?(association)\n walk_object(\"#{association.singularize}\", associated_object)\n if number_of_associated_objects > 1\n print_line($recursion_level,\n \"--- next #{association.singularize} ---\")\n number_of_associated_objects -= 1\n else\n print_line($recursion_level,\n \"--- end of #{object_string}.#{association}.each do |#{association.singularize}| ---\")\n end\n else\n walk_object(\"#{association}\", associated_object)\n end\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (walk_association) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend", "def dump_associations(my_object, my_object_name)\n if my_object.respond_to?(\"associations\")\n self.log(@dump_log_level, \"Begin #{my_object_name}.associations\")\n my_object.associations.sort.each { |a| self.log(:info, \"#{my_object_name} Association - #{a}\")}\n self.log(@dump_log_level, \"End #{my_object_name}.associations\")\n self.log(@dump_log_level, \"\")\n else\n self.log(@dump_log_level, \"No associations for #{my_object_name}\")\n end\n end", "def walk_object(object_string, this_object)\n begin\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n $recursion_level += 1\n if $recursion_level > $max_recursion_level\n print_line($recursion_level, \"*** exceeded maximum recursion level ***\")\n $recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n print_line($recursion_level,\n \"Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}\") if $debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n print_line($recursion_level, \"Debug: this_object_class = #{this_object_class}\") if $debug\n if $object_recorder.key?(this_object_class)\n if $object_recorder[this_object_class].include?(this_object_id)\n print_line($recursion_level,\n \"Object #{this_object_class} with ID #{this_object_id} has already been printed...\")\n $recursion_level -= 1\n return\n else\n $object_recorder[this_object_class] << this_object_id\n end\n else\n $object_recorder[this_object_class] = []\n $object_recorder[this_object_class] << this_object_id\n end\n #\n # Dump out the things of interest\n #\n print_attributes(object_string, this_object)\n print_virtual_columns(object_string, this_object, this_object_class)\n print_associations(object_string, this_object, this_object_class)\n print_methods(object_string, this_object) if $print_methods\n print_tags(this_object, this_object_class) if $service_model_base_supports_taggable\n print_custom_attributes(object_string, this_object)\n \n $recursion_level -= 1\n rescue => err\n $evm.log(\"error\", \"#{$method} (walk_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n $recursion_level -= 1\n end\nend", "def inspect_hierarchy(object_to_inspect, object_to_inspect_class)\n puts \"#{object_to_inspect} instance of \\\"#{object_to_inspect_class.name}\\\"\"\n\n print \"Hierarchy : \"\n object_to_inspect_class.ancestors.each do |ancestor|\n print \"#{ancestor} -> \"\n end\n puts\n puts \"#{Util::get_line_separator}\"\n end", "def print_attributes(object_string, this_object)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n print_line($recursion_level, \"Debug: this_object.inspected = #{this_object.inspect}\") if $debug\n if this_object.attributes.respond_to?(:keys)\n if this_object.attributes.keys.length > 0\n print_line($recursion_level, \"--- attributes follow ---\")\n this_object.attributes.keys.sort.each do |attribute_name|\n attribute_value = this_object.attributes[attribute_name]\n if attribute_name != \"options\"\n if attribute_value.is_a?(DRb::DRbObject)\n if attribute_value.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n print_line($recursion_level,\n \"#{object_string}[\\'#{attribute_name}\\'] => #{attribute_value} #{type(attribute_value)}\")\n walk_object(\"#{object_string}[\\'#{attribute_name}\\']\", attribute_value)\n else\n print_line($recursion_level,\n \"Debug: not dumping, attribute_value.method_missing(:class) = \" \\\n \"#{attribute_value.method_missing(:class)}\") if $debug\n end\n else\n begin\n attr_info = ping_attr(this_object, attribute_name)\n if attr_info[:value].nil?\n print_line($recursion_level,\n \"#{object_string}#{attr_info[:format_string]} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}#{attr_info[:format_string]} = #{attr_info[:value]} #{type(attr_info[:value])}\")\n end\n rescue ArgumentError\n if attribute_value.nil?\n print_line($recursion_level,\n \"#{object_string}.#{attribute_name} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.#{attribute_name} = #{attribute_value} #{type(attribute_value)}\")\n end\n end\n end\n else\n #\n # Option key names can be mixed symbols and strings which confuses .sort\n # Create an option_map hash that maps option_name.to_s => option_name\n #\n option_map = {}\n options = attribute_value.keys\n options.each do |option_name|\n option_map[option_name.to_s] = option_name\n end\n option_map.keys.sort.each do |option|\n if attribute_value[option_map[option]].nil?\n print_line($recursion_level,\n \"#{object_string}.options[#{str_or_sym(option_map[option])}] = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.options[#{str_or_sym(option_map[option])}] = \" \\\n \"#{attribute_value[option_map[option]]} #{type(attribute_value[option_map[option]])}\")\n end\n end\n end\n end\n print_line($recursion_level, \"--- end of attributes ---\")\n else \n print_line($recursion_level, \"--- no attributes ---\")\n end\n else\n print_line($recursion_level, \"*** attributes is not a hash ***\")\n end\n else\n print_line($recursion_level, \"--- no attributes ---\")\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend", "def dump_object(object_string, this_object, spaces)\n begin\n if @recursion_level == 0\n spaces += \" \"\n else\n spaces += \"| \"\n end\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n @recursion_level += 1\n if @recursion_level > MAX_RECURSION_LEVEL\n $evm.log(\"info\", \"#{spaces}#{@method}: Exceeded maximum recursion level\")\n @recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}}\") if @debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object_class = #{this_object_class}\") if @debug\n if @object_recorder.key?(this_object_class)\n if @object_recorder[this_object_class].include?(this_object_id)\n $evm.log(\"info\", \"#{spaces}#{@method}: Object #{this_object_class} with ID #{this_object_id} has already been dumped...\")\n @recursion_level -= 1\n return\n else\n @object_recorder[this_object_class] << this_object_id\n end\n else\n @object_recorder[this_object_class] = []\n @object_recorder[this_object_class] << this_object_id\n end\n \n $evm.log(\"info\", \"#{spaces}#{@method}: Dumping $evm.root\") if @recursion_level == 1\n #\n # Dump out the things of interest\n #\n dump_attributes(object_string, this_object, spaces)\n dump_virtual_columns(object_string, this_object, spaces)\n dump_associations(object_string, this_object, this_object_class, spaces)\n \n @recursion_level -= 1\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend", "def awesome_mongo_mapper_association(object)\n return object.inspect unless defined?(::ActiveSupport::OrderedHash)\n return awesome_object(object) if @options[:raw]\n\n association = object.class.name.split('::').last.titleize.downcase.sub(/ association$/, '')\n association = \"embeds #{association}\" if object.embeddable?\n class_name = object.class_name\n\n \"#{colorize(association, :assoc)} #{colorize(class_name, :class)}\"\n end", "def dump_object(object_string, this_object, indent_string)\n begin\n if @recursion_level == 0\n indent_string += \" \"\n else\n indent_string += \"| \"\n end\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n @recursion_level += 1\n if @recursion_level > MAX_RECURSION_LEVEL\n log(:info, \"#{indent_string}#{@method}: *** exceeded maximum recursion level ***\")\n @recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n log(:info, \"#{indent_string}#{@method}: Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}\") if @debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n log(:info, \"#{indent_string}#{@method}: Debug: this_object_class = #{this_object_class}\") if @debug\n if @object_recorder.key?(this_object_class)\n if @object_recorder[this_object_class].include?(this_object_id)\n log(:info, \"#{indent_string}#{@method}: Object #{this_object_class} with ID #{this_object_id} has already been dumped...\")\n @recursion_level -= 1\n return\n else\n @object_recorder[this_object_class] << this_object_id\n end\n else\n @object_recorder[this_object_class] = []\n @object_recorder[this_object_class] << this_object_id\n end\n\n #log(:info, \"#{indent_string}#{@method}: Dumping $evm.root\") if @recursion_level == 1\n #\n # Dump out the things of interest\n #\n dump_attributes(object_string, this_object, indent_string)\n dump_virtual_columns(object_string, this_object, this_object_class, indent_string)\n dump_associations(object_string, this_object, this_object_class, indent_string)\n dump_methods(object_string, this_object, indent_string) if @dump_methods\n\n @recursion_level -= 1\n rescue => err\n log(:error, \"#{@method} (dump_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def display object\n # stringify symbols in YAML output for better readability\n puts object.to_yaml.gsub(/^([[:blank:]]*(- )?):(?=@?\\w+: )/, '\\1')\n rescue\n require 'pp'\n pp object\n end", "def print(x, objects, printed)\n\n\tif x.class == Page\n\t\tputs \"\\t\"*(x.depth.to_i) + x.to_s\n\t\tprinted.push(x.topic)\n\t\tx.children.each{ |child|\n\t\t\tprint(child, objects, printed)\n\t\t}\n\tend\n\n\tif x.class == Symbol\n\t\ttopic_regex = /title=\"(.*?)\"/\n\t\ttopic_regex.match(x.to_s.gsub!(\" \",\"_\"))\n\t\tthis_topic = $1\n\t\t\n\t\t if objects.include?(this_topic) && !printed.include?(this_topic)\n\t\t\ti = objects.index(this_topic)\n\t\t\tnewX = objects[i]\n\t\t\tprinted.push(newX)\n\t\t\tprint(newX, objects, printed)\n\t\telse\n\t\t\tprinted.push(this_topic)\n\t\t\tputs \"\\t\"*$distance.to_i + this_topic\n\t\tend\n\n\tend\nend", "def dump_association_replicants(dumper, association)\n if reflection = self.class.reflect_on_association(association)\n objects = __send__(reflection.name)\n dumper.dump(objects)\n if reflection.macro == :has_and_belongs_to_many\n dump_has_and_belongs_to_many_replicant(dumper, reflection)\n end\n # clear to allow GC\n __send__(reflection.name).reset if __send__(reflection.name).respond_to?(:reset)\n else\n warn \"error: #{self.class}##{association} is invalid\"\n end\n end", "def dump_attributes(object_string, this_object, indent_string)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n log(:info, \"#{indent_string}#{@method}: Debug: this_object.inspected = #{this_object.inspect}\") if @debug\n this_object.attributes.sort.each do |key, value|\n if key != \"options\"\n if value.is_a?(DRb::DRbObject)\n log(:info, \"#{indent_string}#{@method}: #{object_string}[\\'#{key}\\'] => #{value} #{type(value)}\")\n dump_object(\"#{object_string}[\\'#{key}\\']\", value, indent_string)\n else\n if value.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{key} = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{key} = #{value} #{type(value)}\")\n end\n end\n else\n value.sort.each do |k,v|\n if v.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.options[:#{k}] = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.options[:#{k}] = #{v} #{type(v)}\")\n end\n end\n end\n end\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no attributes\")\n end\n rescue => err\n log(:error, \"#{@method} (dump_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def dump_attributes(object_string, this_object, spaces)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object.inspected = #{this_object.inspect}\") if @debug\n this_object.attributes.sort.each do |key, value|\n if key != \"options\"\n if value.is_a?(DRb::DRbObject)\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}[\\'#{key}\\'] => #{value} (type: #{value.class})\")\n dump_object(\"#{object_string}[\\'#{key}\\']\", value, spaces)\n else\n if value.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{key} = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{key} = #{value} (type: #{value.class})\")\n end\n end\n else\n value.sort.each do |k,v|\n if v.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.options[:#{k}] = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.options[:#{k}] = #{v} (type: #{v.class})\")\n end\n end\n end\n end\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: This object has no attributes\")\n end\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend", "def _print_obj # print_obj object\r\n obj_id = @operands[0]\r\n\r\n text = parse_zchar_sequence peek_zchar_text (zobj obj_id).name_addr\r\n @screen.print text\r\n\r\n dbg :print { text }\r\n end", "def print_object(object, method = nil)\n #logger = RAILS_DEFAULT_LOGGER\n #logger.info \"\\\"print_object speaking. I am about to print Object: \" + object.inspect + \" Method: \" + method.inspect + \". Over.\\\"\"\n unless method.present?\n if object.respond_to? :call\n begin\n object.call.to_s\n # Haml buffers may be provided in callable form, but have to be captured\n rescue Haml::Error\n # Rescue is only successful if buffer available in current scope\n print_buffer { object.call }\n end\n else\n object.to_s # Each object responds to :to_s\n end\n else\n # If the given method can be invoked on the object, the result is returned\n if method.respond_to?(:to_sym) && object.respond_to?(method)\n object.send(method.to_sym).to_s\n # If the given method can be alled with the object, the result is returned\n elsif method.respond_to? :call\n # Call method with object if it takes at most 1 required parameter\n # Arity returns -n-1 if n > 0 optional parameters exist\n if method.arity == 1 || method.arity == -1 || method.arity == -2\n method.call(object).to_s\n else\n raise ArgumentError, \"Content is not printable. Too many (or no) parameters expected in the following method: \" + method.inspect\n end\n else\n raise ArgumentError, \"Content is not printable. Provide a Proc/Method that can be called with object or a method name that can be invoked on the object. Alternatively, do not provide a method argument so that the object's :to_html, :call, or :to_s method is called. Parameters given: Object: \" + object.inspect + \" Method: \" + method.inspect\n end\n end\n end", "def print_association\n operation = OperationType.find(operation_type.id)\n feedback_array = operation.get(:feedback)\n if feedback_array\n show do\n title \"This is printing because debug is on\"\n note \"#{feedback_array}\"\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
End of print_associations Method: print_methods Purpose: Prints the methods (if any) of the object class passed to it Arguments: object_string : friendly text string name for the object this_object : the Ruby object whose methods are to be dumped Returns: None
def print_methods(object_string, this_object) begin # # Only dump the methods of an MiqAeMethodService::* class # if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/ print_line($recursion_level, "Class of remote DRb::DRbObject is: #{this_object.method_missing(:class)}") if $debug # # Get the instance methods of the class and convert to string # if this_object.method_missing(:class).respond_to?(:instance_methods) instance_methods = this_object.method_missing(:class).instance_methods.map { |x| x.to_s } # # Now we need to remove method names that we're not interested in... # # ...attribute names... # attributes = [] if this_object.respond_to?(:attributes) if this_object.attributes.respond_to? :each this_object.attributes.each do |key, value| attributes << key end end end attributes << "attributes" $evm.log("info", "Removing attributes: #{instance_methods & attributes}") if $debug instance_methods -= attributes # # ...association names... # associations = [] if this_object.respond_to?(:associations) associations = Array.wrap(this_object.associations) end associations << "associations" $evm.log("info", "Removing associations: #{instance_methods & associations}") if $debug instance_methods -= associations # # ...virtual column names... # virtual_column_names = [] virtual_column_names = this_object.method_missing(:virtual_column_names) virtual_column_names << "virtual_column_names" $evm.log("info", "Removing virtual_column_names: #{instance_methods & virtual_column_names}") if $debug instance_methods -= virtual_column_names # # ... MiqAeServiceModelBase methods ... # $evm.log("info", "Removing MiqAeServiceModelBase methods: " \ "#{instance_methods & $service_mode_base_instance_methods}") if $debug instance_methods -= $service_mode_base_instance_methods # # Add in the base methods as it's useful to show that they can be used with this object # instance_methods += ['inspect', 'inspect_all', 'reload', 'model_suffix'] if this_object.respond_to?(:taggable?) if this_object.taggable? instance_methods += ['tags', 'tag_assign', 'tag_unassign', 'tagged_with?'] end else instance_methods += ['tags', 'tag_assign', 'tag_unassign', 'tagged_with?'] end # # and finally dump out the list # if instance_methods.length.zero? print_line($recursion_level, "--- no methods ---") else print_line($recursion_level, "--- methods follow ---") instance_methods.sort.each do |instance_method| print_line($recursion_level, "#{object_string}.#{instance_method}") end print_line($recursion_level, "--- end of methods ---") end else print_line($recursion_level, "--- no methods ---") end end rescue => err $evm.log("error", "#{$method} (print_methods) - [#{err}]\n#{err.backtrace.join("\n")}") end end
[ "def print_associations(object_string, this_object, this_object_class)\n begin\n #\n # Only dump the associations of an MiqAeMethodService::* class\n #\n if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n #\n # Print the associations of this object according to the\n # $walk_associations_whitelist & $walk_associations_blacklist hashes\n #\n associations = []\n associated_objects = []\n duplicates = []\n if this_object.respond_to?(:associations)\n associations = Array.wrap(this_object.associations)\n if associations.length.zero?\n print_line($recursion_level, \"--- no associations ---\")\n else\n print_line($recursion_level, \"--- associations follow ---\")\n duplicates = associations.select{|item| associations.count(item) > 1}\n if duplicates.length > 0\n print_line($recursion_level,\n \"*** De-duplicating the following associations: #{duplicates.inspect} ***\")\n end\n associations.uniq.sort.each do |association|\n begin\n associated_objects = Array.wrap(this_object.method_missing(:send, association))\n if associated_objects.length == 0\n print_line($recursion_level,\n \"#{object_string}.#{association} (type: Association (empty))\")\n else\n print_line($recursion_level, \"#{object_string}.#{association} (type: Association)\")\n #\n # See if we need to walk this association according to the walk_association_policy\n # variable, and the walk_association_{whitelist,blacklist} hashes\n #\n if $walk_association_policy == 'whitelist'\n if $walk_association_whitelist.has_key?(this_object_class) &&\n ($walk_association_whitelist[this_object_class].include?('ALL') ||\n $walk_association_whitelist[this_object_class].include?(association.to_s))\n walk_association(object_string, association, associated_objects)\n else\n print_line($recursion_level,\n \"*** not walking: \\'#{association}\\' isn't in the walk_association_whitelist \" \\\n \"hash for #{this_object_class} ***\")\n end\n elsif $walk_association_policy == 'blacklist'\n if $walk_association_blacklist.has_key?(this_object_class) &&\n ($walk_association_blacklist[this_object_class].include?('ALL') ||\n $walk_association_blacklist[this_object_class].include?(association.to_s))\n print_line($recursion_level,\n \"*** not walking: \\'#{association}\\' is in the walk_association_blacklist \" \\\n \"hash for #{this_object_class} ***\")\n else\n walk_association(object_string, association, associated_objects)\n end\n else\n print_line($recursion_level,\n \"*** Invalid $walk_association_policy: #{$walk_association_policy} ***\")\n exit MIQ_ABORT\n end\n end\n rescue NoMethodError\n print_line($recursion_level,\n \"*** #{this_object_class} association: \\'#{association}\\', gives a \" \\\n \"NoMethodError when accessed (product bug?) ***\")\n next\n end\n end\n print_line($recursion_level, \"--- end of associations ---\")\n end\n else\n print_line($recursion_level, \"--- no associations ---\")\n end\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_associations) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend", "def print_object(object, method = nil)\n #logger = RAILS_DEFAULT_LOGGER\n #logger.info \"\\\"print_object speaking. I am about to print Object: \" + object.inspect + \" Method: \" + method.inspect + \". Over.\\\"\"\n unless method.present?\n if object.respond_to? :call\n begin\n object.call.to_s\n # Haml buffers may be provided in callable form, but have to be captured\n rescue Haml::Error\n # Rescue is only successful if buffer available in current scope\n print_buffer { object.call }\n end\n else\n object.to_s # Each object responds to :to_s\n end\n else\n # If the given method can be invoked on the object, the result is returned\n if method.respond_to?(:to_sym) && object.respond_to?(method)\n object.send(method.to_sym).to_s\n # If the given method can be alled with the object, the result is returned\n elsif method.respond_to? :call\n # Call method with object if it takes at most 1 required parameter\n # Arity returns -n-1 if n > 0 optional parameters exist\n if method.arity == 1 || method.arity == -1 || method.arity == -2\n method.call(object).to_s\n else\n raise ArgumentError, \"Content is not printable. Too many (or no) parameters expected in the following method: \" + method.inspect\n end\n else\n raise ArgumentError, \"Content is not printable. Provide a Proc/Method that can be called with object or a method name that can be invoked on the object. Alternatively, do not provide a method argument so that the object's :to_html, :call, or :to_s method is called. Parameters given: Object: \" + object.inspect + \" Method: \" + method.inspect\n end\n end\n end", "def dump_methods(object_string, this_object, indent_string)\n begin\n unless object_string == \"$evm.root\"\n log(:info, \"#{indent_string}#{@method}: Class of remote DRb::DRbObject is: #{this_object.method_missing(:class)}\") if @debug\n #\n # Get the instance methods of the class and convert to string\n #\n if this_object.method_missing(:class).respond_to?(:instance_methods)\n instance_methods = this_object.method_missing(:class).instance_methods.map { |x| x.to_s }\n #\n # Now we need to remove method names that we're not interested in...\n #\n # ...attribute names...\n #\n attributes = []\n if this_object.respond_to?(:attributes)\n this_object.attributes.sort.each do |key, value|\n attributes << key\n end\n end\n attributes << \"attributes\"\n log(:info, \"Removing attributes: #{instance_methods & attributes}\") if @debug\n instance_methods = instance_methods - attributes\n #\n # ...association names...\n #\n associations = []\n if this_object.respond_to?(:associations)\n associations = Array(this_object.associations)\n end\n associations << \"associations\"\n log(:info, \"Removing associations: #{instance_methods & associations}\") if @debug\n instance_methods = instance_methods - associations\n #\n # ...virtual column names...\n #\n virtual_column_names = []\n virtual_column_names = this_object.method_missing(:virtual_column_names)\n virtual_column_names << \"virtual_column_names\"\n log(:info, \"Removing virtual_column_names: #{instance_methods & virtual_column_names}\") if @debug\n instance_methods = instance_methods - virtual_column_names\n #\n # ... MiqAeServiceModelBase methods ...\n #\n log(:info, \"Removing MiqAeServiceModelBase methods: #{instance_methods & @service_mode_base_instance_methods}\") if @debug\n instance_methods = instance_methods - @service_mode_base_instance_methods\n #\n # and finally dump out the remainder\n #\n log(:info, \"#{indent_string}#{@method}: --- methods follow ---\")\n instance_methods.sort.each do | instance_method |\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{instance_method}\")\n end\n log(:info, \"#{indent_string}#{@method}: --- end of methods ---\")\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no instance methods\")\n end\n end\n rescue => err\n log(:error, \"#{@method} (dump_methods) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def print_methods(obj, *options)\n methods = obj.methods\n methods -= Object.methods unless options.include? :more\n filter = options.select {|opt| opt.kind_of? Regexp}.first\n methods = methods.select {|name| name =~ filter} if filter\n\n data = methods.sort.collect do |name|\n method = obj.method(name)\n if method.arity == 0\n args = \"()\"\n elsif method.arity > 0\n n = method.arity\n args = \"(#{(1..n).collect {|i| \"arg#{i}\"}.join(\", \")})\"\n elsif method.arity < 0\n n = -method.arity\n args = \"(#{(1..n).collect {|i| \"arg#{i}\"}.join(\", \")}, ...)\"\n end\n klass = $1 if method.inspect =~ /Method: (.*?)#/\n [name, args, klass]\n end\n max_name = data.collect {|item| item[0].size}.max\n max_args = data.collect {|item| item[1].size}.max\n data.each do |item| \n print \" #{ANSI_BOLD}#{item[0].to_s.rjust(max_name)}#{ANSI_RESET}\"\n print \"#{ANSI_GRAY}#{item[1].ljust(max_args)}#{ANSI_RESET}\"\n print \" #{ANSI_LGRAY}#{item[2]}#{ANSI_RESET}\\n\"\n end\n data.size\n end", "def print_attributes(object_string, this_object)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n print_line($recursion_level, \"Debug: this_object.inspected = #{this_object.inspect}\") if $debug\n if this_object.attributes.respond_to?(:keys)\n if this_object.attributes.keys.length > 0\n print_line($recursion_level, \"--- attributes follow ---\")\n this_object.attributes.keys.sort.each do |attribute_name|\n attribute_value = this_object.attributes[attribute_name]\n if attribute_name != \"options\"\n if attribute_value.is_a?(DRb::DRbObject)\n if attribute_value.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n print_line($recursion_level,\n \"#{object_string}[\\'#{attribute_name}\\'] => #{attribute_value} #{type(attribute_value)}\")\n walk_object(\"#{object_string}[\\'#{attribute_name}\\']\", attribute_value)\n else\n print_line($recursion_level,\n \"Debug: not dumping, attribute_value.method_missing(:class) = \" \\\n \"#{attribute_value.method_missing(:class)}\") if $debug\n end\n else\n begin\n attr_info = ping_attr(this_object, attribute_name)\n if attr_info[:value].nil?\n print_line($recursion_level,\n \"#{object_string}#{attr_info[:format_string]} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}#{attr_info[:format_string]} = #{attr_info[:value]} #{type(attr_info[:value])}\")\n end\n rescue ArgumentError\n if attribute_value.nil?\n print_line($recursion_level,\n \"#{object_string}.#{attribute_name} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.#{attribute_name} = #{attribute_value} #{type(attribute_value)}\")\n end\n end\n end\n else\n #\n # Option key names can be mixed symbols and strings which confuses .sort\n # Create an option_map hash that maps option_name.to_s => option_name\n #\n option_map = {}\n options = attribute_value.keys\n options.each do |option_name|\n option_map[option_name.to_s] = option_name\n end\n option_map.keys.sort.each do |option|\n if attribute_value[option_map[option]].nil?\n print_line($recursion_level,\n \"#{object_string}.options[#{str_or_sym(option_map[option])}] = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.options[#{str_or_sym(option_map[option])}] = \" \\\n \"#{attribute_value[option_map[option]]} #{type(attribute_value[option_map[option]])}\")\n end\n end\n end\n end\n print_line($recursion_level, \"--- end of attributes ---\")\n else \n print_line($recursion_level, \"--- no attributes ---\")\n end\n else\n print_line($recursion_level, \"*** attributes is not a hash ***\")\n end\n else\n print_line($recursion_level, \"--- no attributes ---\")\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend", "def walk_object(object_string, this_object)\n begin\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n $recursion_level += 1\n if $recursion_level > $max_recursion_level\n print_line($recursion_level, \"*** exceeded maximum recursion level ***\")\n $recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n print_line($recursion_level,\n \"Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}\") if $debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n print_line($recursion_level, \"Debug: this_object_class = #{this_object_class}\") if $debug\n if $object_recorder.key?(this_object_class)\n if $object_recorder[this_object_class].include?(this_object_id)\n print_line($recursion_level,\n \"Object #{this_object_class} with ID #{this_object_id} has already been printed...\")\n $recursion_level -= 1\n return\n else\n $object_recorder[this_object_class] << this_object_id\n end\n else\n $object_recorder[this_object_class] = []\n $object_recorder[this_object_class] << this_object_id\n end\n #\n # Dump out the things of interest\n #\n print_attributes(object_string, this_object)\n print_virtual_columns(object_string, this_object, this_object_class)\n print_associations(object_string, this_object, this_object_class)\n print_methods(object_string, this_object) if $print_methods\n print_tags(this_object, this_object_class) if $service_model_base_supports_taggable\n print_custom_attributes(object_string, this_object)\n \n $recursion_level -= 1\n rescue => err\n $evm.log(\"error\", \"#{$method} (walk_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n $recursion_level -= 1\n end\nend", "def _print_obj # print_obj object\r\n obj_id = @operands[0]\r\n\r\n text = parse_zchar_sequence peek_zchar_text (zobj obj_id).name_addr\r\n @screen.print text\r\n\r\n dbg :print { text }\r\n end", "def dump_associations(object_string, this_object, this_object_class, indent_string)\n begin\n #\n # Print the associations of this object according to the @walk_associations_whitelist & @walk_associations_blacklist hashes\n #\n object_associations = []\n associated_objects = []\n duplicates = []\n if this_object.respond_to?(:associations)\n log(:info, \"#{indent_string}#{@method}: --- associations follow ---\")\n object_associations = Array(this_object.associations)\n duplicates = object_associations.select{|item| object_associations.count(item) > 1}\n if duplicates.length > 0\n log(:info, \"#{indent_string}#{@method}: *** De-duplicating the following associations: #{duplicates.inspect} (product bug?) ***\")\n end\n object_associations.uniq.sort.each do |association|\n begin\n associated_objects = Array(this_object.send(association))\n if associated_objects.length == 0\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{association} (type: Association (empty))\")\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{association} (type: Association)\")\n #\n # See if we need to walk this association according to the @walk_association_policy variable, and the @walk_association_{whitelist,blacklist} hashes\n #\n if @walk_association_policy == :whitelist\n if @walk_association_whitelist.has_key?(this_object_class) &&\n (@walk_association_whitelist[this_object_class].include?(:ALL) || @walk_association_whitelist[this_object_class].include?(association.to_s))\n dump_association(object_string, association, associated_objects, indent_string)\n else\n log(:info, \"#{indent_string}#{@method}: *** not walking: \\'#{association}\\' isn't in the @walk_association_whitelist hash for #{this_object_class} ***\")\n end\n elsif @walk_association_policy == :blacklist\n if @walk_association_blacklist.has_key?(this_object_class) &&\n (@walk_association_blacklist[this_object_class].include?(:ALL) || @walk_association_blacklist[this_object_class].include?(association.to_s))\n log(:info, \"#{indent_string}#{@method}: *** not walking: \\'#{association}\\' is in the @walk_association_blacklist hash for #{this_object_class} ***\")\n else\n dump_association(object_string, association, associated_objects, indent_string)\n end\n else\n log(:info, \"#{indent_string}#{@method}: *** Invalid @walk_association_policy: #{@walk_association_policy} ***\")\n return\n end\n end\n rescue NoMethodError\n log(:info, \"#{indent_string}#{@method}: *** #{this_object_class} association: \\'#{association}\\', gives a NoMethodError when accessed (product bug?) ***\")\n end\n end\n log(:info, \"#{indent_string}#{@method}: --- end of associations ---\")\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no associations\")\n end\n rescue => err\n log(:error, \"#{@method} (dump_associations) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def inspect_public_methods(object_to_inspect)\n puts \"- Public methods :\"\n object_to_inspect.public_methods(false).each do |method|\n puts \"\\t- #{method} \"\n end\n puts \"#{Util::get_line_separator}\"\n end", "def dump_object(object_string, this_object, indent_string)\n begin\n if @recursion_level == 0\n indent_string += \" \"\n else\n indent_string += \"| \"\n end\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n @recursion_level += 1\n if @recursion_level > MAX_RECURSION_LEVEL\n log(:info, \"#{indent_string}#{@method}: *** exceeded maximum recursion level ***\")\n @recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n log(:info, \"#{indent_string}#{@method}: Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}\") if @debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n log(:info, \"#{indent_string}#{@method}: Debug: this_object_class = #{this_object_class}\") if @debug\n if @object_recorder.key?(this_object_class)\n if @object_recorder[this_object_class].include?(this_object_id)\n log(:info, \"#{indent_string}#{@method}: Object #{this_object_class} with ID #{this_object_id} has already been dumped...\")\n @recursion_level -= 1\n return\n else\n @object_recorder[this_object_class] << this_object_id\n end\n else\n @object_recorder[this_object_class] = []\n @object_recorder[this_object_class] << this_object_id\n end\n\n #log(:info, \"#{indent_string}#{@method}: Dumping $evm.root\") if @recursion_level == 1\n #\n # Dump out the things of interest\n #\n dump_attributes(object_string, this_object, indent_string)\n dump_virtual_columns(object_string, this_object, this_object_class, indent_string)\n dump_associations(object_string, this_object, this_object_class, indent_string)\n dump_methods(object_string, this_object, indent_string) if @dump_methods\n\n @recursion_level -= 1\n rescue => err\n log(:error, \"#{@method} (dump_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def dump_object(object_string, this_object, spaces)\n begin\n if @recursion_level == 0\n spaces += \" \"\n else\n spaces += \"| \"\n end\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n @recursion_level += 1\n if @recursion_level > MAX_RECURSION_LEVEL\n $evm.log(\"info\", \"#{spaces}#{@method}: Exceeded maximum recursion level\")\n @recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}}\") if @debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object_class = #{this_object_class}\") if @debug\n if @object_recorder.key?(this_object_class)\n if @object_recorder[this_object_class].include?(this_object_id)\n $evm.log(\"info\", \"#{spaces}#{@method}: Object #{this_object_class} with ID #{this_object_id} has already been dumped...\")\n @recursion_level -= 1\n return\n else\n @object_recorder[this_object_class] << this_object_id\n end\n else\n @object_recorder[this_object_class] = []\n @object_recorder[this_object_class] << this_object_id\n end\n \n $evm.log(\"info\", \"#{spaces}#{@method}: Dumping $evm.root\") if @recursion_level == 1\n #\n # Dump out the things of interest\n #\n dump_attributes(object_string, this_object, spaces)\n dump_virtual_columns(object_string, this_object, spaces)\n dump_associations(object_string, this_object, this_object_class, spaces)\n \n @recursion_level -= 1\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend", "def dump_attributes(object_string, this_object, spaces)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object.inspected = #{this_object.inspect}\") if @debug\n this_object.attributes.sort.each do |key, value|\n if key != \"options\"\n if value.is_a?(DRb::DRbObject)\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}[\\'#{key}\\'] => #{value} (type: #{value.class})\")\n dump_object(\"#{object_string}[\\'#{key}\\']\", value, spaces)\n else\n if value.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{key} = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{key} = #{value} (type: #{value.class})\")\n end\n end\n else\n value.sort.each do |k,v|\n if v.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.options[:#{k}] = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.options[:#{k}] = #{v} (type: #{v.class})\")\n end\n end\n end\n end\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: This object has no attributes\")\n end\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend", "def print_custom_attributes(object_string, this_object)\n begin\n if this_object.respond_to?(:custom_keys)\n custom_attribute_keys = Array.wrap(this_object.custom_keys)\n if custom_attribute_keys.length.zero?\n print_line($recursion_level, \"--- no custom attributes ---\")\n else\n print_line($recursion_level, \"--- custom attributes follow ---\")\n custom_attribute_keys.sort.each do |custom_attribute_key|\n custom_attribute_value = this_object.custom_get(custom_attribute_key)\n print_line($recursion_level, \"#{object_string}.custom_get(\\'#{custom_attribute_key}\\') = \\'#{custom_attribute_value}\\'\")\n end\n print_line($recursion_level, \"--- end of custom attributes ---\")\n end\n else\n print_line($recursion_level, \"--- object does not support custom attributes ---\")\n end \n rescue => err\n $evm.log(\"error\", \"#{$method} (print_custom_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend", "def dump_attributes(object_string, this_object, indent_string)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n log(:info, \"#{indent_string}#{@method}: Debug: this_object.inspected = #{this_object.inspect}\") if @debug\n this_object.attributes.sort.each do |key, value|\n if key != \"options\"\n if value.is_a?(DRb::DRbObject)\n log(:info, \"#{indent_string}#{@method}: #{object_string}[\\'#{key}\\'] => #{value} #{type(value)}\")\n dump_object(\"#{object_string}[\\'#{key}\\']\", value, indent_string)\n else\n if value.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{key} = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{key} = #{value} #{type(value)}\")\n end\n end\n else\n value.sort.each do |k,v|\n if v.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.options[:#{k}] = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.options[:#{k}] = #{v} #{type(v)}\")\n end\n end\n end\n end\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no attributes\")\n end\n rescue => err\n log(:error, \"#{@method} (dump_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def print_virtual_columns(object_string, this_object, this_object_class)\n begin\n #\n # Only dump the virtual columns of an MiqAeMethodService::* class\n #\n if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n #\n # Print the virtual columns of this object \n #\n virtual_column_names = []\n if this_object.respond_to?(:virtual_column_names)\n virtual_column_names = Array.wrap(this_object.virtual_column_names)\n if virtual_column_names.length.zero?\n print_line($recursion_level, \"--- no virtual columns ---\")\n else\n print_line($recursion_level, \"--- virtual columns follow ---\")\n virtual_column_names.sort.each do |virtual_column_name|\n begin\n virtual_column_value = this_object.method_missing(:send, virtual_column_name)\n if virtual_column_value.nil?\n print_line($recursion_level,\n \"#{object_string}.#{virtual_column_name} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.#{virtual_column_name} = \" \\\n \"#{virtual_column_value} #{type(virtual_column_value)}\")\n end\n rescue NoMethodError\n print_line($recursion_level,\n \"*** #{this_object_class} virtual column: \\'#{virtual_column_name}\\' \" \\\n \"gives a NoMethodError when accessed (product bug?) ***\")\n end\n end\n print_line($recursion_level, \"--- end of virtual columns ---\")\n end\n else\n print_line($recursion_level, \"--- no virtual columns ---\")\n end\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_virtual_columns) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend", "def inspect_private_methods(object_to_inspect)\n puts \"- Private methods :\"\n object_to_inspect.private_methods(false).each do |method|\n puts \"\\t- #{method}\"\n end\n puts \"#{Util::get_line_separator}\"\n end", "def print_methods\n m = \"----- #{self} (methods) -----\\n\"\n m << methods.sort.join(\"\\n\")\n puts m\n m\n end", "def dump_method_list(objectOrClass)\n puts \"[Debug] method list (#{objectOrClass.class}) #{objectOrClass.inspect} = #{(objectOrClass.methods - Object.methods - Class.methods).sort.to_s}\"\nend", "def inspectObject (theObject)\n puts theObject.inspect\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
End of print_methods Method: print_tags Purpose: Prints the tags (if any) of the object class passed to it Arguments: this_object : the Ruby object whose tags are to be printed this_object_class : the class of the object whose associations are to be dumped Returns: None
def print_tags(this_object, this_object_class) begin if this_object.respond_to?(:taggable?) if this_object.taggable? tags = Array.wrap(this_object.tags) if tags.length.zero? print_line($recursion_level, "--- no tags ---") else print_line($recursion_level, "--- tags follow ---") tags.sort.each do |tag| print_line($recursion_level, "#{tag}") end print_line($recursion_level, "--- end of tags ---") end else print_line($recursion_level, "--- object is not taggable ---") end else print_line($recursion_level, "--- no tags, or object is not taggable ---") end rescue NoMethodError print_line($recursion_level, "*** #{this_object_class} gives a NoMethodError when the :tags method is accessed (product bug?) ***") rescue => err $evm.log("error", "#{$method} (print_tags) - [#{err}]\n#{err.backtrace.join("\n")}") end end
[ "def print_associations(object_string, this_object, this_object_class)\n begin\n #\n # Only dump the associations of an MiqAeMethodService::* class\n #\n if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n #\n # Print the associations of this object according to the\n # $walk_associations_whitelist & $walk_associations_blacklist hashes\n #\n associations = []\n associated_objects = []\n duplicates = []\n if this_object.respond_to?(:associations)\n associations = Array.wrap(this_object.associations)\n if associations.length.zero?\n print_line($recursion_level, \"--- no associations ---\")\n else\n print_line($recursion_level, \"--- associations follow ---\")\n duplicates = associations.select{|item| associations.count(item) > 1}\n if duplicates.length > 0\n print_line($recursion_level,\n \"*** De-duplicating the following associations: #{duplicates.inspect} ***\")\n end\n associations.uniq.sort.each do |association|\n begin\n associated_objects = Array.wrap(this_object.method_missing(:send, association))\n if associated_objects.length == 0\n print_line($recursion_level,\n \"#{object_string}.#{association} (type: Association (empty))\")\n else\n print_line($recursion_level, \"#{object_string}.#{association} (type: Association)\")\n #\n # See if we need to walk this association according to the walk_association_policy\n # variable, and the walk_association_{whitelist,blacklist} hashes\n #\n if $walk_association_policy == 'whitelist'\n if $walk_association_whitelist.has_key?(this_object_class) &&\n ($walk_association_whitelist[this_object_class].include?('ALL') ||\n $walk_association_whitelist[this_object_class].include?(association.to_s))\n walk_association(object_string, association, associated_objects)\n else\n print_line($recursion_level,\n \"*** not walking: \\'#{association}\\' isn't in the walk_association_whitelist \" \\\n \"hash for #{this_object_class} ***\")\n end\n elsif $walk_association_policy == 'blacklist'\n if $walk_association_blacklist.has_key?(this_object_class) &&\n ($walk_association_blacklist[this_object_class].include?('ALL') ||\n $walk_association_blacklist[this_object_class].include?(association.to_s))\n print_line($recursion_level,\n \"*** not walking: \\'#{association}\\' is in the walk_association_blacklist \" \\\n \"hash for #{this_object_class} ***\")\n else\n walk_association(object_string, association, associated_objects)\n end\n else\n print_line($recursion_level,\n \"*** Invalid $walk_association_policy: #{$walk_association_policy} ***\")\n exit MIQ_ABORT\n end\n end\n rescue NoMethodError\n print_line($recursion_level,\n \"*** #{this_object_class} association: \\'#{association}\\', gives a \" \\\n \"NoMethodError when accessed (product bug?) ***\")\n next\n end\n end\n print_line($recursion_level, \"--- end of associations ---\")\n end\n else\n print_line($recursion_level, \"--- no associations ---\")\n end\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_associations) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend", "def print\r\n tags.each do |tag|\r\n puts \"#{@@tag_titles[tag]} -> #{value(tag)}\"\r\n end\r\n end", "def print_object(object, method = nil)\n #logger = RAILS_DEFAULT_LOGGER\n #logger.info \"\\\"print_object speaking. I am about to print Object: \" + object.inspect + \" Method: \" + method.inspect + \". Over.\\\"\"\n unless method.present?\n if object.respond_to? :call\n begin\n object.call.to_s\n # Haml buffers may be provided in callable form, but have to be captured\n rescue Haml::Error\n # Rescue is only successful if buffer available in current scope\n print_buffer { object.call }\n end\n else\n object.to_s # Each object responds to :to_s\n end\n else\n # If the given method can be invoked on the object, the result is returned\n if method.respond_to?(:to_sym) && object.respond_to?(method)\n object.send(method.to_sym).to_s\n # If the given method can be alled with the object, the result is returned\n elsif method.respond_to? :call\n # Call method with object if it takes at most 1 required parameter\n # Arity returns -n-1 if n > 0 optional parameters exist\n if method.arity == 1 || method.arity == -1 || method.arity == -2\n method.call(object).to_s\n else\n raise ArgumentError, \"Content is not printable. Too many (or no) parameters expected in the following method: \" + method.inspect\n end\n else\n raise ArgumentError, \"Content is not printable. Provide a Proc/Method that can be called with object or a method name that can be invoked on the object. Alternatively, do not provide a method argument so that the object's :to_html, :call, or :to_s method is called. Parameters given: Object: \" + object.inspect + \" Method: \" + method.inspect\n end\n end\n end", "def walk_object(object_string, this_object)\n begin\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n $recursion_level += 1\n if $recursion_level > $max_recursion_level\n print_line($recursion_level, \"*** exceeded maximum recursion level ***\")\n $recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n print_line($recursion_level,\n \"Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}\") if $debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n print_line($recursion_level, \"Debug: this_object_class = #{this_object_class}\") if $debug\n if $object_recorder.key?(this_object_class)\n if $object_recorder[this_object_class].include?(this_object_id)\n print_line($recursion_level,\n \"Object #{this_object_class} with ID #{this_object_id} has already been printed...\")\n $recursion_level -= 1\n return\n else\n $object_recorder[this_object_class] << this_object_id\n end\n else\n $object_recorder[this_object_class] = []\n $object_recorder[this_object_class] << this_object_id\n end\n #\n # Dump out the things of interest\n #\n print_attributes(object_string, this_object)\n print_virtual_columns(object_string, this_object, this_object_class)\n print_associations(object_string, this_object, this_object_class)\n print_methods(object_string, this_object) if $print_methods\n print_tags(this_object, this_object_class) if $service_model_base_supports_taggable\n print_custom_attributes(object_string, this_object)\n \n $recursion_level -= 1\n rescue => err\n $evm.log(\"error\", \"#{$method} (walk_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n $recursion_level -= 1\n end\nend", "def dump_object(object_string, this_object, indent_string)\n begin\n if @recursion_level == 0\n indent_string += \" \"\n else\n indent_string += \"| \"\n end\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n @recursion_level += 1\n if @recursion_level > MAX_RECURSION_LEVEL\n log(:info, \"#{indent_string}#{@method}: *** exceeded maximum recursion level ***\")\n @recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n log(:info, \"#{indent_string}#{@method}: Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}\") if @debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n log(:info, \"#{indent_string}#{@method}: Debug: this_object_class = #{this_object_class}\") if @debug\n if @object_recorder.key?(this_object_class)\n if @object_recorder[this_object_class].include?(this_object_id)\n log(:info, \"#{indent_string}#{@method}: Object #{this_object_class} with ID #{this_object_id} has already been dumped...\")\n @recursion_level -= 1\n return\n else\n @object_recorder[this_object_class] << this_object_id\n end\n else\n @object_recorder[this_object_class] = []\n @object_recorder[this_object_class] << this_object_id\n end\n\n #log(:info, \"#{indent_string}#{@method}: Dumping $evm.root\") if @recursion_level == 1\n #\n # Dump out the things of interest\n #\n dump_attributes(object_string, this_object, indent_string)\n dump_virtual_columns(object_string, this_object, this_object_class, indent_string)\n dump_associations(object_string, this_object, this_object_class, indent_string)\n dump_methods(object_string, this_object, indent_string) if @dump_methods\n\n @recursion_level -= 1\n rescue => err\n log(:error, \"#{@method} (dump_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def print(x, objects, printed)\n\n\tif x.class == Page\n\t\tputs \"\\t\"*(x.depth.to_i) + x.to_s\n\t\tprinted.push(x.topic)\n\t\tx.children.each{ |child|\n\t\t\tprint(child, objects, printed)\n\t\t}\n\tend\n\n\tif x.class == Symbol\n\t\ttopic_regex = /title=\"(.*?)\"/\n\t\ttopic_regex.match(x.to_s.gsub!(\" \",\"_\"))\n\t\tthis_topic = $1\n\t\t\n\t\t if objects.include?(this_topic) && !printed.include?(this_topic)\n\t\t\ti = objects.index(this_topic)\n\t\t\tnewX = objects[i]\n\t\t\tprinted.push(newX)\n\t\t\tprint(newX, objects, printed)\n\t\telse\n\t\t\tprinted.push(this_topic)\n\t\t\tputs \"\\t\"*$distance.to_i + this_topic\n\t\tend\n\n\tend\nend", "def inspect_hierarchy(object_to_inspect, object_to_inspect_class)\n puts \"#{object_to_inspect} instance of \\\"#{object_to_inspect_class.name}\\\"\"\n\n print \"Hierarchy : \"\n object_to_inspect_class.ancestors.each do |ancestor|\n print \"#{ancestor} -> \"\n end\n puts\n puts \"#{Util::get_line_separator}\"\n end", "def _print_obj # print_obj object\r\n obj_id = @operands[0]\r\n\r\n text = parse_zchar_sequence peek_zchar_text (zobj obj_id).name_addr\r\n @screen.print text\r\n\r\n dbg :print { text }\r\n end", "def p object\n TetCore.break_after_print\n TetCore.real_p(object)\nend", "def print_objects(array)\n if array[0].class == Product\n print_products(array)\n elsif array[0].class == Category\n print_categories(array)\n else\n print_locations(array)\n end\n end", "def print_attributes(object_string, this_object)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n print_line($recursion_level, \"Debug: this_object.inspected = #{this_object.inspect}\") if $debug\n if this_object.attributes.respond_to?(:keys)\n if this_object.attributes.keys.length > 0\n print_line($recursion_level, \"--- attributes follow ---\")\n this_object.attributes.keys.sort.each do |attribute_name|\n attribute_value = this_object.attributes[attribute_name]\n if attribute_name != \"options\"\n if attribute_value.is_a?(DRb::DRbObject)\n if attribute_value.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n print_line($recursion_level,\n \"#{object_string}[\\'#{attribute_name}\\'] => #{attribute_value} #{type(attribute_value)}\")\n walk_object(\"#{object_string}[\\'#{attribute_name}\\']\", attribute_value)\n else\n print_line($recursion_level,\n \"Debug: not dumping, attribute_value.method_missing(:class) = \" \\\n \"#{attribute_value.method_missing(:class)}\") if $debug\n end\n else\n begin\n attr_info = ping_attr(this_object, attribute_name)\n if attr_info[:value].nil?\n print_line($recursion_level,\n \"#{object_string}#{attr_info[:format_string]} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}#{attr_info[:format_string]} = #{attr_info[:value]} #{type(attr_info[:value])}\")\n end\n rescue ArgumentError\n if attribute_value.nil?\n print_line($recursion_level,\n \"#{object_string}.#{attribute_name} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.#{attribute_name} = #{attribute_value} #{type(attribute_value)}\")\n end\n end\n end\n else\n #\n # Option key names can be mixed symbols and strings which confuses .sort\n # Create an option_map hash that maps option_name.to_s => option_name\n #\n option_map = {}\n options = attribute_value.keys\n options.each do |option_name|\n option_map[option_name.to_s] = option_name\n end\n option_map.keys.sort.each do |option|\n if attribute_value[option_map[option]].nil?\n print_line($recursion_level,\n \"#{object_string}.options[#{str_or_sym(option_map[option])}] = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.options[#{str_or_sym(option_map[option])}] = \" \\\n \"#{attribute_value[option_map[option]]} #{type(attribute_value[option_map[option]])}\")\n end\n end\n end\n end\n print_line($recursion_level, \"--- end of attributes ---\")\n else \n print_line($recursion_level, \"--- no attributes ---\")\n end\n else\n print_line($recursion_level, \"*** attributes is not a hash ***\")\n end\n else\n print_line($recursion_level, \"--- no attributes ---\")\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend", "def dump_associations(object_string, this_object, this_object_class, indent_string)\n begin\n #\n # Print the associations of this object according to the @walk_associations_whitelist & @walk_associations_blacklist hashes\n #\n object_associations = []\n associated_objects = []\n duplicates = []\n if this_object.respond_to?(:associations)\n log(:info, \"#{indent_string}#{@method}: --- associations follow ---\")\n object_associations = Array(this_object.associations)\n duplicates = object_associations.select{|item| object_associations.count(item) > 1}\n if duplicates.length > 0\n log(:info, \"#{indent_string}#{@method}: *** De-duplicating the following associations: #{duplicates.inspect} (product bug?) ***\")\n end\n object_associations.uniq.sort.each do |association|\n begin\n associated_objects = Array(this_object.send(association))\n if associated_objects.length == 0\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{association} (type: Association (empty))\")\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{association} (type: Association)\")\n #\n # See if we need to walk this association according to the @walk_association_policy variable, and the @walk_association_{whitelist,blacklist} hashes\n #\n if @walk_association_policy == :whitelist\n if @walk_association_whitelist.has_key?(this_object_class) &&\n (@walk_association_whitelist[this_object_class].include?(:ALL) || @walk_association_whitelist[this_object_class].include?(association.to_s))\n dump_association(object_string, association, associated_objects, indent_string)\n else\n log(:info, \"#{indent_string}#{@method}: *** not walking: \\'#{association}\\' isn't in the @walk_association_whitelist hash for #{this_object_class} ***\")\n end\n elsif @walk_association_policy == :blacklist\n if @walk_association_blacklist.has_key?(this_object_class) &&\n (@walk_association_blacklist[this_object_class].include?(:ALL) || @walk_association_blacklist[this_object_class].include?(association.to_s))\n log(:info, \"#{indent_string}#{@method}: *** not walking: \\'#{association}\\' is in the @walk_association_blacklist hash for #{this_object_class} ***\")\n else\n dump_association(object_string, association, associated_objects, indent_string)\n end\n else\n log(:info, \"#{indent_string}#{@method}: *** Invalid @walk_association_policy: #{@walk_association_policy} ***\")\n return\n end\n end\n rescue NoMethodError\n log(:info, \"#{indent_string}#{@method}: *** #{this_object_class} association: \\'#{association}\\', gives a NoMethodError when accessed (product bug?) ***\")\n end\n end\n log(:info, \"#{indent_string}#{@method}: --- end of associations ---\")\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no associations\")\n end\n rescue => err\n log(:error, \"#{@method} (dump_associations) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def print_class_and_superclasses(object)\n object.class.ancestors.each do |klass|\n puts klass\n end\nend", "def print(*obj)\n each_ios_and_stdout(*obj, &:print)\n nil\n end", "def dump_object(object_string, this_object, spaces)\n begin\n if @recursion_level == 0\n spaces += \" \"\n else\n spaces += \"| \"\n end\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n @recursion_level += 1\n if @recursion_level > MAX_RECURSION_LEVEL\n $evm.log(\"info\", \"#{spaces}#{@method}: Exceeded maximum recursion level\")\n @recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}}\") if @debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object_class = #{this_object_class}\") if @debug\n if @object_recorder.key?(this_object_class)\n if @object_recorder[this_object_class].include?(this_object_id)\n $evm.log(\"info\", \"#{spaces}#{@method}: Object #{this_object_class} with ID #{this_object_id} has already been dumped...\")\n @recursion_level -= 1\n return\n else\n @object_recorder[this_object_class] << this_object_id\n end\n else\n @object_recorder[this_object_class] = []\n @object_recorder[this_object_class] << this_object_id\n end\n \n $evm.log(\"info\", \"#{spaces}#{@method}: Dumping $evm.root\") if @recursion_level == 1\n #\n # Dump out the things of interest\n #\n dump_attributes(object_string, this_object, spaces)\n dump_virtual_columns(object_string, this_object, spaces)\n dump_associations(object_string, this_object, this_object_class, spaces)\n \n @recursion_level -= 1\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend", "def print_self\n puts self\nend", "def puts object = ''\n TetCore.break_after_print\n TetCore.real_puts(object)\nend", "def inspectObject (theObject)\n puts theObject.inspect\nend", "def print_methods(object_string, this_object)\n begin\n #\n # Only dump the methods of an MiqAeMethodService::* class\n #\n if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n print_line($recursion_level,\n \"Class of remote DRb::DRbObject is: #{this_object.method_missing(:class)}\") if $debug\n #\n # Get the instance methods of the class and convert to string\n #\n if this_object.method_missing(:class).respond_to?(:instance_methods)\n instance_methods = this_object.method_missing(:class).instance_methods.map { |x| x.to_s }\n #\n # Now we need to remove method names that we're not interested in...\n #\n # ...attribute names...\n #\n attributes = []\n if this_object.respond_to?(:attributes)\n if this_object.attributes.respond_to? :each\n this_object.attributes.each do |key, value|\n attributes << key\n end\n end\n end\n attributes << \"attributes\"\n $evm.log(\"info\", \"Removing attributes: #{instance_methods & attributes}\") if $debug\n instance_methods -= attributes\n #\n # ...association names...\n #\n associations = []\n if this_object.respond_to?(:associations)\n associations = Array.wrap(this_object.associations)\n end\n associations << \"associations\"\n $evm.log(\"info\", \"Removing associations: #{instance_methods & associations}\") if $debug\n instance_methods -= associations\n #\n # ...virtual column names...\n #\n virtual_column_names = []\n virtual_column_names = this_object.method_missing(:virtual_column_names)\n virtual_column_names << \"virtual_column_names\"\n $evm.log(\"info\", \"Removing virtual_column_names: #{instance_methods & virtual_column_names}\") if $debug\n instance_methods -= virtual_column_names\n #\n # ... MiqAeServiceModelBase methods ...\n #\n $evm.log(\"info\", \"Removing MiqAeServiceModelBase methods: \" \\\n \"#{instance_methods & $service_mode_base_instance_methods}\") if $debug\n instance_methods -= $service_mode_base_instance_methods\n #\n # Add in the base methods as it's useful to show that they can be used with this object\n #\n instance_methods += ['inspect', 'inspect_all', 'reload', 'model_suffix']\n if this_object.respond_to?(:taggable?)\n if this_object.taggable?\n instance_methods += ['tags', 'tag_assign', 'tag_unassign', 'tagged_with?']\n end\n else\n instance_methods += ['tags', 'tag_assign', 'tag_unassign', 'tagged_with?']\n end\n #\n # and finally dump out the list\n #\n if instance_methods.length.zero?\n print_line($recursion_level, \"--- no methods ---\")\n else\n print_line($recursion_level, \"--- methods follow ---\")\n instance_methods.sort.each do |instance_method|\n print_line($recursion_level, \"#{object_string}.#{instance_method}\")\n end\n print_line($recursion_level, \"--- end of methods ---\")\n end\n else\n print_line($recursion_level, \"--- no methods ---\")\n end\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_methods) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
End of print_tags Method: print_custom_attributes Purpose: Prints the custom attributes (if any) of the object class passed to it Arguments: object_string : friendly text string name for the object this_object : the Ruby object whose tags are to be printed Returns: None
def print_custom_attributes(object_string, this_object) begin if this_object.respond_to?(:custom_keys) custom_attribute_keys = Array.wrap(this_object.custom_keys) if custom_attribute_keys.length.zero? print_line($recursion_level, "--- no custom attributes ---") else print_line($recursion_level, "--- custom attributes follow ---") custom_attribute_keys.sort.each do |custom_attribute_key| custom_attribute_value = this_object.custom_get(custom_attribute_key) print_line($recursion_level, "#{object_string}.custom_get(\'#{custom_attribute_key}\') = \'#{custom_attribute_value}\'") end print_line($recursion_level, "--- end of custom attributes ---") end else print_line($recursion_level, "--- object does not support custom attributes ---") end rescue => err $evm.log("error", "#{$method} (print_custom_attributes) - [#{err}]\n#{err.backtrace.join("\n")}") end end
[ "def dump_attributes(object_string, this_object, indent_string)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n log(:info, \"#{indent_string}#{@method}: Debug: this_object.inspected = #{this_object.inspect}\") if @debug\n this_object.attributes.sort.each do |key, value|\n if key != \"options\"\n if value.is_a?(DRb::DRbObject)\n log(:info, \"#{indent_string}#{@method}: #{object_string}[\\'#{key}\\'] => #{value} #{type(value)}\")\n dump_object(\"#{object_string}[\\'#{key}\\']\", value, indent_string)\n else\n if value.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{key} = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{key} = #{value} #{type(value)}\")\n end\n end\n else\n value.sort.each do |k,v|\n if v.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.options[:#{k}] = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.options[:#{k}] = #{v} #{type(v)}\")\n end\n end\n end\n end\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no attributes\")\n end\n rescue => err\n log(:error, \"#{@method} (dump_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def print_attributes(object_string, this_object)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n print_line($recursion_level, \"Debug: this_object.inspected = #{this_object.inspect}\") if $debug\n if this_object.attributes.respond_to?(:keys)\n if this_object.attributes.keys.length > 0\n print_line($recursion_level, \"--- attributes follow ---\")\n this_object.attributes.keys.sort.each do |attribute_name|\n attribute_value = this_object.attributes[attribute_name]\n if attribute_name != \"options\"\n if attribute_value.is_a?(DRb::DRbObject)\n if attribute_value.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n print_line($recursion_level,\n \"#{object_string}[\\'#{attribute_name}\\'] => #{attribute_value} #{type(attribute_value)}\")\n walk_object(\"#{object_string}[\\'#{attribute_name}\\']\", attribute_value)\n else\n print_line($recursion_level,\n \"Debug: not dumping, attribute_value.method_missing(:class) = \" \\\n \"#{attribute_value.method_missing(:class)}\") if $debug\n end\n else\n begin\n attr_info = ping_attr(this_object, attribute_name)\n if attr_info[:value].nil?\n print_line($recursion_level,\n \"#{object_string}#{attr_info[:format_string]} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}#{attr_info[:format_string]} = #{attr_info[:value]} #{type(attr_info[:value])}\")\n end\n rescue ArgumentError\n if attribute_value.nil?\n print_line($recursion_level,\n \"#{object_string}.#{attribute_name} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.#{attribute_name} = #{attribute_value} #{type(attribute_value)}\")\n end\n end\n end\n else\n #\n # Option key names can be mixed symbols and strings which confuses .sort\n # Create an option_map hash that maps option_name.to_s => option_name\n #\n option_map = {}\n options = attribute_value.keys\n options.each do |option_name|\n option_map[option_name.to_s] = option_name\n end\n option_map.keys.sort.each do |option|\n if attribute_value[option_map[option]].nil?\n print_line($recursion_level,\n \"#{object_string}.options[#{str_or_sym(option_map[option])}] = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.options[#{str_or_sym(option_map[option])}] = \" \\\n \"#{attribute_value[option_map[option]]} #{type(attribute_value[option_map[option]])}\")\n end\n end\n end\n end\n print_line($recursion_level, \"--- end of attributes ---\")\n else \n print_line($recursion_level, \"--- no attributes ---\")\n end\n else\n print_line($recursion_level, \"*** attributes is not a hash ***\")\n end\n else\n print_line($recursion_level, \"--- no attributes ---\")\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend", "def dump_attributes(object_string, this_object, spaces)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object.inspected = #{this_object.inspect}\") if @debug\n this_object.attributes.sort.each do |key, value|\n if key != \"options\"\n if value.is_a?(DRb::DRbObject)\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}[\\'#{key}\\'] => #{value} (type: #{value.class})\")\n dump_object(\"#{object_string}[\\'#{key}\\']\", value, spaces)\n else\n if value.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{key} = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{key} = #{value} (type: #{value.class})\")\n end\n end\n else\n value.sort.each do |k,v|\n if v.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.options[:#{k}] = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.options[:#{k}] = #{v} (type: #{v.class})\")\n end\n end\n end\n end\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: This object has no attributes\")\n end\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend", "def dump_attributes(my_object, my_object_name)\n if my_object.respond_to?(\"attributes\")\n self.log(@dump_log_level, \"Begin #{my_object_name}.attributes\")\n my_object.attributes.sort.each { |k, v| self.log(:info, \"#{my_object_name} Attribute - #{k}: #{v}\")}\n self.log(@dump_log_level, \"End #{my_object_name}.attributes\")\n self.log(@dump_log_level, \"\")\n else\n self.log(@dump_log_level, \"No attributes for #{my_object_name}\")\n end\n end", "def inspect_object_attributs(object_to_inspect)\n puts \"- Instance attributs :\"\n object_to_inspect.instance_variables.each do |attribute|\n value = object_to_inspect.instance_eval attribute.to_s\n puts \"\\t- Name : #{attribute}\"\n puts \"\\t\\t- Type : #{value.class}\"\n puts \"\\t\\t- Value : #{value.inspect}\"\n end\n puts \"#{Util::get_line_separator}\"\n end", "def print_attribute(*) end", "def dump_info(my_object, my_object_name)\n self.dump_attributes(my_object, my_object_name)\n self.dump_associations(my_object, my_object_name)\n self.dump_virtual_columns(my_object, my_object_name)\n end", "def print_attrs(obj, point=\"*\", splitter=\":\", endline=\"\\n\")\n result = \"\"\n if obj.is_a?(Hash)\n obj.each do |arg, value|\n result += \"#{point} #{arg}#{splitter} \"\n result += case value\n when Hash\n \"#{endline}#{print_attrs(value, point[0,1]+point, splitter, endline)}\"\n when Array\n \"#{value.join(\", \")}#{endline}\"\n else\n \"#{value}#{endline}\"\n end\n end\n end\n return result\n end", "def dump_virtual_columns(object_string, this_object, spaces)\n begin\n #\n # Print the virtual columns of this object \n #\n if this_object.respond_to?(:virtual_column_names)\n $evm.log(\"info\", \"#{spaces}#{@method}: --- virtual columns follow ---\")\n this_object.virtual_column_names.sort.each do |virtual_column_name|\n virtual_column_value = this_object.send(virtual_column_name)\n if virtual_column_value.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{virtual_column_name} = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{virtual_column_name} = #{virtual_column_value} (type: #{virtual_column_value.class})\")\n end\n end\n $evm.log(\"info\", \"#{spaces}#{@method}: --- end of virtual columns ---\")\n end\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_virtual_columns) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend", "def _print_obj # print_obj object\r\n obj_id = @operands[0]\r\n\r\n text = parse_zchar_sequence peek_zchar_text (zobj obj_id).name_addr\r\n @screen.print text\r\n\r\n dbg :print { text }\r\n end", "def print_attributes\n @attributes.each{|attribute, value| puts \"#{attribute}: #{value}\"}\n end", "def dump_virtual_columns(object_string, this_object, this_object_class, indent_string)\n begin\n #\n # Print the virtual columns of this object\n #\n if this_object.respond_to?(:virtual_column_names)\n log(:info, \"#{indent_string}#{@method}: --- virtual columns follow ---\")\n this_object.virtual_column_names.sort.each do |virtual_column_name|\n begin\n virtual_column_value = this_object.send(virtual_column_name)\n if virtual_column_value.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{virtual_column_name} = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{virtual_column_name} = #{virtual_column_value} #{type(virtual_column_value)}\")\n end\n rescue NoMethodError\n log(:info, \"#{indent_string}#{@method}: *** #{this_object_class} virtual column: \\'#{virtual_column_name}\\' gives a NoMethodError when accessed (product bug?) ***\")\n end\n end\n log(:info, \"#{indent_string}#{@method}: --- end of virtual columns ---\")\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no virtual columns\")\n end\n rescue => err\n log(:error, \"#{@method} (dump_virtual_columns) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def inspectObject (theObject)\n puts theObject.inspect\nend", "def print_tags(this_object, this_object_class)\n begin\n if this_object.respond_to?(:taggable?)\n if this_object.taggable?\n tags = Array.wrap(this_object.tags)\n if tags.length.zero?\n print_line($recursion_level, \"--- no tags ---\")\n else\n print_line($recursion_level, \"--- tags follow ---\")\n tags.sort.each do |tag|\n print_line($recursion_level, \"#{tag}\")\n end\n print_line($recursion_level, \"--- end of tags ---\")\n end\n else\n print_line($recursion_level, \"--- object is not taggable ---\")\n end\n else\n print_line($recursion_level, \"--- no tags, or object is not taggable ---\")\n end\n \n rescue NoMethodError\n print_line($recursion_level,\n \"*** #{this_object_class} gives a NoMethodError when the :tags method is accessed (product bug?) ***\")\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_tags) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend", "def display object\n # stringify symbols in YAML output for better readability\n puts object.to_yaml.gsub(/^([[:blank:]]*(- )?):(?=@?\\w+: )/, '\\1')\n rescue\n require 'pp'\n pp object\n end", "def custom_inspect(object, *ivars_to_skip)\n variables = (object.instance_variables - ivars_to_skip).\n map { |var| \"#{var}=#{object.instance_variable_get(var).inspect}\" }.\n join(', ')\n \"<#{object.class}: #{variables}>\"\n end", "def dump( object, indent = \"DUMP: \" )\n indent(indent) do\n print(object)\n end\n end", "def printAttrtable(string: nil)\n raise \"printAttrtable expects a string. Missing string: 'text'\" unless string\n printGds2Record(type: 'ATTRTABLE', data: string)\n end", "def render_attrs(obj, *attrs)\n attrs.collect do |a| \n labeled_attr(obj, a)\n end.join(\"\\n\").html_safe\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
End of print_custom_attributes Method: walk_object Purpose: Prints the details of the object passed to it Arguments: indent_level : the numeric value to use to indicate output indent (represents recursion depth) object_string : friendly text string name for the object this_object : the Ruby object to be dumped Returns: None
def walk_object(object_string, this_object) begin # # Make sure that we don't exceed our maximum recursion level # $recursion_level += 1 if $recursion_level > $max_recursion_level print_line($recursion_level, "*** exceeded maximum recursion level ***") $recursion_level -= 1 return end # # Make sure we haven't dumped this object already (some data structure links are cyclical) # this_object_id = this_object.id.to_s rescue this_object.object_id.to_s print_line($recursion_level, "Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}") if $debug this_object_class = "#{this_object.method_missing(:class)}".demodulize print_line($recursion_level, "Debug: this_object_class = #{this_object_class}") if $debug if $object_recorder.key?(this_object_class) if $object_recorder[this_object_class].include?(this_object_id) print_line($recursion_level, "Object #{this_object_class} with ID #{this_object_id} has already been printed...") $recursion_level -= 1 return else $object_recorder[this_object_class] << this_object_id end else $object_recorder[this_object_class] = [] $object_recorder[this_object_class] << this_object_id end # # Dump out the things of interest # print_attributes(object_string, this_object) print_virtual_columns(object_string, this_object, this_object_class) print_associations(object_string, this_object, this_object_class) print_methods(object_string, this_object) if $print_methods print_tags(this_object, this_object_class) if $service_model_base_supports_taggable print_custom_attributes(object_string, this_object) $recursion_level -= 1 rescue => err $evm.log("error", "#{$method} (walk_object) - [#{err}]\n#{err.backtrace.join("\n")}") $recursion_level -= 1 end end
[ "def print_custom_attributes(object_string, this_object)\n begin\n if this_object.respond_to?(:custom_keys)\n custom_attribute_keys = Array.wrap(this_object.custom_keys)\n if custom_attribute_keys.length.zero?\n print_line($recursion_level, \"--- no custom attributes ---\")\n else\n print_line($recursion_level, \"--- custom attributes follow ---\")\n custom_attribute_keys.sort.each do |custom_attribute_key|\n custom_attribute_value = this_object.custom_get(custom_attribute_key)\n print_line($recursion_level, \"#{object_string}.custom_get(\\'#{custom_attribute_key}\\') = \\'#{custom_attribute_value}\\'\")\n end\n print_line($recursion_level, \"--- end of custom attributes ---\")\n end\n else\n print_line($recursion_level, \"--- object does not support custom attributes ---\")\n end \n rescue => err\n $evm.log(\"error\", \"#{$method} (print_custom_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend", "def dump_attributes(object_string, this_object, indent_string)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n log(:info, \"#{indent_string}#{@method}: Debug: this_object.inspected = #{this_object.inspect}\") if @debug\n this_object.attributes.sort.each do |key, value|\n if key != \"options\"\n if value.is_a?(DRb::DRbObject)\n log(:info, \"#{indent_string}#{@method}: #{object_string}[\\'#{key}\\'] => #{value} #{type(value)}\")\n dump_object(\"#{object_string}[\\'#{key}\\']\", value, indent_string)\n else\n if value.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{key} = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{key} = #{value} #{type(value)}\")\n end\n end\n else\n value.sort.each do |k,v|\n if v.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.options[:#{k}] = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.options[:#{k}] = #{v} #{type(v)}\")\n end\n end\n end\n end\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no attributes\")\n end\n rescue => err\n log(:error, \"#{@method} (dump_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def print_attributes(object_string, this_object)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n print_line($recursion_level, \"Debug: this_object.inspected = #{this_object.inspect}\") if $debug\n if this_object.attributes.respond_to?(:keys)\n if this_object.attributes.keys.length > 0\n print_line($recursion_level, \"--- attributes follow ---\")\n this_object.attributes.keys.sort.each do |attribute_name|\n attribute_value = this_object.attributes[attribute_name]\n if attribute_name != \"options\"\n if attribute_value.is_a?(DRb::DRbObject)\n if attribute_value.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n print_line($recursion_level,\n \"#{object_string}[\\'#{attribute_name}\\'] => #{attribute_value} #{type(attribute_value)}\")\n walk_object(\"#{object_string}[\\'#{attribute_name}\\']\", attribute_value)\n else\n print_line($recursion_level,\n \"Debug: not dumping, attribute_value.method_missing(:class) = \" \\\n \"#{attribute_value.method_missing(:class)}\") if $debug\n end\n else\n begin\n attr_info = ping_attr(this_object, attribute_name)\n if attr_info[:value].nil?\n print_line($recursion_level,\n \"#{object_string}#{attr_info[:format_string]} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}#{attr_info[:format_string]} = #{attr_info[:value]} #{type(attr_info[:value])}\")\n end\n rescue ArgumentError\n if attribute_value.nil?\n print_line($recursion_level,\n \"#{object_string}.#{attribute_name} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.#{attribute_name} = #{attribute_value} #{type(attribute_value)}\")\n end\n end\n end\n else\n #\n # Option key names can be mixed symbols and strings which confuses .sort\n # Create an option_map hash that maps option_name.to_s => option_name\n #\n option_map = {}\n options = attribute_value.keys\n options.each do |option_name|\n option_map[option_name.to_s] = option_name\n end\n option_map.keys.sort.each do |option|\n if attribute_value[option_map[option]].nil?\n print_line($recursion_level,\n \"#{object_string}.options[#{str_or_sym(option_map[option])}] = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.options[#{str_or_sym(option_map[option])}] = \" \\\n \"#{attribute_value[option_map[option]]} #{type(attribute_value[option_map[option]])}\")\n end\n end\n end\n end\n print_line($recursion_level, \"--- end of attributes ---\")\n else \n print_line($recursion_level, \"--- no attributes ---\")\n end\n else\n print_line($recursion_level, \"*** attributes is not a hash ***\")\n end\n else\n print_line($recursion_level, \"--- no attributes ---\")\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend", "def dump_object(object_string, this_object, indent_string)\n begin\n if @recursion_level == 0\n indent_string += \" \"\n else\n indent_string += \"| \"\n end\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n @recursion_level += 1\n if @recursion_level > MAX_RECURSION_LEVEL\n log(:info, \"#{indent_string}#{@method}: *** exceeded maximum recursion level ***\")\n @recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n log(:info, \"#{indent_string}#{@method}: Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}\") if @debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n log(:info, \"#{indent_string}#{@method}: Debug: this_object_class = #{this_object_class}\") if @debug\n if @object_recorder.key?(this_object_class)\n if @object_recorder[this_object_class].include?(this_object_id)\n log(:info, \"#{indent_string}#{@method}: Object #{this_object_class} with ID #{this_object_id} has already been dumped...\")\n @recursion_level -= 1\n return\n else\n @object_recorder[this_object_class] << this_object_id\n end\n else\n @object_recorder[this_object_class] = []\n @object_recorder[this_object_class] << this_object_id\n end\n\n #log(:info, \"#{indent_string}#{@method}: Dumping $evm.root\") if @recursion_level == 1\n #\n # Dump out the things of interest\n #\n dump_attributes(object_string, this_object, indent_string)\n dump_virtual_columns(object_string, this_object, this_object_class, indent_string)\n dump_associations(object_string, this_object, this_object_class, indent_string)\n dump_methods(object_string, this_object, indent_string) if @dump_methods\n\n @recursion_level -= 1\n rescue => err\n log(:error, \"#{@method} (dump_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end", "def dump( object, indent = \"DUMP: \" )\n indent(indent) do\n print(object)\n end\n end", "def dump_attributes(object_string, this_object, spaces)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object.inspected = #{this_object.inspect}\") if @debug\n this_object.attributes.sort.each do |key, value|\n if key != \"options\"\n if value.is_a?(DRb::DRbObject)\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}[\\'#{key}\\'] => #{value} (type: #{value.class})\")\n dump_object(\"#{object_string}[\\'#{key}\\']\", value, spaces)\n else\n if value.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{key} = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{key} = #{value} (type: #{value.class})\")\n end\n end\n else\n value.sort.each do |k,v|\n if v.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.options[:#{k}] = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.options[:#{k}] = #{v} (type: #{v.class})\")\n end\n end\n end\n end\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: This object has no attributes\")\n end\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend", "def dump_object(object_string, this_object, spaces)\n begin\n if @recursion_level == 0\n spaces += \" \"\n else\n spaces += \"| \"\n end\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n @recursion_level += 1\n if @recursion_level > MAX_RECURSION_LEVEL\n $evm.log(\"info\", \"#{spaces}#{@method}: Exceeded maximum recursion level\")\n @recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}}\") if @debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object_class = #{this_object_class}\") if @debug\n if @object_recorder.key?(this_object_class)\n if @object_recorder[this_object_class].include?(this_object_id)\n $evm.log(\"info\", \"#{spaces}#{@method}: Object #{this_object_class} with ID #{this_object_id} has already been dumped...\")\n @recursion_level -= 1\n return\n else\n @object_recorder[this_object_class] << this_object_id\n end\n else\n @object_recorder[this_object_class] = []\n @object_recorder[this_object_class] << this_object_id\n end\n \n $evm.log(\"info\", \"#{spaces}#{@method}: Dumping $evm.root\") if @recursion_level == 1\n #\n # Dump out the things of interest\n #\n dump_attributes(object_string, this_object, spaces)\n dump_virtual_columns(object_string, this_object, spaces)\n dump_associations(object_string, this_object, this_object_class, spaces)\n \n @recursion_level -= 1\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend", "def inspectObject (theObject)\n puts theObject.inspect\nend", "def _print_obj # print_obj object\r\n obj_id = @operands[0]\r\n\r\n text = parse_zchar_sequence peek_zchar_text (zobj obj_id).name_addr\r\n @screen.print text\r\n\r\n dbg :print { text }\r\n end", "def dump_attributes(my_object, my_object_name)\n if my_object.respond_to?(\"attributes\")\n self.log(@dump_log_level, \"Begin #{my_object_name}.attributes\")\n my_object.attributes.sort.each { |k, v| self.log(:info, \"#{my_object_name} Attribute - #{k}: #{v}\")}\n self.log(@dump_log_level, \"End #{my_object_name}.attributes\")\n self.log(@dump_log_level, \"\")\n else\n self.log(@dump_log_level, \"No attributes for #{my_object_name}\")\n end\n end", "def dump_info(my_object, my_object_name)\n self.dump_attributes(my_object, my_object_name)\n self.dump_associations(my_object, my_object_name)\n self.dump_virtual_columns(my_object, my_object_name)\n end", "def inspect_object_attributs(object_to_inspect)\n puts \"- Instance attributs :\"\n object_to_inspect.instance_variables.each do |attribute|\n value = object_to_inspect.instance_eval attribute.to_s\n puts \"\\t- Name : #{attribute}\"\n puts \"\\t\\t- Type : #{value.class}\"\n puts \"\\t\\t- Value : #{value.inspect}\"\n end\n puts \"#{Util::get_line_separator}\"\n end", "def pretty(object)\n PP.pp(object, out)\n end", "def print_automation_objects(indent_level, hierarchy)\n case hierarchy.position\n when 'root'\n print_line(indent_level, \"#{hierarchy.obj_name} ($evm.root)\")\n when 'parent'\n print_line(indent_level, \"#{hierarchy.obj_name} ($evm.parent)\")\n when 'object'\n print_line(indent_level, \"#{hierarchy.obj_name} ($evm.object)\")\n else\n print_line(indent_level, \"#{hierarchy.obj_name}\")\n end\n indent_level += 1\n hierarchy.children.each do |child|\n print_automation_objects(indent_level, child)\n end\nend", "def app_pretty_print(obj)\r\n pp obj\r\n end", "def inspect_hierarchy(object_to_inspect, object_to_inspect_class)\n puts \"#{object_to_inspect} instance of \\\"#{object_to_inspect_class.name}\\\"\"\n\n print \"Hierarchy : \"\n object_to_inspect_class.ancestors.each do |ancestor|\n print \"#{ancestor} -> \"\n end\n puts\n puts \"#{Util::get_line_separator}\"\n end", "def pp(obj)\n id = obj.object_id\n\n if check_inspect_key(id)\n group {obj.pretty_print_cycle self}\n return\n end\n\n begin\n push_inspect_key(id)\n group {obj.pretty_print self}\n ensure\n pop_inspect_key(id) unless PP.sharing_detection\n end\n end", "def print_object(object, method = nil)\n #logger = RAILS_DEFAULT_LOGGER\n #logger.info \"\\\"print_object speaking. I am about to print Object: \" + object.inspect + \" Method: \" + method.inspect + \". Over.\\\"\"\n unless method.present?\n if object.respond_to? :call\n begin\n object.call.to_s\n # Haml buffers may be provided in callable form, but have to be captured\n rescue Haml::Error\n # Rescue is only successful if buffer available in current scope\n print_buffer { object.call }\n end\n else\n object.to_s # Each object responds to :to_s\n end\n else\n # If the given method can be invoked on the object, the result is returned\n if method.respond_to?(:to_sym) && object.respond_to?(method)\n object.send(method.to_sym).to_s\n # If the given method can be alled with the object, the result is returned\n elsif method.respond_to? :call\n # Call method with object if it takes at most 1 required parameter\n # Arity returns -n-1 if n > 0 optional parameters exist\n if method.arity == 1 || method.arity == -1 || method.arity == -2\n method.call(object).to_s\n else\n raise ArgumentError, \"Content is not printable. Too many (or no) parameters expected in the following method: \" + method.inspect\n end\n else\n raise ArgumentError, \"Content is not printable. Provide a Proc/Method that can be called with object or a method name that can be invoked on the object. Alternatively, do not provide a method argument so that the object's :to_html, :call, or :to_s method is called. Parameters given: Object: \" + object.inspect + \" Method: \" + method.inspect\n end\n end\n end", "def dump_virtual_columns(object_string, this_object, spaces)\n begin\n #\n # Print the virtual columns of this object \n #\n if this_object.respond_to?(:virtual_column_names)\n $evm.log(\"info\", \"#{spaces}#{@method}: --- virtual columns follow ---\")\n this_object.virtual_column_names.sort.each do |virtual_column_name|\n virtual_column_value = this_object.send(virtual_column_name)\n if virtual_column_value.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{virtual_column_name} = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{virtual_column_name} = #{virtual_column_value} (type: #{virtual_column_value.class})\")\n end\n end\n $evm.log(\"info\", \"#{spaces}#{@method}: --- end of virtual columns ---\")\n end\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_virtual_columns) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the "official" name for the 7600B form, comprised of the GTC number, the order number , and the mod number, both padded to 4 digits and all separated by dashes.
def name "#{gtc_number}-#{name_str(order_number)}-#{name_str(mod_number)}" end
[ "def name\n \"#{gtc_number}-0000-#{mod_number.to_s.rjust(4, '0')}\"\n end", "def generate_name_with_digit (digit)\n char_array = ('a'..'z').to_a + ('0'..'9').to_a + ['_'] # char_array.length is 37\n\n quotient = digit\n queue = []\n while true do\n queue.push quotient % N_CHAR\n quotient = (quotient / N_CHAR).round - 1\n if quotient <= -1\n break\n end\n end\n\n name = ''\n while queue.any? do\n name = name + char_array[queue.pop]\n end\n name\n end", "def pcb_name\n \"#{self.pcb_prefix}-#{self.pcb_number}-#{self.pcb_dash_number}\"\n end", "def design_name\n\n if 1 == 2 # self.part_number_id == 0\n design_name = self.prefix.pcb_mnemonic + self.number\n design_name += self.revision.name if self.revision && self.revision_id > 0\n \n case self.entry_type\n when 'dot_rev'\n design_name += self.numeric_revision.to_s if self.numeric_revision > 0\n when 'date_code'\n design_name += self.numeric_revision.to_s if self.numeric_revision && self.numeric_revision > 0\n design_name += '_eco'\n design_name += self.eco_number\n end\n \n \"#{design_name} (\" + \n self.prefix.pcb_number(self.number,\n self.revision.name,\n self.numeric_revision) + ')'\n else\n self.pcb_number\n end\n \n end", "def long_name\n n = name\n n += \" (\" if version.present? || language.present?\n n += \"rev#{ version }\" if version.present?\n n += \"-\" if version.present? && language.present?\n n += \"#{ language.upcase }\" if language.present?\n n += \")\" if version.present? || language.present?\n n\n end", "def make_name\n @instruction_count += 1\n\n name_numbers = (0..9).to_a.sample(3)\n name_letters = (\"A\"..\"Z\").to_a.sample(2)\n\n (name_letters + name_numbers).join\n\n end", "def generate_fake_jack_id_label(building)\n charset = (0..9)\n \"#{building.short_name}-#{generate_random_string(2, charset)}-#{generate_random_string(2, charset)}-#{generate_random_string(3,charset)}\"\nend", "def homework_number\n \"#{homework_phone_prefix}-#{rand(8..9)}#{FFaker.numerify('##-##-##')}\"\n end", "def efnGen()\n\t\tclassIdentifier = (@mailClasses.index(@mailClass) + 1).to_s.rjust(2, '0')\n\t\treturn \"92750#{@mid}#{classIdentifier}#{rand(999999).to_s.rjust(6, '0')}\"\n\tend", "def pcb_display_name\n name = self.pcb_name\n name += ' ' + self.pcb_revision if self.pcb_revision.size > 0\n name\n end", "def generate_name(prefix, adjuster)\n \"#{Date.today.strftime(\"%Y-%m-%d\")}_#{prefix}.#{adjuster}\"\nend", "def pcba_name\n \"#{self.pcba_prefix}-#{self.pcba_number}-#{self.pcba_dash_number}\"\n end", "def pnemonic_based_name\n \n base_name = self.board.name + self.revision.name\n \n if self.dot_rev? && self.numeric_revision?\n base_name += self.numeric_revision.to_s\n end\n \n base_name\n \n \n end", "def south_african_pty_ltd_registration_number\n generate(:string) do |g|\n g.int(length: 4)\n g.lit('/')\n g.int(ranges: [1000..9_999_999_999])\n g.lit('/07')\n end\n end", "def full_name_course_num\n \"#{course_num}: #{name}\"\n end", "def swedish_organisation_number\n # Valid leading digit: 1, 2, 3, 5, 6, 7, 8, 9\n # Valid third digit: >= 2\n # Last digit is a control digit\n base = [sample([1, 2, 3, 5, 6, 7, 8, 9]), sample((0..9).to_a), sample((2..9).to_a), format('%06d', rand(10**6))].join\n base + luhn_algorithm(base).to_s\n end", "def south_african_listed_company_registration_number\n generate(:string) do |g|\n g.int(length: 4)\n g.lit('/')\n g.int(ranges: [1000..9_999_999_999])\n g.lit('/06')\n end\n end", "def export_cell_name(project_id, product_type_name, class_number, attribute_name, carrier_name)\r\n str = \"#{project_id} #{product_type_name} #{class_number} #{attribute_name} #{carrier_name}\"\r\n str = str.gsub(/[^0-9a-z]/i, '')\r\n str = 'P' + str\r\n str\r\n end", "def pcb_unique_number\n self.pcb_prefix + '-' + self.pcb_number\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /mercadoria/1 DELETE /mercadoria/1.json
def destroy @mercadorium.destroy respond_to do |format| format.html { redirect_to mercadoria_url } format.json { head :no_content } end end
[ "def destroy\n @json.destroy\n\n head :no_content\n end", "def destroy\n @asignatura.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @prueba_json.destroy\n respond_to do |format|\n format.html { redirect_to prueba_jsons_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @remuneracion.destroy\n respond_to do |format|\n format.html { redirect_to remuneraciones_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @agronomiagalera = Agronomiagalera.find(params[:id])\n @agronomiagalera.destroy\n\n respond_to do |format|\n format.html { redirect_to agronomiagaleras_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @miembro = Miembro.find(params[:id])\n @miembro.destroy\n\n respond_to do |format|\n format.html { redirect_to miembros_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @remito = Remito.find(params[:id])\n @remito.destroy\n\n respond_to do |format|\n format.html { redirect_to remitos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @agronomiadecanato = Agronomiadecanato.find(params[:id])\n @agronomiadecanato.destroy\n\n respond_to do |format|\n format.html { redirect_to agronomiadecanatos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @reconocimiento = Reconocimiento.find(params[:id])\n @reconocimiento.destroy\n\n respond_to do |format|\n format.html { redirect_to reconocimientos_url }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @imobiliaria = Imobiliaria.find(params[:id])\r\n @imobiliaria.destroy\r\n\r\n respond_to do |format|\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @unidad.destroy\n respond_to do |format|\n format.html { redirect_to unidad_index_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @respuesta = Respuesta.find(params[:id])\n @respuesta.destroy\n\n respond_to do |format|\n format.html { redirect_to respuestas_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @unidad.destroy\n respond_to do |format|\n format.html { redirect_to unidades_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @metodologia.destroy\n respond_to do |format|\n format.html { redirect_to metodologias_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @reclamo.destroy\n respond_to do |format|\n format.html { redirect_to reclamos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @idioma = Idioma.find(params[:id])\n @idioma.destroy\n\n respond_to do |format|\n format.html { redirect_to idiomas_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @recetum = Recetum.find(params[:id])\n @recetum.destroy\n\n respond_to do |format|\n format.html { redirect_to receta_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @datosgenerale.destroy\n respond_to do |format|\n format.html { redirect_to datosgenerales_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @orcamento.destroy\n respond_to do |format|\n format.html { redirect_to orcamentos_url }\n format.json { head :no_content }\n end\n\n\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /permits POST /permits.json
def create @permit = Permit.new(permit_params) @permit.category_id = params[:category_id] @permit.employee_id = params[:employee_id] @permit.site_id = params[:site_id] respond_to do |format| if @permit.save format.html { redirect_to @permit, notice: 'Permit was successfully created.' } format.json { render :show, status: :created, location: @permit } else format.html { render :new } format.json { render json: @permit.errors, status: :unprocessable_entity } end end end
[ "def create\n @permit = Permit.new(permit_params)\n @permit.service_type = @service_type\n @permit.trusted_app = @current_app\n\n # Determine the permitable object\n @permit.permitable = permitable\n\n respond_to do |format|\n if @permit.save\n format.json { render action: 'show', status: :created, location: api_v1_permit_url(@permit) }\n else\n format.json { render json: @permit.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @permit = Permit.new(permit_params)\n\n respond_to do |format|\n if @permit.save\n format.html { redirect_to @permit, notice: 'Permit was successfully created.' }\n format.json { render action: 'show', status: :created, location: @permit }\n else\n format.html { render action: 'new' }\n format.json { render json: @permit.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @permit = Permit.new(permit_params)\n\n respond_to do |format|\n if @permit.save\n format.html { redirect_to @permit, notice: 'Permit was successfully created.' }\n format.json { render :show, status: :created, location: @permit }\n else\n format.html { render :new }\n format.json { render json: @permit.errors, status: :unprocessable_entity }\n end\n end\n end", "def permits\n @permits ||= Hashie::Mash.new\n end", "def permits\n @permits\n end", "def create\n @bldg_permit = BldgPermit.new(bldg_permit_params)\n\n if @bldg_permit.save\n render json: @bldg_permit, status: :created, location: @bldg_permit\n else\n render json: @bldg_permit.errors, status: :unprocessable_entity\n end\n end", "def permit(*capabilities)\n @caps[:permitted].merge parse(capabilities)\n save\n end", "def permits=(list)\n if list.class == Array\n list = List.new(list)\n list.each_with_index do |value, index|\n if value.is_a?(Hash)\n list[index] = Permit.new(value)\n end\n end\n end\n @permits = list\n end", "def index\n @permits = Permit.all\n end", "def create_permits\n begin\n names.inject([]) do |res, name|\n permit = permit(name)\n res << permit if valid?(permit)\n res\n end\n rescue RuntimeError => e\n debug \"Error instantiating Permit instance for #{name}, cause: #{e}\"\n nil\n end\n end", "def permit\n case method\n when :get\n permit?\n when :post\n permit!\n end\n end", "def update\n @permit.permitable = permitable \n respond_to do |format|\n if @permit.update(permit_params)\n format.json { head :no_content }\n else\n format.json { render json: @permit.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @permitowner = Permitowner.new(permitowner_params)\n\n respond_to do |format|\n if @permitowner.save\n format.html { redirect_to @permitowner, notice: 'Permitowner was successfully created.' }\n format.json { render :show, status: :created, location: @permitowner }\n else\n format.html { render :new }\n format.json { render json: @permitowner.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @auth_assign_permit = Auth::AssignPermit.new(params[:auth_assign_permit])\n\n respond_to do |format|\n if @auth_assign_permit.save\n format.html { redirect_to @auth_assign_permit, notice: 'Assign permit was successfully created.' }\n format.json { render json: @auth_assign_permit, status: :created, location: @auth_assign_permit }\n else\n format.html { render action: \"new\" }\n format.json { render json: @auth_assign_permit.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_permit(apparat)\n unless current_user.admin?\n company = Company.find(apparat_params[:company_id]) if apparat_params[:company_id].present?\n if company and current_user.companies_permits.find_by(company: company)\n role = current_user.companies_permits.find_by(company: company).role\n else\n role = \"newbie\"\n end\n apparat.apparats_permits.create(user: current_user, role: role)\n end\n end", "def permits\n @permits ||= builders.inject({}) do |permits, builder|\n debug \"++ Permit Builder: #{builder_class builder}\"\n built_permits = permits_built_with(builder)\n\n if built_permits\n debug \"== Permits built: #{built_permits.size}\"\n permits[builder] = built_permits\n end\n\n permits\n end\n end", "def post\n raise HTTPStatus::Forbidden\n end", "def permit!\n @permitted = true and self\n end", "def permits_service\n @permits_service ||= PermitsService.new(self, 'permits')\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /permits/1 PATCH/PUT /permits/1.json
def update @permit.category_id = params[:category_id] @permit.employee_id = params[:employee_id] @permit.site_id = params[:site_id] respond_to do |format| if @permit.update(permit_params) format.html { redirect_to @permit, notice: 'Permit was successfully updated.' } format.json { render :show, status: :ok, location: @permit } else format.html { render :edit } format.json { render json: @permit.errors, status: :unprocessable_entity } end end end
[ "def update\n @permit.permitable = permitable \n respond_to do |format|\n if @permit.update(permit_params)\n format.json { head :no_content }\n else\n format.json { render json: @permit.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @permit.update(permit_params)\n format.html { redirect_to @permit, notice: 'Permit was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @permit.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @permit.update(permit_params)\n format.html { redirect_to @permit, notice: 'Permit was successfully updated.' }\n format.json { render :show, status: :ok, location: @permit }\n else\n format.html { render :edit }\n format.json { render json: @permit.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @bldg_permit = BldgPermit.find(params[:id])\n\n if @bldg_permit.update(bldg_permit_params)\n head :no_content\n else\n render json: @bldg_permit.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @permitowner.update(permitowner_params)\n format.html { redirect_to @permitowner, notice: 'Permitowner was successfully updated.' }\n format.json { render :show, status: :ok, location: @permitowner }\n else\n format.html { render :edit }\n format.json { render json: @permitowner.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n authorize! :update, CompetenceTier\n \n @competence_tier.update!(competence_tier_params)\n render json: {status: :ok}\n end", "def put?; request_method == \"PUT\" end", "def put\n request_method('PUT')\n end", "def update\n respond_to do |format|\n if @miscellaneous_ability.update(miscellaneous_ability_params)\n format.html { redirect_to @miscellaneous_ability, notice: 'Miscellaneous ability was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @miscellaneous_ability.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n #raise CanCan::AccessDenied.new(\"不能修改已审批的申请!\",assaults_path ) if @assault.state > 0\n respond_to do |format|\n if @assault.update(assault_params)\n format.html { redirect_to @assault, notice: 'Assault was successfully updated.' }\n format.json { render :show, status: :ok, location: @assault }\n else\n format.html { render :edit }\n format.json { render json: @assault.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n authorize @specialization\n\n respond_to do |format|\n if @specialization.update(specialization_update_params)\n format.html { redirect_to @specialization, notice: I18n.t(\"activerecord.notice.specialization.success_update\") }\n format.json { render :show, status: :ok, location: @specialization }\n else\n format.html { render :edit }\n format.json { render json: @specialization.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n authorize @requirement\n\n respond_to do |format|\n if @requirement.update(\n name: requirement_params[:name],\n description: requirement_params[:description],\n num_required: requirement_params[:num_required]\n )\n format.html { redirect_to @requirement, notice: 'Requirement was successfully updated.' }\n format.json { render :show, status: :ok, location: @requirement }\n else\n format.html { render :edit }\n format.json { render json: @requirement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @standalone_resource = StandaloneResource.find(params[:id])\n # require modify permissions for this object\n require_privilege(Alberich::Privilege::MODIFY, @standalone_resource)\n\n respond_to do |format|\n if @standalone_resource.update_attributes(params[:standalone_resource])\n format.html { redirect_to @standalone_resource, notice: 'Standalone resource was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @standalone_resource.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n authorize! :update, @water_fountain\n respond_to do |format|\n if @water_fountain.update(water_fountain_params)\n format.json { head :no_content }\n else\n format.json { render json: { error: @water_fountain.errors.full_messages }, status: :unprocessable_entity }\n end\n end\n end", "def update\n keystone.update_tenant({:id=>params[:id],:name=>params[:name],:description=>params[:description],:enabled=>params[:enabled]})\n respond_to do |format|\n format.html { redirect_to tenants_path, :notice => 'Tenant was successfully updated.' }\n format.json { head :ok }\n end\n end", "def permit\n case method\n when :get\n permit?\n when :post\n permit!\n end\n end", "def update\n @request_for_change.set_manager(force: true)\n @request_for_change.set_security_officer(force: true)\n\n respond_to do |format|\n if @request_for_change.update(request_for_change_params)\n format.html { redirect_to edit_request_for_change_path(@request_for_change), notice: 'Request for change was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @request_for_change.errors, status: :unprocessable_entity }\n end\n end\n end", "def put(*a) route 'PUT', *a end", "def update\n if( get_seeker_id = params[:id] )\n @seeker.skill_list = params[:seeker][:skill_list].to_s.downcase\n respond_to do |format|\n if @seeker.update(seeker_params)\n format.html { redirect_to root_path, notice: 'Seeker was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @seeker.errors, status: :unprocessable_entity }\n end\n end\n else\n permission_denied \"You_do_no_own_this_profile\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /permits/1 DELETE /permits/1.json
def destroy @permit.destroy respond_to do |format| format.html { redirect_to permits_url, notice: 'Permit was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @permit.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @permit.destroy\n respond_to do |format|\n format.html { redirect_to permits_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @bldg_permit.destroy\n\n head :no_content\n end", "def destroy\n @permitdetail.destroy\n respond_to do |format|\n format.html { redirect_to permitdetails_url, notice: 'Permitdetail was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @vehiclepermit.destroy\n respond_to do |format|\n format.html { redirect_to permits_url, notice: 'Permit was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @permitowner.destroy\n respond_to do |format|\n format.html { redirect_to permitowners_url, notice: 'Permitowner was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @privilege.destroy\n respond_to do |format|\n format.html { redirect_to privileges_url }\n format.json { head :no_content }\n end\n end", "def destroy\n PolicyBrief.delete_hack(params[:id])\n\n respond_to do |format|\n format.html { redirect_to policy_briefs_url }\n format.json { head :ok }\n end\n end", "def destroy\n @miscellaneous_ability.destroy\n respond_to do |format|\n format.html { redirect_to miscellaneous_abilities_url }\n format.json { head :no_content }\n end\n end", "def destroy\n authorize! :destroy, @water_fountain\n @water_fountain.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @food_business_permit.destroy\n respond_to do |format|\n format.html { redirect_to food_business_permits_url, notice: 'Food business permit was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @access.destroy\n respond_to do |format|\n format.html { redirect_to accesses_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @privilege_level.destroy\n respond_to do |format|\n format.html { redirect_to privilege_levels_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @disability = Disability.find(params[:id])\n @disability.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_disabilities_url }\n format.json { head :ok }\n end\n end", "def destroy\n @permit_role.destroy\n respond_to do |format|\n format.html { redirect_to permit_roles_url, notice: 'Permit role was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n authorize! :read_admin, User\n @typeresid.destroy\n respond_to do |format|\n format.html { redirect_to typeresids_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @req = Req.find(params[:id])\n @req.destroy\n\n respond_to do |format|\n format.html { redirect_to reqs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @secret.destroy\n respond_to do |format|\n format.html { redirect_to secrets_url, notice: 'El secreto se eliminó correctamente.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @userprivilege = Userprivilege.find(params[:id])\n @userprivilege.destroy\n\n respond_to do |format|\n format.html { redirect_to userprivileges_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checkse if devfile has any user added observers and sends notification to those nodes
def checkForObservers(devfile) begin path = "/user/" + params[:username] + "/device/" + params[:devicename] + "/files" + devfile.path + devfile.name devfile.file_observers.each do |fo| begin if fo XmppHelper::notificationToNode(fo, devfile, "Content updated!") end rescue Exception => ex putsE(ex) end end rescue Exception => e puts "Error in cheking checking devfile for observers!" puts " -- line: #{e.backtrace[0].to_s}" end end
[ "def checkForObservers(devfile, username, devicename)\n begin\n path = \"/user/\" + username + \"/device/\" + devicename + \"/files\" + devfile.path + devfile.name\n devfile.file_observers.each do |fo|\n begin\n if fo\n XmppHelper::notificationToNode(fo, devfile, \"Content updated!\")\n end\n rescue Exception => ex\n putsE(ex)\n end \n end \n rescue Exception => e\n puts \"Error in cheking checking devfile for observers!\"\n puts \" -- line: #{e.backtrace[0].to_s}\"\n end\n end", "def notify_users_and_add_it\n return # disabled for now\n return true if remote?\n User.find_all_by_notify_on_new_torrents(true).each do |user|\n Notifier.send_new(user,self) if user.notifiable_via_jabber?\n user.watch(self) unless user.dont_watch_new_torrents?\n end\n end", "def listeners\n users_to_notify = Set.new\n users_to_notify += self.proposal.currently_awaiting_approvers\n users_to_notify += self.proposal.individual_steps.approved.map(&:user)\n users_to_notify += self.proposal.observers\n users_to_notify << self.proposal.requester\n # Creator of comment doesn't need to be notified\n users_to_notify.delete(self.user)\n users_to_notify\n end", "def listeners\n users_to_notify = Set.new\n users_to_notify += self.proposal.currently_awaiting_approvers\n users_to_notify += self.proposal.approvals.approved.map(&:user)\n users_to_notify += self.proposal.observers\n users_to_notify << self.proposal.requester\n # Creator of comment doesn't need to be notified\n users_to_notify.delete(self.user)\n users_to_notify\n end", "def add_observer_if_necessary\n observer = @obs.user.name || @obs.user.login\n collector = @obs.collection_numbers.first&.name\n return if collector == observer\n\n label(\"Observer\")\n @para << observer\n @para.line_break\n end", "def notify_on_changes!\n ensure_connection! { register_callback(notifier) }\n end", "def users_to_notify\n super\n end", "def notify_observers\r\n self.observers.each {|observer| observer.update(self)}\r\n end", "def notify_user\n group = self.group\n admin = self.group.admin\n if group && admin && self.user_id != self.admin.id\n self.user.devices.each { |x| x.fire_notification!(\"#{admin.username} added you to the group #{group.name}\", :added_to_group, { group_id: group.id, group: group.as_json }) }\n end\n end", "def observers\n\t\t\t@observers ||= []\n\t\tend", "def observers\n @observers ||= []\n end", "def notify_observers(notification)\n observers = Array(@observer_map[notification.name])\n observers.each{|observer| observer.notify_observer(notification)}\n end", "def notify\n @subscribers.each { |ident, (block,obj)| block.call(obj) }\n end", "def notify_observers\n @observers.each do |observer|\n observer.update(self)\n end\n end", "def observers\n [reporter]\n end", "def notified_users\n notified = []\n\n # Author and auditors are always notified unless they have been\n # locked or don't want to be notified\n notified << user if user\n\n notified += auditor_users\n\n # Only notify active users\n notified = notified.select { |u| u.active? }\n\n notified.uniq!\n\n notified\n end", "def notify_starting\n\t\tuser_list = []\n\t\tparty_list.each do |uid, uhash|\n\t\t\tuser_list <<= uid if uhash[:status] == STATUS_ATTENDING\t\t\t\n\t\tend\n\t\tnotification = EventNotification.new(NOTIF_EVENT_STARTING, self)\n\t\tnotify(notification, user_list, false)\n\tend", "def inform_obeservers\n\t\t@observers.each { |observer| observer.update(self) }\n\tend", "def loadNotifiersAsObservers(notifier_dir)\n # dynamically load each notifier found\n Dir.glob(\"#{notifier_dir}/**/*.rb\").each{|f| require f}\n @notification = nil\n @logger ||= Logger.new(STDOUT, Logger::INFO)\n @logger.info(\"NOTIFIER_DIR = #{notifier_dir}\")\n Dir.glob(\"#{notifier_dir}/*.rb\").each do |f|\n @logger.debug(\"loading notifier from file: #{f}\")\n clazz = getClassFromFile(f)\n self.add_observer(clazz.instance)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates file's metadata to db parameters: f filehash commit the commit the file belongs to
def updateDevfile(f, commit) #:doc: dev_file = nil begin # Checks if there is any changes in files. f_filedate = DateTime.strptime(f['filedate'], "%T %F") f_filedate = f_filedate.strftime('%F %T').to_s now = DateTime.now.strftime('%F %T') puts "name: #{f['name']}" puts "path: #{f['path']}" puts "Finding devfile.." dev_file = @device.devfiles.find(:first, :conditions => ["name = ? and path = ?", f['name'], f['path']]) if dev_file != nil puts "devfile found: " + dev_file.id.to_s else puts "Devfile not found" raise Exception.new("Devfile not found. Can not update it!") end blob = dev_file.blobs.find_by_blob_hash_and_devfile_id(f['blob_hash'], dev_file.id) if blob != nil puts "Blob already exists!" puts "Blob: " + blob.id.to_s return else puts "Blob was not found!" end # Finds the blob that is newest one previous_blob_id = nil current_blob = dev_file.blobs.find_by_id(dev_file.blob_id) if current_blob != nil previous_blob_id = current_blob.id.to_s puts "Current blob: " + current_blob.id.to_s end # If the blob, didn't exist yet, creates it. Ensures that blob will have version number. if blob == nil #or current_blob == nil version = 0 if current_blob != nil version = current_blob.version + 1 end puts "Creates new blob, verion num: " + version.to_s sql = "insert into blobs(blob_hash, created_at, updated_at, size, filedate, uploaded, version, devfile_id, predecessor_id, latitude, longitude) values('#{f['blob_hash']}', '#{now}', '#{now}', '#{f['size']}', '#{f_filedate}', '0', '#{version}', '#{dev_file.id}', '#{previous_blob_id}', '#{@commit_location['latitude']}', '#{@commit_location['longitude']}');" ActiveRecord::Base.connection.execute(sql) end puts "Finding the newly created blob.." blob = dev_file.blobs.find_by_blob_hash(f['blob_hash']) puts " found blob: " + blob.id.to_s current_blob.update_attribute(:follower_id, blob.id) puts "Updating devfile" # Updates changes in devfile (current blob) sql = "update devfiles set filetype = '#{f['filetype']}', latitude = '#{f['latitude']}', longitude = '#{f['longitude']}', blob_id = '#{blob.id.to_s}', updated_at = '#{now}' where name = '#{f['name']}' and path = '#{f['path']}' and device_id = #{@device.id};" puts " SQL: " + sql.background(:red) ActiveRecord::Base.connection.execute(sql) BlobsInCommit.find_or_create_by_blob_id_and_commit_id(blob.id, commit.id) #checkForObservers(dev_file) rescue => e puts "Errors in updating file" + e raise e end puts "devfile updated!" return dev_file end
[ "def update_metadata\n # @todo db - refactor to use an update\n metadata = files_doc\n metadata[:length] = @file_position\n metadata[:md5] = @local_md5\n @files.save(metadata)\n end", "def update_file_metadata(data)\n update_attributes!( :file_size => data.bytesize, :file_hash => Digest::SHA1.hexdigest( data ) )\n end", "def update_file_metadata( data = asset_store.read_original(self) )\n update_attributes!( :file_size => data.bytesize, :file_hash => Digest::SHA1.hexdigest( data ) )\n end", "def update_file_in_db(file_id, filename, public_status, folder_id)\n $db.execute(\"UPDATE files SET file_name = ?, public_status = ?, folder_id = ? WHERE file_id = ?\", filename, public_status, folder_id, file_id)\nend", "def prepare_db_data( f, cl, tbd, df )\n s = File::Stat.new( f )\n if ! s\n puts \"couldn't stat #{f}\\n\"\n next\n end\n\n # grab extension\n m = /(\\.\\w+)$/.match( f )\n if m && m[1]\n # yes it's redundant, but this way, if the file is outside of it's directory i have half a chance of knowing what it is\n new_pathfile = s.mtime.strftime( \"%m/%d/%m%d%H%M\" ) + m[1]\n else \n puts \"couldn't find file extension for #{f}\\n\"\n next\n end\n\n md5_checksum = Digest::MD5.hexdigest( File.read( f ) )\n\n # make directories if needed\n testfile = tbd + s.mtime.strftime( \"/%m\" )\n if ! File.exists?( testfile )\n Dir.mkdir( testfile )\n end\n\n testfile += s.mtime.strftime( \"/%d\" )\n if ! File.exists?( testfile )\n Dir.mkdir( testfile )\n end\n\n # copy file to new location\n FileUtils.copy( f, \"#{tbd}/\" + new_pathfile )\n\n # save data for db push\n df.push( { :class => cl, :created_text_date => s.mtime, :created_epoch_seconds => s.mtime.to_i, :pathfile => new_pathfile, :md5_checksum => md5_checksum } )\nend", "def set_metadata( file_list, tag_hash)\n file_list = [*file_list] # make sure file_list is an array\n file_list.each do |file_name|\n if File.exist?(file_name) \n ok = TagLib::FileRef.open(file_name) do |f|\n tag = f.tag\n tag_hash.each do |tag_name, value|\n\n # make sure that the tag_nam (hash key) is a string and then add = to it\n if tag_name.class != String\n tag_name = tag_name.to_s\n end\n tag_name += \"=\"\n\n if tag.respond_to?(tag_name)\n tag.send(tag_name, value)\n else\n puts \"can't modify tag #{tag_name}\"\n end\n end\n f.save\n end\n if ok == false then\n puts \"uh-oh. There was a problem saving/opening #{f}, it's tags were not modified.\"\n end\n else\n puts \"file #{file_name} does not exist, so its tags were not updated.\"\n end\n end\n end", "def createDevfile(f, commit) #:doc:\n \n dev_file = nil\n blob = nil\n b_in_c = nil\n \n # If file already exists, raises an error but nothing needs to be deleted (except the commit is cancelled)\n begin \n dev_file = Devfile.find_by_name_and_path_and_device_id(f['name'], f['path'], @device.id)\n if dev_file != nil\n puts \"Devfile: #{f['path'] + f['name']} already exits, cannot create, use update instead\"\n #raise ArgumentError.new(\"Devfile already exits for this device, cannot use CREATE -method, use UPDATE instead to add new version\")\n \n # This is tested! Not sure how well it works..\n puts \"Devfile already found -> updates it!\"\n #updateDevfile(f, commit)\n end\n rescue Exception => e\n puts e.to_s\n puts e.backtrace[0].to_s\n raise e\n end\nputs \"name: #{f['name']}\"\nputs \"path: #{f['path']}\"\n \n # If something goes wrong, raises an error, and deletes the data created\n begin\n \n puts \"Creating new dev_file, blob etc..\"\n \n \n f_filedate = DateTime.strptime(f['filedate'], \"%T %F\")\n f_filedate = f_filedate.strftime('%F %T').to_s\n \n now = DateTime.now\n \n # get or create devfile\n dev_file = Devfile.find_or_create_by_name_and_path_and_device_id(f['name'], f['path'], @device.id)\n if dev_file.created_at >= now\n sql = \"update devfiles set filetype='#{f['filetype']}', path='#{f['path']}', privatefile=0 where id=#{dev_file.id}\" \n ActiveRecord::Base.connection.execute(sql)\n end\n \n # get or create blob\n blob = Blob.find_or_create_by_blob_hash_and_devfile_id(f['blob_hash'], dev_file.id)\n if blob.created_at >= now # if just created\n # Version number\n version = 0\n predecessor_blob_id = \"NULL\"\n follower_blob_id = \"NULL\"\n if dev_file.blob_id != nil\n predecessor_blob_id = dev_file.blobs.find_by_id(dev_file.blob_id) ? dev_file.blobs.find_by_follower_id(dev_file.blob_id).id.to_s : \"NULL\"\n follower_blob_id = dev_file.blobs.find_by_predecessor_id(blob.id) ? dev_file.blobs.find_by_predecessor_id(blob.id).id.to_s : \"NULL\"\n version = dev_file.blobs.find_by_id(dev_file.blob_id).version + 1 \n end\n \nputs \"predecessor_id=#{predecessor_blob_id.to_s},\"\nputs \"follower_id=#{follower_blob_id.to_s},\"\nputs \"size=#{f['size'].to_s},\" \nputs \"filedate='#{f_filedate.to_s}',\" \nputs \"version=#{version.to_s},\" \nputs \"uploaded=#{f['uploaded'].to_s},\" \nputs \"latitude=#{@commit_location['latitude'].to_s}, \" \nputs \"longitude=#{@commit_location['longitude'].to_s} \" \n \n if f['uploaded']\n puts \"uploaded: true\"\n ul = '1'\n else\n puts \"uploaded: false\"\n ul = '0'\n end\n \n sql = \"update blobs set uploaded=#{ul}, predecessor_id=#{predecessor_blob_id.to_s}, follower_id=#{follower_blob_id.to_s}, size=#{f['size'].to_s}, filedate='#{f_filedate.to_s}', version=#{version.to_s}, latitude=#{@commit_location['latitude'].to_s}, longitude=#{@commit_location['longitude'].to_s} where id=#{blob.id};\"\nputs \"sql: \" + sql\n \n ActiveRecord::Base.connection.execute(sql)\n end\n \n # Creates association between blob and commit\n b_in_c = BlobsInCommit.find_or_create_by_blob_id_and_commit_id(blob.id, commit.id)\n \n # update blob_id to devfile\n if dev_file.blob_id != blob.id\n sql = \"update devfiles set blob_id=#{blob.id} where id=#{dev_file.id};\"\n ActiveRecord::Base.connection.execute(sql)\n end\n \n \n #checkForObservers(dev_file)\n \n # If parent_blob_hash is given, tries to find the parent, and creates new branch from the parent\n if f['file_origin'] \n createBranch(f['file_origin'], blob)\n end\n\n rescue Exception => e\n puts \" -- Error in createDevfile: \" + e\n puts \" -- line: #{e.backtrace[0].to_s}\"\n \n puts \"Deleting created data..\"\n \n # If dev_file was created now, deletes it\n dev_file.delete if dev_file\n puts \"Deleted created dev_file!\" if dev_file\n \n if blob \n if b_in_c\n BlobsInCommit.delete_all([\"commit_id = ? AND blob_id = ?\", b_in_c.commit_id.to_s, blob.blob_id.to_s])\n puts \"Deleted created blobs_in_commits!\" if b_in_c\n end\n blob.delete \n puts \"Deleted created blob!\"\n end\n \n # Throws forward the exception..\n raise e\n end\n puts \"File created\"\n return dev_file\n end", "def commit\n File.open(@path, 'r+') {\n |f|\n f.seek(-TagSize, IO::SEEK_END)\n tag = f.read(3)\n if tag != 'TAG'\n\t# Append new tag\n\tf.seek(0, IO::SEEK_END)\n\tf.write('TAG')\n end\n f.write([@songname,@artist,@album, (\"%04d\" % @year), @comment, 0, @tracknum, @genre_id].pack(TAGFORMAT_WRITE))\n }\n end", "def createDevfile(f, commit) #:doc:\n \n dev_file = nil\n blob = nil\n b_in_c = nil\n \n # If file already exists, raises an error but nothing needs to be deleted (except the commit is cancelled)\n begin \n dev_file = Devfile.find_by_name_and_path_and_device_id(f['name'], f['path'], @device.id)\n if dev_file != nil\n puts \"Devfile: #{f['path'] + f['name']} already exits, cannot create, use update instead\"\n raise ArgumentError.new(\"Devfile already exits for this device, cannot use CREATE -method, use UPDATE instead to add new version\")\n end\n rescue Exception => e\n puts e.to_s\n puts e.backtrace[0].to_s\n raise e\n end\nputs \"name: #{f['name']}\"\nputs \"path: #{f['path']}\"\n \n # If something goes wrong, raises an error, and deletes the data created\n begin\n \n puts \"Creating new dev_file, blob etc..\"\n \n \n f_filedate = DateTime.strptime(f['filedate'], \"%T %F\")\n f_filedate = f_filedate.strftime('%F %T').to_s\n \n now = DateTime.now\n \n # get or create devfile\n dev_file = Devfile.find_or_create_by_name_and_path_and_device_id(f['name'], f['path'], @device.id)\n if dev_file.created_at >= now\n sql = \"update devfiles set filetype='#{f['filetype']}', path='#{f['path']}', privatefile=0 where id=#{dev_file.id}\" \n ActiveRecord::Base.connection.execute(sql)\n end\n \n # get or create blob\n blob = Blob.find_or_create_by_blob_hash_and_devfile_id(f['blob_hash'], dev_file.id)\n if blob.created_at >= now # if just created\n # Version number\n version = 0\n predecessor_blob_id = \"NULL\"\n follower_blob_id = \"NULL\"\n if dev_file.blob_id != nil\n predecessor_blob_id = dev_file.blobs.find_by_id(dev_file.blob_id) ? dev_file.blobs.find_by_follower_id(dev_file.blob_id).id.to_s : \"NULL\"\n follower_blob_id = dev_file.blobs.find_by_predecessor_id(blob.id) ? dev_file.blobs.find_by_predecessor_id(blob.id).id.to_s : \"NULL\"\n version = dev_file.blobs.find_by_id(dev_file.blob_id).version + 1 \n end\n \nputs \"predecessor_id=#{predecessor_blob_id.to_s},\"\nputs \"follower_id=#{follower_blob_id.to_s},\"\nputs \"size=#{f['size'].to_s},\" \nputs \"filedate='#{f_filedate.to_s}',\" \nputs \"version=#{version.to_s},\" \nputs \"uploaded='0',\" \nputs \"latitude=#{@commit_location['latitude'].to_s}, \" \nputs \"longitude=#{@commit_location['longitude'].to_s} \" \n \n sql = \"update blobs set predecessor_id=#{predecessor_blob_id.to_s}, follower_id=#{follower_blob_id.to_s}, size=#{f['size'].to_s}, filedate='#{f_filedate.to_s}', version=#{version.to_s}, uploaded='0', latitude=#{@commit_location['latitude'].to_s}, longitude=#{@commit_location['longitude'].to_s} where id=#{blob.id};\"\nputs \"sql: \" + sql\n \n ActiveRecord::Base.connection.execute(sql)\n end\n \n # Creates association between blob and commit\n b_in_c = BlobsInCommit.find_or_create_by_blob_id_and_commit_id(blob.id, commit.id)\n \n # update blob_id to devfile\n if dev_file.blob_id != blob.id\n sql = \"update devfiles set blob_id=#{blob.id} where id=#{dev_file.id};\"\n ActiveRecord::Base.connection.execute(sql)\n end\n \n \n #checkForObservers(dev_file)\n \n # If parent_blob_hash is given, tries to find the parent, and creates new branch form the parent\n if f['file_origin'] \n createBranch(f['file_origin'], blob)\n end\n\n rescue Exception => e\n puts \" -- Error in createDevfile: \" + e\n puts \" -- line: #{e.backtrace[0].to_s}\"\n \n puts \"Deleting created data..\"\n \n # If dev_file was created now, deletes it\n dev_file.delete if dev_file\n puts \"Deleted created dev_file!\" if dev_file\n \n if blob \n if b_in_c\n BlobsInCommit.delete_all([\"commit_id = ? AND blob_id = ?\", b_in_c.commit_id.to_s, blob.blob_id.to_s])\n puts \"Deleted created blobs_in_commits!\" if b_in_c\n end\n blob.delete \n puts \"Deleted created blob!\"\n end\n \n # Throws forward the exception..\n raise e\n end\n puts \"File created\"\n return dev_file\n end", "def add_hash_for_file filename, hash\n @client.query \"INSERT INTO #{@config['abc_file_hashes_table']} (filename, hash) VALUES ('#{filename}', '#{hash}')\"\n end", "def update_metadata!\n compilation_context.source_file_database.update_metadata(source_path)\n compilation_context.target_file_database.update_metadata(source_path)\n end", "def update_file_meta_data\n if file.present? && file_changed?\n self.filename = read_attribute(:file)\n self.content_type = file.file.content_type unless file.file.content_type.blank?\n self.file_size = file.file.size unless file.file.size.blank?\n end\n end", "def update_fileset_metadata(work, attrs)\n work.ordered_members.to_a.each_with_index do |member, i|\n builder = FileSetBuilder.new(member, user, attrs[i])\n builder.run\n end\n end", "def add_commit_to_db(hash)\n #insert hash values into proper attribute in commits table\n @con.exec_prepared('commitInsert', hash.values_at(*@@GIT_LOG_PROPERTIES))\n \n create_commit_filepath(hash[\"filepaths\"], hash[:commit_hash])\n create_commit_bug(hash[:bug], hash[:commit_hash]) if hash[:bug]!=nil\n end", "def update_file(params)\n self.processed = false\n self.attributes = params\n set_upload_attributes\n save!\n Document.delay.finalize_and_cleanup(id)\n end", "def update_metadata(file)\n metadata = MetadataEngine.new(file)\n\n # Special renaming case for misc files that do not need the tracklist\n if metadata.filepath.get_type == \"misc\"\n metadata.tags.artist = metadata.filepath.artist\n metadata.tags.year = metadata.filepath.year\n metadata.tags.album = metadata.filepath.album\n metadata.tags.cd = metadata.filepath.cd\n metadata.tags.index = metadata.filepath.index\n metadata.tags.title = metadata.filepath.title\n metadata.tags.save\n return\n end\n\n unless metadata.tracklist.has_tracklist?\n puts \"No .tracklist found for #{file}, generating it now.\"\n %x[generate-tracklist #{file.shellescape}]\n metadata = MetadataEngine.new(file)\n end\n\n # Update tags to reflect what's in the tracklist\n metadata.tags.artist = metadata.tracklist.artist\n metadata.tags.year = metadata.tracklist.year\n metadata.tags.album = metadata.tracklist.album\n metadata.tags.cd = metadata.tracklist.cd\n metadata.tags.index = metadata.tracklist.index\n metadata.tags.title = metadata.tracklist.title\n metadata.tags.type = metadata.tracklist.type\n metadata.tags.save\n\n # Update filepath to rename files based on new metadata\n metadata.filepath.artist = metadata.tracklist.artist\n metadata.filepath.year = metadata.tracklist.year\n metadata.filepath.album = metadata.tracklist.album\n metadata.filepath.cd = metadata.tracklist.cd\n metadata.filepath.index = metadata.tracklist.index\n metadata.filepath.title = metadata.tracklist.title\n metadata.filepath.save\n end", "def update_metadata(metsfile)\n\n @doc = Nokogiri::XML(File.read(metsfile))\n bitstreams = @doc.css('file')\n\n @provenance = <<-EOF.gsub(/^\\s+/, '')\n MIT Libraries updated OCW and media links to https; change made by\n Andromeda Yelton (m31@mit.edu) on %{date}\n No. of bitstreams updated: %{count}\n EOF\n\n @count = 0\n bitstreams.each do |bitstream|\n checksum = bitstream.attribute('CHECKSUM')\n bitstreampath = File.split(metsfile)[0]\n new_checksum, file_size = get_new_metadata(bitstreampath, bitstream)\n\n # You have to force both checksums to String, or else the equality test\n # will fail due to their different object types, even though the\n # representations look the same. If they differ, update the MODS and\n # PREMIS records.\n if checksum.to_s != new_checksum.to_s\n digest_node, size_node, original_name = get_premis_components(checksum)\n bitstream['CHECKSUM'] = digest_node.content = new_checksum.to_s\n bitstream['SIZE'] = size_node.content = file_size\n append_provenance(original_name, new_checksum, file_size)\n @count += 1\n end\n end\n\n date = Time.now.utc.strftime('%Y-%m-%d %H:%M:%S (UTC)')\n @provenance = @provenance % {:date => date, :count => @count}\n set_item_id(metsfile)\n File.write(metsfile, @doc.to_xml)\n end", "def file_hash=(value)\n @file_hash = value\n end", "def update_file_size(file_id, file_size)\n $db.execute(\"UPDATE files SET file_size = ? WHERE file_id = ?\", file_size, file_id)\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates metadata of a new file to db parameters: f file commit the commit the file belongs to
def createDevfile(f, commit) #:doc: dev_file = nil blob = nil b_in_c = nil # If file already exists, raises an error but nothing needs to be deleted (except the commit is cancelled) begin dev_file = Devfile.find_by_name_and_path_and_device_id(f['name'], f['path'], @device.id) if dev_file != nil puts "Devfile: #{f['path'] + f['name']} already exits, cannot create, use update instead" raise ArgumentError.new("Devfile already exits for this device, cannot use CREATE -method, use UPDATE instead to add new version") end rescue Exception => e puts e.to_s puts e.backtrace[0].to_s raise e end puts "name: #{f['name']}" puts "path: #{f['path']}" # If something goes wrong, raises an error, and deletes the data created begin puts "Creating new dev_file, blob etc.." f_filedate = DateTime.strptime(f['filedate'], "%T %F") f_filedate = f_filedate.strftime('%F %T').to_s now = DateTime.now # get or create devfile dev_file = Devfile.find_or_create_by_name_and_path_and_device_id(f['name'], f['path'], @device.id) if dev_file.created_at >= now sql = "update devfiles set filetype='#{f['filetype']}', path='#{f['path']}', privatefile=0 where id=#{dev_file.id}" ActiveRecord::Base.connection.execute(sql) end # get or create blob blob = Blob.find_or_create_by_blob_hash_and_devfile_id(f['blob_hash'], dev_file.id) if blob.created_at >= now # if just created # Version number version = 0 predecessor_blob_id = "NULL" follower_blob_id = "NULL" if dev_file.blob_id != nil predecessor_blob_id = dev_file.blobs.find_by_id(dev_file.blob_id) ? dev_file.blobs.find_by_follower_id(dev_file.blob_id).id.to_s : "NULL" follower_blob_id = dev_file.blobs.find_by_predecessor_id(blob.id) ? dev_file.blobs.find_by_predecessor_id(blob.id).id.to_s : "NULL" version = dev_file.blobs.find_by_id(dev_file.blob_id).version + 1 end puts "predecessor_id=#{predecessor_blob_id.to_s}," puts "follower_id=#{follower_blob_id.to_s}," puts "size=#{f['size'].to_s}," puts "filedate='#{f_filedate.to_s}'," puts "version=#{version.to_s}," puts "uploaded='0'," puts "latitude=#{@commit_location['latitude'].to_s}, " puts "longitude=#{@commit_location['longitude'].to_s} " sql = "update blobs set predecessor_id=#{predecessor_blob_id.to_s}, follower_id=#{follower_blob_id.to_s}, size=#{f['size'].to_s}, filedate='#{f_filedate.to_s}', version=#{version.to_s}, uploaded='0', latitude=#{@commit_location['latitude'].to_s}, longitude=#{@commit_location['longitude'].to_s} where id=#{blob.id};" puts "sql: " + sql ActiveRecord::Base.connection.execute(sql) end # Creates association between blob and commit b_in_c = BlobsInCommit.find_or_create_by_blob_id_and_commit_id(blob.id, commit.id) # update blob_id to devfile if dev_file.blob_id != blob.id sql = "update devfiles set blob_id=#{blob.id} where id=#{dev_file.id};" ActiveRecord::Base.connection.execute(sql) end #checkForObservers(dev_file) # If parent_blob_hash is given, tries to find the parent, and creates new branch form the parent if f['file_origin'] createBranch(f['file_origin'], blob) end rescue Exception => e puts " -- Error in createDevfile: " + e puts " -- line: #{e.backtrace[0].to_s}" puts "Deleting created data.." # If dev_file was created now, deletes it dev_file.delete if dev_file puts "Deleted created dev_file!" if dev_file if blob if b_in_c BlobsInCommit.delete_all(["commit_id = ? AND blob_id = ?", b_in_c.commit_id.to_s, blob.blob_id.to_s]) puts "Deleted created blobs_in_commits!" if b_in_c end blob.delete puts "Deleted created blob!" end # Throws forward the exception.. raise e end puts "File created" return dev_file end
[ "def createDevfile(f, commit) #:doc:\n \n dev_file = nil\n blob = nil\n b_in_c = nil\n \n # If file already exists, raises an error but nothing needs to be deleted (except the commit is cancelled)\n begin \n dev_file = Devfile.find_by_name_and_path_and_device_id(f['name'], f['path'], @device.id)\n if dev_file != nil\n puts \"Devfile: #{f['path'] + f['name']} already exits, cannot create, use update instead\"\n #raise ArgumentError.new(\"Devfile already exits for this device, cannot use CREATE -method, use UPDATE instead to add new version\")\n \n # This is tested! Not sure how well it works..\n puts \"Devfile already found -> updates it!\"\n #updateDevfile(f, commit)\n end\n rescue Exception => e\n puts e.to_s\n puts e.backtrace[0].to_s\n raise e\n end\nputs \"name: #{f['name']}\"\nputs \"path: #{f['path']}\"\n \n # If something goes wrong, raises an error, and deletes the data created\n begin\n \n puts \"Creating new dev_file, blob etc..\"\n \n \n f_filedate = DateTime.strptime(f['filedate'], \"%T %F\")\n f_filedate = f_filedate.strftime('%F %T').to_s\n \n now = DateTime.now\n \n # get or create devfile\n dev_file = Devfile.find_or_create_by_name_and_path_and_device_id(f['name'], f['path'], @device.id)\n if dev_file.created_at >= now\n sql = \"update devfiles set filetype='#{f['filetype']}', path='#{f['path']}', privatefile=0 where id=#{dev_file.id}\" \n ActiveRecord::Base.connection.execute(sql)\n end\n \n # get or create blob\n blob = Blob.find_or_create_by_blob_hash_and_devfile_id(f['blob_hash'], dev_file.id)\n if blob.created_at >= now # if just created\n # Version number\n version = 0\n predecessor_blob_id = \"NULL\"\n follower_blob_id = \"NULL\"\n if dev_file.blob_id != nil\n predecessor_blob_id = dev_file.blobs.find_by_id(dev_file.blob_id) ? dev_file.blobs.find_by_follower_id(dev_file.blob_id).id.to_s : \"NULL\"\n follower_blob_id = dev_file.blobs.find_by_predecessor_id(blob.id) ? dev_file.blobs.find_by_predecessor_id(blob.id).id.to_s : \"NULL\"\n version = dev_file.blobs.find_by_id(dev_file.blob_id).version + 1 \n end\n \nputs \"predecessor_id=#{predecessor_blob_id.to_s},\"\nputs \"follower_id=#{follower_blob_id.to_s},\"\nputs \"size=#{f['size'].to_s},\" \nputs \"filedate='#{f_filedate.to_s}',\" \nputs \"version=#{version.to_s},\" \nputs \"uploaded=#{f['uploaded'].to_s},\" \nputs \"latitude=#{@commit_location['latitude'].to_s}, \" \nputs \"longitude=#{@commit_location['longitude'].to_s} \" \n \n if f['uploaded']\n puts \"uploaded: true\"\n ul = '1'\n else\n puts \"uploaded: false\"\n ul = '0'\n end\n \n sql = \"update blobs set uploaded=#{ul}, predecessor_id=#{predecessor_blob_id.to_s}, follower_id=#{follower_blob_id.to_s}, size=#{f['size'].to_s}, filedate='#{f_filedate.to_s}', version=#{version.to_s}, latitude=#{@commit_location['latitude'].to_s}, longitude=#{@commit_location['longitude'].to_s} where id=#{blob.id};\"\nputs \"sql: \" + sql\n \n ActiveRecord::Base.connection.execute(sql)\n end\n \n # Creates association between blob and commit\n b_in_c = BlobsInCommit.find_or_create_by_blob_id_and_commit_id(blob.id, commit.id)\n \n # update blob_id to devfile\n if dev_file.blob_id != blob.id\n sql = \"update devfiles set blob_id=#{blob.id} where id=#{dev_file.id};\"\n ActiveRecord::Base.connection.execute(sql)\n end\n \n \n #checkForObservers(dev_file)\n \n # If parent_blob_hash is given, tries to find the parent, and creates new branch from the parent\n if f['file_origin'] \n createBranch(f['file_origin'], blob)\n end\n\n rescue Exception => e\n puts \" -- Error in createDevfile: \" + e\n puts \" -- line: #{e.backtrace[0].to_s}\"\n \n puts \"Deleting created data..\"\n \n # If dev_file was created now, deletes it\n dev_file.delete if dev_file\n puts \"Deleted created dev_file!\" if dev_file\n \n if blob \n if b_in_c\n BlobsInCommit.delete_all([\"commit_id = ? AND blob_id = ?\", b_in_c.commit_id.to_s, blob.blob_id.to_s])\n puts \"Deleted created blobs_in_commits!\" if b_in_c\n end\n blob.delete \n puts \"Deleted created blob!\"\n end\n \n # Throws forward the exception..\n raise e\n end\n puts \"File created\"\n return dev_file\n end", "def prepare_db_data( f, cl, tbd, df )\n s = File::Stat.new( f )\n if ! s\n puts \"couldn't stat #{f}\\n\"\n next\n end\n\n # grab extension\n m = /(\\.\\w+)$/.match( f )\n if m && m[1]\n # yes it's redundant, but this way, if the file is outside of it's directory i have half a chance of knowing what it is\n new_pathfile = s.mtime.strftime( \"%m/%d/%m%d%H%M\" ) + m[1]\n else \n puts \"couldn't find file extension for #{f}\\n\"\n next\n end\n\n md5_checksum = Digest::MD5.hexdigest( File.read( f ) )\n\n # make directories if needed\n testfile = tbd + s.mtime.strftime( \"/%m\" )\n if ! File.exists?( testfile )\n Dir.mkdir( testfile )\n end\n\n testfile += s.mtime.strftime( \"/%d\" )\n if ! File.exists?( testfile )\n Dir.mkdir( testfile )\n end\n\n # copy file to new location\n FileUtils.copy( f, \"#{tbd}/\" + new_pathfile )\n\n # save data for db push\n df.push( { :class => cl, :created_text_date => s.mtime, :created_epoch_seconds => s.mtime.to_i, :pathfile => new_pathfile, :md5_checksum => md5_checksum } )\nend", "def create_file(file)\n @generic_file = GenericFile.new\n @generic_file.batch_id = object.batch.pid\n @generic_file.add_file(file.read, 'content', file.name)\n @generic_file.apply_depositor_metadata(object.edit_users.first)\n @generic_file.date_uploaded = Time.now.ctime\n @generic_file.date_modified = Time.now.ctime\n @generic_file.save\n end", "def create\n File.open(@db_file, \"w\" ) do |file|\n end\n end", "def add_file_to_database(name, path, size, owner)\n $db.execute(\"INSERT INTO files (owner_id, file_name, file_size, file_path, publicity) VALUES (?, ?, ?, ?, 0)\", [owner, name, size, path])\nend", "def create_commit_filepath(filepaths, commit_hash)\n filepaths.each do |str_path, churn|\n @con.exec_prepared('fileInsert', [commit_hash,str_path, churn])\n end\n end", "def commit\n File.open(@path, 'r+') {\n |f|\n f.seek(-TagSize, IO::SEEK_END)\n tag = f.read(3)\n if tag != 'TAG'\n\t# Append new tag\n\tf.seek(0, IO::SEEK_END)\n\tf.write('TAG')\n end\n f.write([@songname,@artist,@album, (\"%04d\" % @year), @comment, 0, @tracknum, @genre_id].pack(TAGFORMAT_WRITE))\n }\n end", "def create_file_with_blog_metadata(title)\n filename = generate_filename(title)\n filepath = \"_posts/#{filename}\"\n\n raise 'The file already exists.' if File.exists?(filepath)\n\n blog_metadata = generate_metadata_for(title)\n File.write(filepath, blog_metadata)\n\n filepath\nend", "def add_hash_for_file filename, hash\n @client.query \"INSERT INTO #{@config['abc_file_hashes_table']} (filename, hash) VALUES ('#{filename}', '#{hash}')\"\n end", "def make_new_file\n\t\tmetadata_file_data = \"\"\n\t\tmetadata_file_data << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" standalone=\\\"yes\\\"?><cp:coreProperties\"\n\t\tmetadata_file_data << \" xmlns:cp=\\\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\\\" \"\n\t\tmetadata_file_data << \"xmlns:dc=\\\"http://purl.org/dc/elements/1.1/\\\" xmlns:dcterms=\\\"http://purl.org/dc/terms/\\\" \"\n\t\tmetadata_file_data << \"xmlns:dcmitype=\\\"http://purl.org/dc/dcmitype/\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">\"\n\t\tmetadata_file_data << \"<dc:creator>#{datastore['DOCAUTHOR']}</dc:creator><cp:lastModifiedBy>#{datastore['DOCAUTHOR']}\"\n\t\tmetadata_file_data << \"</cp:lastModifiedBy><cp:revision>1</cp:revision><dcterms:created xsi:type=\\\"dcterms:W3CDTF\\\">\"\n\t\tmetadata_file_data << \"2013-01-08T14:14:00Z</dcterms:created><dcterms:modified xsi:type=\\\"dcterms:W3CDTF\\\">\"\n\t\tmetadata_file_data << \"2013-01-08T14:14:00Z</dcterms:modified></cp:coreProperties>\"\n\n\t\t#where to find the skeleton files required for creating an empty document\n\t\tdata_dir = File.join(Msf::Config.install_root, \"data\", \"exploits\", \"docx\")\n\n\t\t#making the actual docx\n\t\tdocx = Rex::Zip::Archive.new\n\t\t#add skeleton files\n\t\tvprint_status(\"Adding skeleton files from #{data_dir}\")\n\t\tDir[\"#{data_dir}/**/**\"].each do |file|\n\t\t\tif not File.directory?(file)\n\t\t\t\tdocx.add_file(file.sub(data_dir,''), File.read(file))\n\t\t\tend\n\t\tend\n\t\t#add on-the-fly created documents\n\t\tvprint_status(\"Adding injected files\")\n\t\tdocx.add_file(\"docProps/core.xml\", metadata_file_data)\n\t\tdocx.add_file(\"word/_rels/settings.xml.rels\", @rels_file_data)\n\t\t#add the otherwise skipped \"hidden\" file\n\t\tfile = \"#{data_dir}/_rels/.rels\"\n\t\tdocx.add_file(file.sub(data_dir,''), File.read(file))\n\t\t#and lets create the file\n\t\tfile_create(docx.pack)\n\tend", "def addMetadata(filename, metadatatype, metadatavalue)\n begin\n \n if @fileMetadata.has_key?(filename)\n @fileMetadata[filename] = @fileMetadata[filename].to_s + \"&&&\" + metadatatype.downcase + \":\" + metadatavalue.downcase\n else\n @fileMetadata[filename] = metadatatype.downcase + \":\" + metadatavalue.downcase\n end\n \n rescue Exception => e\n puts \"Error: #{e.to_s}\"\n puts \" -- line: #{e.backtrace[0].to_s}\"\n raise Exception.new(\"Could not add metadata to a new file!\")\n end\n end", "def create_file_ds(f, id= nil, label=nil)\n puts \"creating file ds for #{f} \"\n if id.nil? || id.empty?\n id = File.basename(f, File.extname(f)).gsub(\" \", \"-\")\n end\n if label.nil? || label.empty?\n label = File.basename(f, File.extname(f)).gsub(\" \", \"-\")\n end\n\n ActiveFedora::Datastream.new(:dsID=>id, :controlGroup=>\"M\" , :blob=>File.open(f), :dsLabel=>label)\n\n end", "def write_metadata; end", "def trx_new_file\n if @current_user\n trx_id = params[:tid]\n file_name = request.query_parameters[:file_name]\n work_pid = ApiTransaction.find(trx_id).work_id\n file_pid = mint_new_id\n next_sequence = next_file_sequence(trx_id: trx_id, file_id: file_pid)\n\n metadata_formatter = Api::FileMetadataFormatter.new(content: { file_name: file_name, file_id: file_pid, work_id: work_pid }, user: @current_user )\n # validate metadata\n if metadata_formatter.valid?\n # write file from body of message to bucket\n bucket.put(\n named_path: \"#{trx_id}/#{file_pid}-#{next_sequence}\",\n body: request.body()\n )\n # write file metadata to bucket\n bucket.put(\n named_path: \"#{trx_id}/metadata-file-#{file_pid}.json\",\n body: metadata_formatter.initial_metadata\n )\n # update trx status\n ApiTransaction.set_status_based_on(trx_id: trx_id, action: :update)\n # respond ok\n render json: { trx_id: trx_id,\n file_name: file_name,\n file_id: file_pid,\n sequence: next_sequence },\n status: :ok\n else # invalid metadata, error 406\n render json: { error: 'Invalid metadata for file',\n file_name: file_name,\n file_id: file_pid,\n work_id: work_pid },\n status: :not_acceptable\n end\n else # unauthenticated user, error 401\n render json: { error: 'Token is required to authenticate user' },\n status: :unauthorized\n end\n end", "def create\n\n if File.exists?(dbfilename)\n puts \"Moved '#{dbfilename}' to '#{dbfilename}.bak'.\"\n FileUtils.mv(dbfilename, dbfilename + '.bak')\n end\n db = Sequel.sqlite(dbfilename)\n db.create_table :pdfmd_documents do\n String :md5sum, :primary_key => true\n String :filename\n String :author\n String :title\n String :subject\n Date :createdate\n String :keywords\n String :filepath\n end\n db.add_index :pdfmd_documents, :md5sum\n db.add_index :pdfmd_documents, :keywords\n end", "def updateDevfile(f, commit) #:doc:\n \n dev_file = nil\n \n begin\n # Checks if there is any changes in files.\n f_filedate = DateTime.strptime(f['filedate'], \"%T %F\")\n f_filedate = f_filedate.strftime('%F %T').to_s \n \n now = DateTime.now.strftime('%F %T')\nputs \"name: #{f['name']}\"\nputs \"path: #{f['path']}\"\n puts \"Finding devfile..\"\n dev_file = @device.devfiles.find(:first, :conditions => [\"name = ? and path = ?\", f['name'], f['path']])\n if dev_file != nil\n puts \"devfile found: \" + dev_file.id.to_s\n else\n puts \"Devfile not found\"\n raise Exception.new(\"Devfile not found. Can not update it!\")\n end\n \n \n blob = dev_file.blobs.find_by_blob_hash_and_devfile_id(f['blob_hash'], dev_file.id)\n if blob != nil\n puts \"Blob already exists!\"\n puts \"Blob: \" + blob.id.to_s\n return\n else\n puts \"Blob was not found!\"\n end\n \n # Finds the blob that is newest one\n previous_blob_id = nil\n current_blob = dev_file.blobs.find_by_id(dev_file.blob_id)\n if current_blob != nil\n previous_blob_id = current_blob.id.to_s\n puts \"Current blob: \" + current_blob.id.to_s\n \n end\n \n # If the blob, didn't exist yet, creates it. Ensures that blob will have version number.\n if blob == nil #or current_blob == nil\n version = 0\n if current_blob != nil\n version = current_blob.version + 1\n end\n \n puts \"Creates new blob, verion num: \" + version.to_s\n sql = \"insert into blobs(blob_hash, created_at, updated_at, size, filedate, uploaded, version, devfile_id, predecessor_id, latitude, longitude) values('#{f['blob_hash']}', '#{now}', '#{now}', '#{f['size']}', '#{f_filedate}', '0', '#{version}', '#{dev_file.id}', '#{previous_blob_id}', '#{@commit_location['latitude']}', '#{@commit_location['longitude']}');\"\n ActiveRecord::Base.connection.execute(sql)\n end\n \n puts \"Finding the newly created blob..\"\n blob = dev_file.blobs.find_by_blob_hash(f['blob_hash'])\n puts \" found blob: \" + blob.id.to_s\n \n current_blob.update_attribute(:follower_id, blob.id)\n \n puts \"Updating devfile\"\n # Updates changes in devfile (current blob)\n sql = \"update devfiles set filetype = '#{f['filetype']}', latitude = '#{f['latitude']}', longitude = '#{f['longitude']}', blob_id = '#{blob.id.to_s}', updated_at = '#{now}' where name = '#{f['name']}' and path = '#{f['path']}' and device_id = #{@device.id};\"\n puts \" SQL: \" + sql.background(:red)\n ActiveRecord::Base.connection.execute(sql)\n \n BlobsInCommit.find_or_create_by_blob_id_and_commit_id(blob.id, commit.id)\n \n \n #checkForObservers(dev_file)\n \n rescue => e\n puts \"Errors in updating file\" + e\n raise e\n end\n \n puts \"devfile updated!\"\n return dev_file\n end", "def createFileWithHeader \n # TODO - See about using !File.exist?(\"music_db.txt\")\n if File.exist?(\"music_db.txt\")\n else\n open('music_db.txt', 'w') { |z|\n }\n end \n end", "def create_file_set(file_node, file)\n attributes = {\n title: file_node.original_filename,\n file_metadata: [file_node],\n processing_status: \"in process\"\n }.merge(\n file.try(:container_attributes) || {}\n )\n persister.save(resource: FileSet.new(attributes))\n end", "def create\n self.write(@file_content)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add blobs from prev_commit to commit ignoring blobs in changed_files parameters: prev_commit The previous commit commit new commit changed_files list of files to ignore
def addUnchangedFilesToCommit(prev_commit, commit, changed_files) #:doc: # sql = "select devfiles.path, devfiles.name, devfiles.blob_id from devfiles, blobs, blobs_in_commits where blobs.devfile_id=devfiles.id and blobs_in_commits.blob_id=blobs.id and blobs_in_commits.commit_id=#{prev_commit.id};" # devfiles_of_prev_commit = ActiveRecord::Base.connection.execute(sql) # devfiles_of_prev_commit = Devfile.find_by_sql("select devfiles.path, devfiles.name, devfiles.blob_id from devfiles, blobs, blobs_in_commits where blobs.devfile_id=devfiles.id and blobs_in_commits.blob_id=blobs.id and blobs_in_commits.commit_id=#{prev_commit.id};") if devfiles_of_prev_commit.size > 0 ActiveRecord::Base.connection.execute("begin") now = DateTime.now devfiles_of_prev_commit.each do |df| if not changed_files.has_key?(df.path + df.name) begin sql = "insert into blobs_in_commits(blob_id, commit_id, created_at, updated_at) values('#{df['blob_id']}', '#{commit.id}', '#{now}', '#{now}');" ActiveRecord::Base.connection.execute(sql) rescue # do nothing end end end ActiveRecord::Base.connection.execute("commit") end end
[ "def addUnchangedFilesToCommit(prev_commit, commit, changed_files) #:doc:\n\n devfiles_of_prev_commit = Devfile.find_by_sql(\"select devfiles.path, devfiles.name, devfiles.blob_id from devfiles, blobs, blobs_in_commits where blobs.devfile_id=devfiles.id and blobs_in_commits.blob_id=blobs.id and blobs_in_commits.commit_id=#{prev_commit.id};\")\n if devfiles_of_prev_commit.size > 0\n ActiveRecord::Base.connection.execute(\"begin\")\n now = DateTime.now\n devfiles_of_prev_commit.each do |df|\n if not changed_files.has_key?(df.path + df.name)\n begin\n sql = \"insert into blobs_in_commits(blob_id, commit_id, created_at, updated_at) values('#{df['blob_id']}', '#{commit.id}', '#{now}', '#{now}');\"\n ActiveRecord::Base.connection.execute(sql)\n rescue\n # do nothing\n end\n end\n end\n ActiveRecord::Base.connection.execute(\"commit\")\n end\n end", "def changing(*files)\n support! :file_stats\n\n commits = CommitCollection.new\n each do |commit|\n commit_files = commit.added_files + commit.deleted_files + commit.modified_files\n commits << commit unless (commit_files & files).empty?\n end\n commits\n end", "def add_remove_commit_all(commit_msg)\n chdir do\n # modified, untracked\n changed_files().each do |c_file|\n add_file_command(c_file.first)\n end\n # deleted\n deleted_files().each do |d_file|\n remove_file(d_file.first)\n end\n # commit \n commit(commit_msg)\n end\n end", "def modified_files\n @modified_files ||= begin\n @modified_files = []\n\n rewritten_commits.each do |rewritten_commit|\n refs = \"#{rewritten_commit.old_hash} #{rewritten_commit.new_hash}\"\n @modified_files |= Overcommit::GitRepo.modified_files(refs: refs)\n end\n\n filter_modified_files(@modified_files)\n end\n end", "def modified_files\n @modified_files ||=\n Overcommit::GitRepo.modified_files(refs: \"#{previous_head} #{new_head}\")\n end", "def changed_files(last_commits)\n changed_files = []\n last_commits.each do |commit|\n files_in_commit = (`cd #{data_path} && git diff-tree --no-commit-id --name-status -r #{commit} && cd ..`).split(\"\\n\")\n commit_message = (`cd #{data_path} && git log --pretty=format:'%s' -1 -c #{commit} && cd ..`).gsub(/(\\n+)$/,'')\n files_in_commit.each do |changed_file|\n changed_files << [changed_file, commit_message].join(\"\\t\")\n end\n end\n changed_files.flatten\n end", "def push_files(files, commit_msg, prefix)\n ui.info(\"Applying your repository changes\")\n commit_prefix = \"#{prefix}:\"\n first_add = true\n files.each do |file|\n file_path = File.expand_path(file)\n if prefix == \"db\"\n file_name = file_path.split('/').last(3).join('/')\n else\n file_name = file_path.split('/').last(2).join('/')\n end\n Dir.chdir(Chef::Config[:git_repo]) do\n if(!first_add)\n commit_prefix += \",\"\n end\n first_add = false\n commit_prefix += file_name.split('/').last\n ui.info(\"- #{file_name}\")\n git.add(\"#{file_name}\")\n end\n end\n Dir.chdir(Chef::Config[:git_repo]) do\n push(commit_prefix, commit_msg)\n end\n end", "def files_changed_since sha: nil, branch: nil\n if branch\n commit = branch_commit branch\n else\n commit = lookup_commit sha\n end\n\n diff = @repo.index.diff commit\n\n files_from_diff diff\n end", "def getChangesOfCommit(commit_id = false)\n my_commit = ((commit_id == false and @repo.commits.size > 0) ? @repo.commits.first : @repo.commit(commit_id))\n if my_commit == nil\n return false\n end\n \n # get list of changed files and parse it\n @filelist = Hash.new\n options = {:r => true, :name_status => true, :no_commit_id => true}\n if @repo.commit(my_commit.sha).parents[0] == nil # if my_commit is the first commit\n options[:root] = true\n end\n changed_files_list = @git.diff_tree(options, my_commit.id).strip\n if changed_files_list.class == String and changed_files_list.length > 0\n changed_files_list.split(\"\\n\").each do |f|\n commit = my_commit\n operation = f[0,1] # D/M/A\n filepath = f[2..-1] # path+filename\n path = \"/\" + filepath.match(/^.+\\//).to_s # just path\n status = \"created\"\n if operation =~ /^D$/i # deleted\n # the file was deleted, so get the blob from the parent-commit\n commit = @repo.commit(my_commit.parents[0].sha)\n status = \"deleted\"\n elsif operation =~ /^M$/i # modified\n status = \"updated\"\n end\n blob = commit.tree/(filepath)\n\n #name = filepath.gsub(path[1..-1], '') #blob.name\n path = path.gsub(/\\/private\\/[0-9]+\\//,'')\n \n \n \n @filelist[\"/\" + filepath] = {\"uploaded\" => '1', \"status\" => status, \"blob_hash\" => blob.id, \"name\" => blob.name, \"path\" => \"/#{path}\", \"size\" => blob.size, \"filetype\" => blob.mime_type, \"filedate\" => @repo.commit(commit.sha).date.strftime('%T %F').to_s}\n \n \n end\n end\n\n if @filelist.size > 0\n return @filelist\n else\n return false\n end\n end", "def git_add_all_files\n files = `git ls-files`.split(\"\\n\").collect {|f| \"'#{f}'\"}\n index = 0\n while index < files.size\n block_size = 100\n to_process = files[index, block_size]\n index += block_size\n mysystem(\"git add --all --force #{to_process.join(' ')} 2> /dev/null > /dev/null\")\n end\n end", "def contents_added(git_commits)\n db_ids = {} # f(tree git id) -> {true, false} if it's in the db or not\n\n roots = git_commits.map(&:tree)\n root_ids = roots.map(&:id)\n db_roots = Set.new self.trees.select([:gitid, :repository_id]).\n where(gitid: root_ids).map(&:gitid)\n root_ids.each { |root_id| db_ids[root_id] = db_roots.include? root_id }\n roots = roots.reject { |root| db_ids[root.id] }\n\n new_trees = topological_sort roots do |tree|\n parents = tree.contents.select { |child| child.kind_of? Grit::Tree }\n unknown_ids = parents.map(&:id).reject { |p_id| db_ids.has_key? p_id }\n db_ids2 = Set.new self.trees.select([:gitid, :repository_id]).\n where(gitid: unknown_ids).map(&:gitid)\n unknown_ids.each { |p_id| db_ids[p_id] = db_ids2.include? p_id }\n\n parents = parents.reject { |parent| db_ids[parent.id] }\n { id: tree.id, next: parents }\n end\n\n new_blobs = new_trees.map { |tree|\n tree.contents.select { |child| child.kind_of? Grit::Blob }\n }.flatten.index_by(&:id).values\n new_ids = new_blobs.map(&:id)\n db_ids = Set.new self.blobs.select([:gitid, :repository_id]).\n where(gitid: new_ids).map(&:gitid)\n new_blobs.reject! { |blob| db_ids.include? blob.id }\n\n new_submodules = new_trees.map { |tree|\n tree.contents.select { |child| child.kind_of? Grit::Submodule }\n }.flatten.index_by { |sub| [sub.basename, sub.id] }.values\n new_ids = new_submodules.map(&:id)\n new_names = new_submodules.map(&:basename)\n db_keys = Set.new self.submodules.select([:gitid, :name, :repository_id]).\n where(gitid: new_ids, name: new_names).\n map { |sub| [sub.gitid, sub.name] }\n new_submodules.reject! { |sub| db_keys.include? [sub.id, sub.basename] }\n\n { blobs: new_blobs, submodules: new_submodules, trees: new_trees }\n end", "def altered_files; raw_changeset.files; end", "def get_committed_files\n # set the current branch name to be the current branch you're on --> need to check that this works as part of push\n curr_branch_name = `git rev-parse --abbrev-ref HEAD`\n\n # raw_sha_list lists all the local, unpushed commit SHAs from your current branch\n raw_sha_list = `git log --graph --pretty=format:'%H' #{curr_branch_name}`\n\n committed_files = []\n # loop through the raw_sha_list and push properly formatted SHAs into the all_shas arr\n raw_sha_list.each_line { |sha|\n # using the .tr method on the sha makes a copy of the sha and replaces instances that matches with the to_str (second arg),\n # unless the range starts with a ^ carrot, in which case, it replaces on matches outside the range\n curr_sha = sha.tr('^A-Za-z0-9', '')\n\n # this `git diff-tree --no-commit-id --name-only -r <SHA>` will list the files of an individual commit when you add the SHA\n # on each iteration, set the changed_files variable to be the list of files from a particular commit, based its SHA\n changed_files = `git diff-tree --no-commit-id --name-only -r #{curr_sha}`\n\n # loop over the changed_files and add in each file that's part of a commit and add into the committed_files arr\n changed_files.each_line { |file|\n # remove any trailing whitespace from the file name and add into our arr\n committed_files << file.rstrip()\n }\n }\n # return the final, no-repeat array of committed files in this push\n return committed_files.uniq\nend", "def modified_files\n staged = squash?\n refs = 'HEAD^ HEAD' if merge_commit?\n @modified_files ||= Overcommit::GitRepo.modified_files(staged: staged, refs: refs)\n end", "def modified_files\n files.reject do |github_file|\n github_file.status == FILE_REMOVED_STATUS\n end\n end", "def previously_changed_files\n `git show --pretty=\"format:\" --name-only`.split(\"\\n\")\n end", "def fetching_other_file_information commit, obj, raw_commit\n commit.diff_parent.stats[:files].map do |file_path, changes|\n clone_obj = raw_commit.clone\n clone_obj.changes = {file_path => other_file_info(obj, file_path, changes)}\n clone_obj\n end\n end", "def getChangesOfCommit(commit_id = false)\n my_commit = ((commit_id == false and @repo.commits.size > 0) ? @repo.commits.first : @repo.commit(commit_id))\n if my_commit == nil\n return false\n end\n \n # get list of changed files and parse it\n @filelist = Hash.new\n options = {:r => true, :name_status => true, :no_commit_id => true}\n if @repo.commit(my_commit.sha).parents[0] == nil # if my_commit is the first commit\n options[:root] = true\n end\n changed_files_list = @git.diff_tree(options, my_commit.id).strip\n if changed_files_list.class == String and changed_files_list.length > 0\n changed_files_list.split(\"\\n\").each do |f|\n commit = my_commit\n operation = f[0,1] # D/M/A\n filepath = f[2..-1] # path+filename\n path = \"/\" + filepath.match(/^.+\\//).to_s # just path\n status = \"created\"\n if operation =~ /^D$/i # deleted\n # the file was deleted, so get the blob from the parent-commit\n commit = @repo.commit(my_commit.parents[0].sha)\n status = \"deleted\"\n elsif operation =~ /^M$/i # modified\n status = \"updated\"\n end\n blob = commit.tree/(filepath)\n @filelist[\"/\" + filepath] = {\"status\" => status, \"blob_hash\" => blob.id, \"name\" => blob.name, \"path\" => path, \"size\" => blob.size, \"filetype\" => blob.mime_type, \"filedate\" => @repo.commit(commit.sha).date.strftime('%T %F').to_s}\n \n if @vR_branches[blob.id]\n @filelist[\"/\" + filepath].merge!({\"file_origin\" => @vR_branches[blob.id]})\n end\n \n end\n end\n\n if @filelist.size > 0\n return @filelist\n else\n return false\n end\n end", "def prev_commit\n init_commits\n @prev_commit\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if commit is missing (some of) it's thumbnails. Sends xmppmessages to the device for the missing thumbnails. parameters: commit the commit in question
def checkForThumbs(commit) #:doc: prev_commit_blob_ids = Array.new prev_commit = Commit.find(:first, :conditions => ["id = ?", commit.previous_commit_id]) if prev_commit prev_commit.blobs.find_each(:batch_size => 1500) do |pb| prev_commit_blob_ids.push(pb.id) end end blobs_without_thumb = Array.new new_thumbs = 0 new_thumbs_without_thumb = 0 prev_thumbs_ok = true commit.blobs.find_each(:batch_size => 1500) do |blob| if blob.thumbnail_name == nil and not prev_commit_blob_ids.include?(blob.id) and not blobs_without_thumb.include?(blob.blob_hash) blobs_without_thumb.push(blob.blob_hash) new_thumbs_without_thumb += 1 new_thumbs += 1 elsif blob.thumbnail_name == nil and not blobs_without_thumb.include?(blob.blob_hash) blobs_without_thumb.push(blob.blob_hash) prev_thumbs_ok = false elsif blob.thumbnail_name != nil and not prev_commit_blob_ids.include?(blob.id) new_thumbs += 1 end end if blobs_without_thumb.size == 0 # we have all thumbs, do nothing return elsif prev_thumbs_ok and new_thumbs_without_thumb == new_thumbs # all new thumbs missing XmppHelper::sendXmppMessage(@device.xmppname, "thumbs " + commit.commit_hash) else # some thumbs are missing. get them. i = 0 blobs_per_message = 100 message = blobs_without_thumb[i...blobs_per_message] while message != nil do XmppHelper::sendXmppMessage(@device.xmppname, "thumbs " + commit.commit_hash + " " + message.join(" ")) i += blobs_per_message message = blobs_without_thumb[i...blobs_per_message] end end end
[ "def general_comment?() commit_file_id.nil? end", "def check_row\n err_arr = []\n begin\n if @row_hash[\"ao_ref_id\"].nil? && @row_hash[\"ao_uri\"].nil?\n err_arr.push I18n.t(\"bulk_import.error.no_uri_or_ref\")\n end\n end\n normalize_publish_column(@row_hash)\n normalize_publish_column(@row_hash, 'digital_object_link_publish')\n normalize_publish_column(@row_hash, 'thumbnail_publish')\n err_arr.join(\"; \")\n end", "def addUnchangedFilesToCommit(prev_commit, commit, changed_files) #:doc:\n# sql = \"select devfiles.path, devfiles.name, devfiles.blob_id from devfiles, blobs, blobs_in_commits where blobs.devfile_id=devfiles.id and blobs_in_commits.blob_id=blobs.id and blobs_in_commits.commit_id=#{prev_commit.id};\"\n# devfiles_of_prev_commit = ActiveRecord::Base.connection.execute(sql)\n#\n devfiles_of_prev_commit = Devfile.find_by_sql(\"select devfiles.path, devfiles.name, devfiles.blob_id from devfiles, blobs, blobs_in_commits where blobs.devfile_id=devfiles.id and blobs_in_commits.blob_id=blobs.id and blobs_in_commits.commit_id=#{prev_commit.id};\")\n if devfiles_of_prev_commit.size > 0\n ActiveRecord::Base.connection.execute(\"begin\")\n now = DateTime.now\n devfiles_of_prev_commit.each do |df|\n if not changed_files.has_key?(df.path + df.name)\n begin\n sql = \"insert into blobs_in_commits(blob_id, commit_id, created_at, updated_at) values('#{df['blob_id']}', '#{commit.id}', '#{now}', '#{now}');\"\n ActiveRecord::Base.connection.execute(sql)\n rescue\n # do nothing\n end\n end\n end\n ActiveRecord::Base.connection.execute(\"commit\")\n end\n end", "def fix_thumbnails\n MessageQueue.execute do\n Photo.deleted_at_nil.s3_key_nil.with_photo.find_each do |photo|\n \n logit \"Attempting to fix thumbnail #{thumb.id}\"\n if thumb.staging?\n thumb.upload\n else\n thumb.stage!\n end\n sleep(0.5) # For uploader message publishing\n end\n end\n end", "def satisfied?(commit)\n false\n end", "def normal_commit?\n !ARGV[1] || ARGV[1] == 'message'\n end", "def file_comment?() !commit_file_id.nil? end", "def commit_msg_empty?(commit_msg_file)\n File.open(commit_msg_file, 'r') do |f|\n f.readlines.each do |line|\n strip_line = line.strip\n return false if (!strip_line.empty? && !strip_line.start_with?('#'))\n end\n end\n true\nend", "def no_new_commit\n puts red(\"No new commit found\")\n end", "def existe_commit? (commit_hash)\n `git --git-dir='#{@path_to_repo}' rev-list #{commit_hash} 2>&1`; existe=$?.success?\n existe\n end", "def message_exists?(message)\n blank? message.rpartition(commit_msg_start).first\nend", "def nothing_to_commit?\n @git.status do |file, status|\n return false unless status.empty?\n end\n return true\n end", "def breaking_change?(commit)\n !commit.fetch(\"message\").match(/^[a-z]*!/).nil?\nend", "def check_do_row\n err_arr = []\n begin\n err_arr.push I18n.t('plugins.aspace-import-excel.error.ref_id_miss') if @row_hash['ao_ref_id'].blank?\n obj_link = @row_hash['digital_object_link']\n thumb = @row_hash['thumbnail'] || @row_hash['Thumbnail']\n err_arr.push I18n.t('plugins.aspace-import-excel.error.dig_info_miss') if @row_hash['digital_object_link'].blank? && thumb.blank?\n end\n v = @row_hash['publish']\n v = v.strip if !v.blank?\n @row_hash['publish'] = (v == '1')\n err_arr.join('; ')\n end", "def skip_existing?(sha, clean)\n if @gitlog.key? sha\n unless clean\n print \"\\n#{sha} already exists in gitlog.json, skipping\"\n return true\n end\n puts \"INFO: commit #{sha} already exists in gitlog.json. Will be overwritten.\"\n end\n return false\n end", "def addUnchangedFilesToCommit(prev_commit, commit, changed_files) #:doc:\n\n devfiles_of_prev_commit = Devfile.find_by_sql(\"select devfiles.path, devfiles.name, devfiles.blob_id from devfiles, blobs, blobs_in_commits where blobs.devfile_id=devfiles.id and blobs_in_commits.blob_id=blobs.id and blobs_in_commits.commit_id=#{prev_commit.id};\")\n if devfiles_of_prev_commit.size > 0\n ActiveRecord::Base.connection.execute(\"begin\")\n now = DateTime.now\n devfiles_of_prev_commit.each do |df|\n if not changed_files.has_key?(df.path + df.name)\n begin\n sql = \"insert into blobs_in_commits(blob_id, commit_id, created_at, updated_at) values('#{df['blob_id']}', '#{commit.id}', '#{now}', '#{now}');\"\n ActiveRecord::Base.connection.execute(sql)\n rescue\n # do nothing\n end\n end\n end\n ActiveRecord::Base.connection.execute(\"commit\")\n end\n end", "def photo_exist?(photo) \n\t### \n\t# compare sha of photo with the sha tag of EVERY photo that we've\n\t# already uploaded. \n\t# \thow do we do that? \n\t# \t\t \n\t# return true if that sha already exits as a tag. \n\t# return false if it dunna. \n\tsha = checksum_photo(photo) \n\t####\n\t# \t\nend", "def save_upload\n @entry = Entry.new(params[:entry])\n\n @upload = small_thumb = nil\n\n # resize the upload into three images\n begin\n @upload = Upload.new(params[:upload])\n @upload.data = Resize.resize_and_watermark(@upload.data, 1024, 768)\n\n small_thumb = Upload.copy_from(@upload)\n small_thumb.data = Resize.resize_and_watermark(small_thumb.data, 160, 120)\n rescue\n logger.error \"Could not create thumbnail: #{$!}\"\n return redirect_to :action=>:index\n end\n\n begin\n Entry.transaction do\n logger.info \"Saving entry\"\n if @entry.save! \n logger.info \"Entry saved\"\n @entry = Entry.find_by_id(@entry.id)\n logger.info \"Refetched entry: #{@entry}\"\n \n logger.info \"Setting entry for @upload: #{@upload}\"\n @upload.entry = @entry\n logger.info \"Setting entry for small thumb: #{small_thumb}\"\n small_thumb.entry = @entry\n\n logger.info \"Saving upload\"\n if @upload.save!\n \n logger.info \"Saving small thumb\"\n if small_thumb.save!\n @entry.upload = @upload\n @entry.small_thumbnail= small_thumb\n @entry.save!\n\n # send the notification email\n begin\n PeeMailer.deliver_upload_received(@upload)\n rescue\n logger.error \"Could not deliver email: {$!}\"\n end\n\n flash[:notice] = 'Thank you for your upload. After it is approved, it will be available on the live site'\n return redirect_to :action=>:index\n end\n end\n end\n end\n rescue\n msg = \"Could not save something: #{$!}\"\n logger.error msg\n \n flash[:error] = msg\n return redirect_to :action=>:index\n end\n\n end", "def kde_commits(commit_id,message,silent)\n warning = ''\n emailAddy = `git log #{commit_id} --encoding=UTF-8 -n 1 --pretty='format:%ae'`\n if not validate_email_domain(emailAddy) then\n warning = \"[BAD EMAIL] \"\n end\n from = `git log #{commit_id} --encoding=UTF-8 -n 1 --pretty='format:%an <%ae>'`\n subject = `git log #{commit_id} --encoding=UTF-8 -n 1 --pretty='format:%h'` + ': ' + `git log #{commit_id} --encoding=UTF-8 -n1 --pretty='format:%s'`[0,50]\n subject = \"#{warning}#{subject}\"\n\n if (!(silent && from == \"Script Kiddy <scripty@kde.org>\")) then\n send_email(from, \"kde-commits@kde.org\", \"#{subject}\\nX-Commit-Directories: (0) #{SVN_LOCATION}\", \"#{message}\")\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that all necessary http parameters are given. parameters: username, password, devicename and dev_type. port is optionla, but if given must be a number. Returns false is some of the parameters is missing or is in wrong form. Returns true if parameters are fine. register uses this method.
def check_params #:doc: if params[:username] !~ /.{1,}/ or params[:password] !~ /.{1,}/ or params[:devicename] !~ /.{1,}/ or params[:dev_type] !~ /.{1,}/ or (params[:port] != nil and params[:port] !~ /\d{1,10}/) return false else return true end end
[ "def check_params\n # For each key,value in GLOBAL VAR **PARAMS**.\n PARAMS.each do |param, method|\n # Next if there isn't param in the request of client\n next unless params[param]\n # Check the *param* with *method*\n unless send(method, params[param])\n @error_object = \"Param #{param} is wrong, #{method} failed\"\n return false\n end\n end\n true\n end", "def valid_http_auth?\n controller.authenticate_with_http_basic do |login, password|\n if !login.blank? && !password.blank?\n send(\"#{login_field}=\", login)\n send(\"#{password_field}=\", password)\n return valid?\n end\n end\n \n false\n end", "def read_and_validate_params\n if @name_args.length < 1\n show_usage\n exit 1\n end\n\n if config[:hostname].nil? ||\n config[:username].nil? ||\n config[:flavor].nil? ||\n config[:password].nil? ||\n config[:main_network_adapter].nil?\n show_usage\n exit 1\n end\n\n if config[:guest_dhcp].eql? false\n if config[:guest_ip].nil? ||\n config[:guest_gateway].nil? ||\n config[:guest_netmask].nil? ||\n config[:guest_nameserver].nil?\n ui.fatal \"When using a static IP, you must specify the IP, Gateway, Netmask, and Nameserver\"\n exit 1\n end\n end\n\n end", "def portus?\n username == \"portus\"\n end", "def verify_parameters\n # TODO: rails 3 and activemodel validation\n parts = (params[:mask].to_s.split('@', 2) + [params[:nick], params[:url]])\n if parts.length != 4 || params.any?(&:blank?)\n render :text => \"Invalid submission\", :status => 400\n return false\n end\n end", "def is_valid_parameter?(options)\n platforms = get_platforms\n if options[:param_name] == \"os\"\n if platforms.has_key?(options[:param_value])\n true\n else\n false\n end\n elsif options[:param_name] == \"version\"\n if platforms[\"#{options[:os_value]}\"].include?(options[:param_value])\n true\n else\n false\n end\n elsif options[:param_name] == \"arch\"\n if options[:param_value] == \"x86_64\" || options[:param_value] == \"i386\"\n true\n else\n false\n end\n end\nend", "def valid_user?\n params['username'] && params['password']\n end", "def validate\n [@user,@pass,@host,@db].each { |param|\n raise \"Insufficient parameters to connect to MySQL Database!\" if param.nil?\n }\n end", "def validate_api_param\n set_valid(true)\n if @api_key.nil? || @api_key.empty? || @password.nil? || @password.empty?\n add_error_code(Constants::API_KEY_INVALID_ERROR_CODE)\n set_valid(false)\n end\n if @rapid_endpoint.nil? || @rapid_endpoint.empty?\n add_error_code(Constants::LIBRARY_NOT_HAVE_ENDPOINT_ERROR_CODE)\n set_valid(false)\n end\n if @is_valid\n begin\n parser_endpoint_to_web_url\n unless @list_error.nil?\n @list_error.clear\n end\n set_valid(true)\n @logger.info \"Initiate client using [#{@web_url}] successful!\" if @logger\n rescue => e\n @logger.error \"Error setting Rapid endpoint #{e.backtrace.inspect}\" if @logger\n set_valid(false)\n add_error_code(Constants::LIBRARY_NOT_HAVE_ENDPOINT_ERROR_CODE)\n end\n else\n @logger.warn 'Invalid parameter passed to Rapid client' if @logger\n end\n end", "def validates?\n # include the params to validate our request\n request_params = denormalize params.merge({\n :Comando => \"validar\",\n :Token => @token || PagSeguro.config[\"authenticity_token\"]\n }).dup\n\n return true if PagSeguro.developer?\n\n # do the request\n uri = URI.parse(API_URL)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n request = Net::HTTP::Post.new(uri.path)\n request.set_form_data request_params\n response = http.start {|r| r.request request }\n (response.body =~ /VERIFICADO/) != nil\n end", "def validateurl(myparameters)\n myparameters.each do |columnname, value|\n if columnname.to_s == \"administratorname\"\n existcheck = Administrator.all.where(\"name = '\" + value + \"'\").ids\n else\n existcheck = Course.all.where(columnname.to_s + \" = '\" + value + \"'\").ids\n end\n #If the url parameters dont exist in the database, size of existcheck should be 0\n #Throw a 404 error\n if existcheck.size() == 0\n respond_to do |format|\n format.html { render :file => \"#{Rails.root}/public/404\", :layout => false, :status => :not_found }\n format.xml { head :not_found }\n format.any { head :not_found }\n end\n return false\n end\n end\n return true\n end", "def allowed_http?\n port_protocol_allowed('80')\n end", "def check_port(v)\n return v unless v\n\n if @opaque\n raise InvalidURIError,\n \"can not set port with registry or opaque\"\n elsif !v.kind_of?(Integer) && parser.regexp[:PORT] !~ v\n raise InvalidComponentError,\n \"bad component(expected port component): #{v.inspect}\"\n end\n\n return true\n end", "def validate_send_params\n @api_id = env.params['auth_key']\n @data = env.params['data']\n @channel = env.params['channel']\n raise AuthError.new(\"api_id is mandatory\") if @api_id.nil?\n raise AuthError.new(\"data is mandatory\") if @data.nil?\n raise AuthError.new(\"channel is mandatory\") if @channel.nil?\n raise AuthError.new(\"no signature\") unless env.params['auth_signature']\n end", "def hikvision_validate_device\n response = connect_to_hikvision_device(self.server_ip, self.server_port, self.username, self.password)\n if(validate_http_response(response))\n return true\n else\n raise 'Failed to connect to HikVision device.'\n end\n end", "def username_and_password?\n params[:username].present? && params[:password].present?\n end", "def hikvision_validate_device\n response = connect_to_hikvision_device(self.server_ip, self.server_port, self.username, self.password)\n if (validate_http_response(response))\n return true\n else\n raise 'Failed to connect to HikVision device.'\n end\n end", "def validate_registeration_params\n\n return success if @client_token.registration_done?\n\n @airdrop_amount = @airdrop_amount.present? ? BigDecimal.new(@airdrop_amount) : @airdrop_amount\n @ost_to_bt = @ost_to_bt.present? ? BigDecimal.new(@ost_to_bt) : @ost_to_bt\n @number_of_users = @number_of_users.to_i\n\n return error_with_data(\n 'e_sam_8',\n 'invalid_api_params',\n GlobalConstant::ErrorAction.default\n ) if @ost_to_bt.blank? || @bt_to_mint < 0\n\n return error_with_data(\n 'e_sam_11',\n 'invalid_api_params',\n GlobalConstant::ErrorAction.default\n ) if GlobalConstant::Base.sandbox_sub_environment? &&\n (@number_of_users < 0 || @airdrop_amount.blank? || @airdrop_amount < 0 || @airdrop_user_list_type.blank?)\n\n success\n\n end", "def validate_default_transport\n validate_app_name &&\n validate_transport_type &&\n validate_api_key &&\n validate_env &&\n validate_log_level &&\n validate_mode_type\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executes queries using the replica database. Fails over to primary if no replica is found. if you want to execute a block of code on the replica you can go: Account.on_replica do Account.first end the first account will be found on the replica DB For oneliners you can simply do Account.on_replica.first
def on_replica(&block) on_primary_or_replica(:replica, &block) end
[ "def on_replica(&block)\n on_master_or_replica(:replica, &block)\n end", "def enable_replica\n begin\n ActiveRecord::Base.connection.enable_replica\n yield\n rescue Makara::Errors::AllConnectionsBlacklisted => e\n yield\n ensure\n ActiveRecord::Base.connection.disable_replica\n end\n end", "def execute\n init_waiter\n prepare_replication\n\n until termination_requested do\n begin\n RR.logger.debug 'RUNNER - Starting replication cycle'\n execute_once\n if !@last_run_successfull && !@last_run_successfull.nil?\n RR.logger.info 'RUNNER - Connection successfully established again'\n end\n RR.logger.debug 'RUNNER - Finished replication cycle successfully'\n @last_run_successfull = true\n rescue Exception => e\n # Check if it's a connection problem\n if (e.is_a?(PG::Error) && e.to_s =~ %r/could not connect/) || e.to_s =~ %r/no connection to '(.*)' database/\n if @last_run_successfull\n RR.logger.error 'RUNNER - Lost connection to one database, terminating session.'\n @last_run_successfull = false\n end\n \n clear_session\n RR.logger.debug 'RUNNER - Databases disconnected, a new one will be built when needed...'\n else\n RR.logger.error(\"Exception caught: #{e}\")\n end\n end\n pause_replication\n end\n end", "def get_any_replica(id, options = GetAnyReplicaOptions.new) end", "def select_replica(user)\n # If the user's `min_lsn` is `NULL` then they haven't performed an operation\n # yet, and we don't yet know if we can use a replica yet. Default to the\n # primary.\n return :default if user.min_lsn.nil?\n\n # exclude :default at the zero index\n replica_names = DB.servers[1..-1].map { |name| name.to_s }\n\n res = DB[Sequel.lit(<<~eos), replica_names, user.min_lsn]\n SELECT name\n FROM replica_statuses\n WHERE name IN ?\n AND pg_wal_lsn_diff(last_lsn, ?) >= 0;\n eos\n\n # If no candidates are caught up enough, then go to the primary.\n return :default if res.nil? || res.empty?\n\n # Return a random replica name from amongst the candidates.\n candidate_names = res.map { |res| res[:name].to_sym }\n candidate_names.sample\nend", "def createReadReplica\n\t\t\tdb_node_name = MU::MommaCat.getResourceName(@db['read_replica']['name'])\n\t\t\t\n\t\t\t@db['read_replica']['identifier'] = getName(db_node_name, type: \"dbidentifier\")\n\t\t\t@db['read_replica']['source_identifier'] = @db['identifier'] if !@db['read_replica']['source_identifier']\n\n\t\t\treplica_config = {\n\t\t\t\tdb_instance_identifier: @db['read_replica']['identifier'],\n\t\t\t\tsource_db_instance_identifier: @db['read_replica']['source_identifier'],\n\t\t\t\tauto_minor_version_upgrade: @db['read_replica']['auto_minor_version_upgrade'],\n\t\t\t\tstorage_type: @db['read_replica']['storage_type'],\n\t\t\t\tpublicly_accessible: @db['read_replica']['publicly_accessible'],\n\t\t\t\tport: @db['read_replica']['port'],\n\t\t\t\tdb_instance_class: @db['read_replica']['size'],\n\t\t\t\ttags: []\n\t\t\t}\n\n\t\t\tif @db['read_replica']['region'] != @db['region']\n\t\t\t\t# Need to deal with case where read replica is created in different region than source DB instance.\n\t\t\t\t# Will have to create db_subnet_group_name in different region.\n\t\t\t\t# Read replica deployed in the same region as the source DB instance will inherit from source DB instance \n\t\t\tend\n\n\t\t\t\n\t\t\treplica_config[:iops] = @db['read_replica'][\"iops\"] if @db['read_replica']['storage_type'] == \"io1\"\n\n\t\t\tMU::MommaCat.listStandardTags.each_pair { |name, value|\n\t\t\t\treplica_config[:tags] << { key: name, value: value }\n\t\t\t}\n\n\t\t\tattempts = 0\n\t\t\tbegin\n\t\t\t\tMU.log \"Read replica RDS config: #{replica_config}\", MU::DEBUG\n\t\t\t\tMU.log \"Creating read replica database instance #{@db['read_replica']['identifier']} from #{@db['read_replica']['source_identifier']} database instance\", details: replica_config\n\t\t\t\tresp = MU.rds(@db['read_replica']['region']).create_db_instance_read_replica(replica_config)\n\t\t\trescue Aws::RDS::Errors::InvalidParameterValue => e\n\t\t\t\tif attempts < 5\n\t\t\t\t\tMU.log \"Got #{e.inspect} creating #{@db['read_replica']['identifier']}, will retry a few times in case of transient errors.\", MU::WARN\n\t\t\t\t\tattempts += 1\n\t\t\t\t\tsleep 10\n\t\t\t\t\tretry\n\t\t\t\telse\n\t\t\t\t\tMU.log \"Exhausted retries to create DB read replica #{@db['read_replica']['identifier']}, giving up\", MU::ERR, details: e.inspect\n\t\t\t\t\traise \"Exhausted retries to create DB read replica #{@db['read_replica']['identifier']}, giving up\"\n\t\t\t\tend\n\t\t\tend\n\n\t\t\tbegin # this ends in an ensure block that cleans up if we die\n\t\t\t\tdatabase = MU::Database.getDatabaseById(@db['read_replica']['identifier'], region: @db['region'])\n\t\t\t\t# Calling this a second time after the DB instance is ready or DNS record creation will fail.\n\t\t\t\twait_start_time = Time.now\n\n\t\t\t\tMU.rds(@db['region']).wait_until(:db_instance_available, db_instance_identifier: @db['read_replica']['identifier']) do |waiter|\n\t\t\t\t# Does create_db_instance_read_replica implement wait_until_available ?\n\t\t\t\t\twaiter.max_attempts = nil\n\t\t\t\t\twaiter.before_attempt do |attempts|\n\t\t\t\t\t\tMU.log \"Waiting for Read Replica RDS database #{@db['read_replica']['identifier']} to be ready...\", MU::NOTICE if attempts % 10 == 0\n\t\t\t\t\tend\n\t\t\t\t\twaiter.before_wait do |attempts, resp|\n\t\t\t\t\t\tthrow :success if resp.data.db_instances.first.db_instance_status == \"available\"\n\t\t\t\t\t\tthrow :failure if Time.now - wait_start_time > 2400\n\t\t\t\t\tend\n\t\t\t\tend\n\n\t\t\t\tdatabase = MU::Database.getDatabaseById(@db['read_replica']['identifier'], region: @db['region'])\n\n\t\t\t\tMU::DNSZone.genericDNSEntry(@db['read_replica']['identifier'], \"#{database.endpoint.address}.\", MU::Database, sync_wait: @db['read_replica']['dns_sync_wait'])\n\t\t\t\tif !@db['read_replica']['dns_records'].nil?\n\t\t\t\t\t@db['read_replica']['dns_records'].each { |dnsrec|\n\t\t\t\t\t\tdnsrec['name'] = @db['read_replica']['identifier'].downcase if !dnsrec.has_key?('name')\n\t\t\t\t\t}\n\t\t\t\tend\n\t\t\t\tMU::DNSZone.createRecordsFromConfig(@db['read_replica']['dns_records'], target: database.endpoint.address)\n\n\t\t\t\tMU::Database.notifyDeploy(@db['read_replica']['name'], @db['read_replica']['identifier'], @db['password'], \"read_replica\", region: @db['read_replica']['region'])\n\t\t\t\tMU.log \"Database instance #{@db['read_replica']['identifier']} is ready to use\"\n\t\t\t\tdone = true\n\t\t\tensure\n\t\t\t\tif !done and database\n\t\t\t\t\tMU::Cleanup.terminate_rds_instance(database, region: @db['read_replica']['region'])\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn @db['read_replica']['identifier']\n\t\tend", "def active_record_replica_read_from_primary?\n ActiveRecordReplica.read_from_primary? ||\n open_transactions.positive? && !ActiveRecordReplica.ignore_transactions?\n end", "def execute_once\n session.refresh\n timeout = session.configuration.options[:database_connection_timeout]\n terminated = TaskSweeper.timeout(timeout) do |sweeper|\n run = ReplicationRun.new session, sweeper\n run.run\n end.terminated?\n\n if terminated\n message = 'RUNNER - Replication run timed out'\n RR.logger.error(message)\n raise message\n end\n end", "def replica_db_synced_with_master_db?(replica_host, agents)\n # Save a beaker host_hash[:vmhostname], set it to the supplied host_name param,\n # and then set it back to the original at the end of the ensure. The :vmhostname\n #overrides the host.hostname, and nothing should win out over it.\n original_host_name = host.host_hash[:vmhostname]\n begin\n host.host_hash[:vmhostname] = replica_host.hostname\n\n replica_nodes = query_nodes.body\n replica_catalogs = query_catalogs.body\n replica_facts = query_facts.body\n replica_reports = query_reports.body\n ensure\n host.host_hash[:vmhostname] = original_host_name\n end\n master_nodes = query_nodes.body\n master_catalogs = query_catalogs.body\n master_facts = query_facts.body\n master_reports = query_reports.body\n\n nodes_synced = nodes_synced?(agents, replica_nodes, master_nodes)\n catalogs_synced = catalogs_synced?(agents, replica_catalogs, master_catalogs)\n facts_synced = facts_synced?(replica_facts, master_facts)\n reports_synced = reports_synced?(agents, replica_reports, master_reports)\n\n errors = ''\n errors << \"Nodes not synced\\r\\n\" unless nodes_synced\n errors << \"Catalogs not synced\\r\\n\" unless catalogs_synced\n errors << \"Facts not synced\\r\\n\" unless facts_synced\n errors << \"Reports not synced\\r\\n\" unless reports_synced\n\n host.logger.warn(errors.chomp) unless errors.empty?\n errors.empty?\n end", "def execute\n initializer = ReplicationInitializer.new session\n initializer.prepare_replication\n puts \"Preparation completed.\"\n end", "def run\n $stdout.write \"-\" if session.configuration.options[:replication_trace]\n\n RR.heartbeat(session.configuration.options[:heartbeat_file])\n\n return unless [:left, :right].any? do |database|\n next false if session.configuration.send(database)[:mode] == :slave\n changes_pending = false\n RR.limited_execute(session.configuration.options[:database_connection_timeout]) do\n changes_pending = session.send(database).select_one(\n \"select id from #{session.configuration.options[:rep_prefix]}_pending_changes limit 1\"\n ) != nil\n end\n changes_pending\n end\n\n # Apparently sometimes above check for changes takes already so long, that\n # the replication run times out.\n # Check for this and if timed out, return (silently).\n return if sweeper.terminated?\n\n success = false\n begin\n replicator # ensure that replicator is created and has chance to validate settings\n break_on_terminate = false\n\n loop do\n $stdout.write \".\" if session.configuration.options[:replication_trace]\n RR.heartbeat(session.configuration.options[:heartbeat_file])\n\n break unless loaders.update # ensure the cache of change log records is up-to-date\n\n loop do\n begin\n diff = load_difference\n break unless diff.loaded?\n break_on_terminate = sweeper.terminated? || $rubyrep_shutdown\n break if break_on_terminate\n if diff.type != :no_diff and not event_filtered?(diff) # Should probably be :no_change, :no_diff doesn't exist\n replicator.replicate_difference diff\n end\n rescue Exception => e\n if e.message =~ /violates foreign key constraint|foreign key constraint fails/i and !diff.second_chance?\n # Note:\n # Identifying the foreign key constraint violation via regular expression is\n # database dependent and *dirty*.\n # It would be better to use the ActiveRecord #translate_exception mechanism.\n # However as per version 3.0.5 this doesn't work yet properly.\n\n diff.second_chance = true\n second_chancers << diff\n else\n begin\n helper.log_replication_outcome diff, e.message, e.class.to_s + \"\\n\" + e.backtrace.join(\"\\n\")\n rescue Exception => _\n # if logging to database itself fails, re-raise the original exception\n raise e\n end\n end\n end\n\n break if break_on_terminate\n end\n end\n success = true\n ensure\n if sweeper.terminated?\n helper.finalize false\n session.disconnect_databases\n else\n helper.finalize success\n end\n end\n end", "def reconnect\n @read_replica.reconnect\n @primary.reconnect\n end", "def with_primary(retries = max_retries, &block)\n if node = nodes.find(&:primary?)\n begin\n node.ensure_primary do\n return yield node.apply_auth(auth)\n end\n rescue Errors::ConnectionFailure, Errors::ReplicaSetReconfigured\n # Fall through to the code below if our connection was dropped or the\n # node is no longer the primary.\n end\n end\n\n if retries > 0\n # We couldn't find a primary node, so refresh the list and try again.\n warning(\" MOPED: Retrying connection to primary for replica set #{inspect}\")\n sleep(retry_interval)\n refresh\n with_primary(retries - 1, &block)\n else\n raise(\n Errors::ConnectionFailure,\n \"Could not connect to a primary node for replica set #{inspect}\"\n )\n end\n end", "def create\n status = mongo(\"#{get_client}\", \"--quiet\", \"--eval\", \"rs.status().ok\")\n replica_members = {}\n\n # has replica already been initialized ?\n if Integer(status) == 1\n nb_members = mongo(\"#{get_client}\", \"--quiet\", \"--eval\", \"rs.status().members.length\")\n # retrieve existing replica informations\n for i in 0..(Integer(nb_members) - 1)\n key_member = mongo(\"#{get_client}\", \"--quiet\", \"--eval\", \"rs.status().members[#{i}].name\").tr(\"\\n\", '')\n value_health = mongo(\"#{get_client}\", \"--quiet\", \"--eval\", \"rs.status().members[#{i}].health\").tr(\"\\n\", '')\n\n replica_members[key_member] = value_health\n end\n else\n Puppet.debug(\"REPLICASET-DEBUG: Replica initialisation...\") if active_debug\n mongo(\"#{get_client}\", \"--quiet\", \"--eval\", \"rs.initiate()\")\n end\n\n if resource[:members].is_a? Array\n resource[:members].each do |member|\n self.add_member_to_replicaset(replica_members, member)\n end\n else\n self.add_member_to_replicaset(replica_members, resource[:members])\n end\n end", "def transaction(options = {}, &block)\n return super unless replica_pools_enabled?\n self.with_leader { super }\n end", "def run_on_db(use_slave = nil)\n# logger.debug(\"checking conn. use_slave? #{use_slave} in trans? #{Thread.current['open_transactions']}\") if logger && logger.debug\n if (use_slave && \n connection.is_a?(ConnectionAdapters::MysqlReplicationAdapter) && \n (Thread.current['open_transactions'] || 0) == 0)\n\n connection.load_balance_query { yield }\n else\n yield\n end\n end", "def with_primary(&block)\n if node = nodes.find(&:primary?)\n begin\n node.ensure_primary do\n return yield(node)\n end\n rescue Errors::ConnectionFailure, Errors::ReplicaSetReconfigured\n end\n end\n raise Errors::ConnectionFailure, \"Could not connect to a primary node for replica set #{inspect}\"\n end", "def execute(node)\n node.process(operation) do |reply|\n # Avoid LocalJumpError\n ret = nil\n if reply.unauthorized? && node.credentials.key?(@database)\n node.connection do |conn|\n username, password = node.credentials[@database]\n if username && password\n conn.login(operation.database, username, password)\n ret = execute(node)\n end\n end\n end\n\n if ret.nil?\n if operation.failure?(reply)\n raise operation.failure_exception(reply)\n end\n\n ret = operation.results(reply)\n end\n\n ret\n end\n end", "def check_replication\n secondary_states = ReplicaResult.all(@connection)\n master_state = @connection.execute(MASTER_LOG_LOCATION_QUERY)\n\n report!(secondary_states, master_state)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable saving of unknown barewords. With this, the only way to terminate parsing is to hit the end of the parse or with . You can retrieve the saved words from saved.
def save_unknown! @saved = [] end
[ "def preload\n !words_list.empty?\n end", "def save\n blowup_keywords\n super\n end", "def save_unmatched_words # :nodoc:\n tokens = phrase_without_matches.split(' ')\n unmatched_db = Corpus.new(\"unmatched-#{program_name}.db\")\n tokens.each do |token|\n if !complex_token_matches?(token) # token was not transformed earlier\n @to_match << token\n unmatched_db[token] = @processor.original_text\n end\n end\n unmatched_db.close\n end", "def read_and_define_word\n name = read_word\n words = []\n while (word = read_word)\n break if word == ';'\n words << word\n end\n @dictionary.word(name, &compile_words( *words ))\n end", "def load_words\n @words = []\n File.readlines(\"databases/\"+@short+\"/words.lang\").each do |line|\n word = line.split(\";\")\n @words[word[0].to_i] = Word.new(word[0], word[1], word[2], word[3], word[4].split(\"/\"), word[5].split(\"/\"))\n end\n load_words_user\n end", "def save_words\n f = File.new(\"/home/swistak35/Projekty/tuxlang/user/\"+@short+\"/words\",\"w\")\n @words.each do |word|\n f.puts word.id.to_s+\";\"+word.level.to_s+\";\"+word.rep.to_i.to_s+\";\" if word.level>0\n end\n f.close\n end", "def load_words!\n @exact, @greedy = YAML::load(File.read(File.join(File.dirname(__FILE__), \"../config/black_list.yml\")))\n end", "def handle_save(edit_lines, type)\n if validate_inputs edit_lines\n @word = Word.new do |word|\n word.type = type.downcase.to_sym\n edit_lines.each do |k,v|\n word[k] = v.text\n end\n end\n\n puts \"Created #{@word.inf}\"\n\n Words << @word\n File.open Words_File, 'w' do |file|\n file.truncate 0\n file.write Words.to_yaml\n file.close\n end\n\n clear_edit_lines edit_lines.values\n else\n puts 'not valid'\n end\n end", "def nonwords\n @nonwords ||= %w(& of in the and).map{|w| w.to_sym}.to_set\n end", "def ignore? word\n ignore = word.short?(@emphasis[:short_words_threshold])\n\n # exception: allow short words\n ignore = (not allow_short_words?) if ignore\n\n # exception: custom handler\n unless @emphasis[:ignore].nil?\n ignore = @emphasis[:ignore].call(word)\n end\n\n ignore\n end", "def process_sentance(blob)\n # strip out enclosures\n blob = blob.gsub(/\\\\/,'')\n # test for quotes\n # if quotes, these words are important (flag them)\n test = blob.match(/[\"'](.*)['\"]/)\n if test && test.size > 1\n @words = test[1..test.size].join(\" \")\n #test.each{|word|\n # @words << word\n #}\n #blob = blob.gsub(@words,'')\n blob = blob.gsub(/([\"'])/,'')\n end\n unless @words.nil?\n # break up and add to @local_important\n tmp = @words.split(\" \")\n tmp.each{|word|\n @local_important << word.downcase unless @local_important.include? word\n }\n end\n #puts blob\n the_pieces = blob.split(\" \")\n parse_words(the_pieces)\n \n # try to sort words\n words = grab_important_words\n puts words.inspect\n \n puts \"Derived Tags: #{words.join(' ')}\"\n \n end", "def save\n\t\tNg2::HashDb.add(@word, serialize)\n\tend", "def parser_ignore!\n not_among(*OPS, C_QUOTE).many\n end", "def naive_term\n eat_ws_and_comments\n file, line, col = save\n buffer = \"\"\n until eof? || special? || ws?\n buffer += eat\n end\n handle_naive_term buffer, file, line, col\n end", "def add_missing!(d)\n (d.words.keys-@words.keys).each do |new_word|\n p new_word\n add_definition(new_word,d.words[new_word])\n end\n end", "def save_ambigious_words(file_name)\n File.open(file_name, 'w') do |f|\n sentences.each do |s|\n s.words.each do |w|\n tag_strings = w.get_correct_tags().collect { |t| t.clean_out_tag }\n f.puts w.string + \"\\t\" + tag_strings.sort.join(\"\\t\") if tag_strings.count > 1\n end\n end\n end\n\n nil\n end", "def save_words\n\t\t @word_weight.each do |word, weight|\n\t\t \t@db.update_or_create_word(word, @filename, weight, @word_frequency[word])\n\t\t end\n\t\tend", "def remove\n words.each do |word|\n val = \"#{word}#{ArchiveConfig.autocomplete[:terminator]}\"\n remove_from_scored_set(val)\n remove_from_completion_set(val) if only_use?(val)\n end\n end", "def save_words\n f = File.new \"/home/swistak35/Projekty/Tucotuco/user/\"+@short+\"/words\", \"w\"\n @words.each do |word|\n f.puts \"#{word.id};#{word.level};#{word.rep.to_i};\" if word.level > 0\n #word.id.to_s+\";\"+word.level.to_s+\";\"+word.rep.to_i.to_s+\";\" if word.level>0\n end\n f.close\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns either the banner set with banner= or a simple banner like "Usage: $0 [arguments]"
def banner @banner || "Usage: #{program_prefix} [arguments]" end
[ "def banner(banner, options)\n if banner\n puts banner\n else\n # Usage needs to know about the defined options.\n usage(options)\n end\n end", "def help_banner\n output = ''\n if command_parser.main_options.banner?\n output << format(command_parser.main_options.banner, indent: 0) << \"\\n\\n\"\n end\n output << format(usage, indent: 7) << \"\\n\\n\"\n end", "def banner\n raise \"Command.banner should be overriden by subclasses\"\n end", "def banner(banner = nil)\n @banner = banner if banner\n @banner\n end", "def default_banner\n command_name = File.basename($0).gsub(/\\.[^.]+$/, '')\n bannertext = ''\n bannertext << \"Usage: #{command_name} #{@usage}\\n\" if @usage\n bannertext << \"#{@synopsis}\\n\" if @synopsis\n bannertext << \"\\n\" if @usage || @synopsis\n bannertext << \"#{@version}\\n\" if @version\n unless subcommands.empty?\n bannertext << \"\\n\" if @version \n bannertext << \"Commands:\\n\"\n @subcommand_parsers.each_value do |scmd|\n bannertext << sprintf(\" %-20s %s\\n\", scmd.name, scmd.desc)\n end\n bannertext << \"\\n\" \n end\n bannertext << \"Options:\\n\"\n return bannertext\n end", "def banner(banner = nil)\n config[:banner] = banner if banner\n config[:banner]\n end", "def banner\n \"#{basename} #{self_command.formatted_usage(self, false)}\"\n end", "def banner\n lines = []\n \n name_line = \"#{ name } role\"\n lines << name_line\n lines << \"=\" * name_line.length\n lines << ''\n if meta['description']\n lines << meta['description']\n lines << ''\n end\n lines << 'usage:'\n # lines << \" qb #{ name } [OPTIONS] DIRECTORY\"\n lines << \" #{ usage }\"\n lines << ''\n lines << 'options:'\n \n lines.join(\"\\n\")\n end", "def banner(text=nil)\n @banner = text if text\n @banner\n end", "def banner\n print_line BANNER\n print_line\n print_line\n end", "def banner\n lines = []\n \n name_line = \"#{ name } role\"\n lines << name_line\n lines << \"=\" * name_line.length\n lines << ''\n if meta['description']\n lines << meta['description']\n lines << ''\n end\n lines << 'Usage:'\n lines << ''\n lines << \" #{ usage }\"\n lines << ''\n lines << ''\n \n lines.join(\"\\n\")\n end", "def cli_banner()\n print \"> \"\n end", "def banner\n self.class.instance_variable_get(:@__banner)\n end", "def banner(command, namespace = T.unsafe(nil), subcommand = T.unsafe(nil)); end", "def banner(command, namespace = nil, subcommand = false)\n \"#{basename} #{command.formatted_usage(self, $thor_runner, subcommand)}\"\n end", "def shell_banner\n Command::ShellBannerBuilder\n end", "def banner\n self.class.banner\n end", "def banner\n puts \"******************************************************************************\".colorize(color: :white, background: :magenta)\n puts \"* rotor_machine: Simple simulation of the German WWII Enigma Machine *\".colorize(color: :white, background: :magenta)\n puts \"* By Tammy Cravit <tammycravit@me.com> *\".colorize(color: :white, background: :magenta)\n puts \"* http://github.com/tammycravit/rotor_machine *\".colorize(color: :white, background: :magenta)\n puts \"******************************************************************************\".colorize(color: :white, background: :magenta)\n puts \"\"\n puts \"rotor_machine version #{RotorMachine::VERSION}. Type 'help' for help. <Tab> to complete commands.\".colorize(color: :magenta)\n puts \"\"\n end", "def banner_text\n banner_text = ENV.key?('ENVIRONMENT_BANNER') ? ENV['ENVIRONMENT_BANNER'] : ''\n ENV['ENVIRONMENT_BANNER'].freeze unless banner_text.empty?\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the follower common event call
def check_follower_trigger_there(new_x, new_y) if @follower.x == new_x && @follower.y == new_y if @follower.is_a?(Game_Event) @follower.start else @follower.turn_toward_player $game_temp.common_event_id = Game_CommonEvent::FOLLOWER_SPEECH end return true end return false end
[ "def check_self_follow\n if helpers.am_i_owner?\n flash[:notice] = \"You can't follow your own event!\"\n redirect_to @event\n end\n end", "def following?(event)\n following.include?(event)\n end", "def on_follow(user)\n end", "def following? subject\n has_event? 'follow', subject\n end", "def followup_needed?\n if broker_calls.count > 0\n\n end\n end", "def pbTalkToFollower\n if !$PokemonTemp.dependentEvents.can_refresh?\n if !($PokemonGlobal.surfing ||\n (GameData::MapMetadata.exists?($game_map.map_id) &&\n GameData::MapMetadata.get($game_map.map_id).always_bicycle) ||\n !$game_player.pbFacingTerrainTag.can_surf_freely ||\n !$game_map.passable?($game_player.x,$game_player.y,$game_player.direction,$game_player))\n pbSurf\n end\n return false\n end\n first_pkmn = $Trainer.first_able_pokemon\n GameData::Species.play_cry(first_pkmn)\n event = pbGetFollowerDependentEvent\n random_val = rand(6)\n Events.OnTalkToFollower.trigger(first_pkmn,event.x,event.y,random_val)\n pbTurnTowardEvent(event,$game_player)\nend", "def following_event?(event)\n partecipa_events.find_by_evento_id(event.id)\n end", "def following?(other_listener)\n following.include?(other_listener)\n end", "def process_follow_ups\n manager = Autoresponder::Jobs::FollowUpManagerJob.new(self.email_list.id)\n manager.send_first_email_notification(self.id)\n end", "def notify_followers_if_necessary\n if state == MERGE_STATE['merge']\n notify_followers(jingle.id, child_jingle.user.id)\n end\n end", "def follow_event(event)\n following_event << event\n end", "def pbPokemonFollow(x)\n return false if !$Trainer.first_able_pokemon\n $PokemonTemp.dependentEvents.removeEventByName(\"FollowerPkmn\") if pbGetFollowerDependentEvent\n pbAddDependency2(x,\"FollowerPkmn\",FollowerSettings::FOLLOWER_COMMON_EVENT)\n $PokemonGlobal.follower_toggled = true\n event = pbGetFollowerDependentEvent\n $PokemonTemp.dependentEvents.pbFollowEventAcrossMaps($game_player,event,true,false)\n $PokemonTemp.dependentEvents.refresh_sprite(true)\nend", "def follow(follower_id, followee_id)\n \n end", "def followed_by?(follower)\n f = get_follow_for(follower)\n (f && !f.blocked?) ? true : false\n end", "def update_follower_event(last_follower, follower_event)\n last_follower_event = follower_event\n while last_follower_event&.follower\n last_follower_event.set_follower(nil) unless last_follower_event.follower.is_a?(Game_Event)\n last_follower_event = last_follower_event.follower\n end\n last_follower.set_follower(follower_event) if last_follower.follower != follower_event\n end", "def needs_followup?\n followup_note_count && followup_note_count > 0\n end", "def check_followup fup\n if fup\n if ( fup.current_stage + 1 ).even?\n # OFFx: Trigger only on no signals in candidate beam\n trigger_followup(fup, nil, false) if signal_groups.count == 0 \n else\n # ONx: Trigger on highest confidence valid signal\n confidence = 0\n sig_grp_best = nil\n signal_groups.each do |sig_grp|\n real = sig_grp.is_real? \n if real && ( sig_grp.confidence > confidence )\n sig_grp_best = sig_grp\n confidence = sig_grp.confidence\n end\n end\n trigger_followup( fup, sig_grp_best, true ) if sig_grp_best\n end\n else\n # ON: Trigger on all valid signals\n signal_groups.each do |sig_grp|\n trigger_followup( Followup.new(), sig_grp, true ) if sig_grp.is_real?\n end\n end\n end", "def follows?(user)\n user.followers.include?(self)\n end", "def is_followable?\n true\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute a contentEditable command
def edit(command, value=nil) command = command.gsub(/_./) { |i| i[1].upcase } focus if value `#{document}.native.execCommand(#{command}, false, #{value})` else `#{document}.native.execCommand(#{command}, false)` end end
[ "def command_mode(s) \n\t\t@command_editor.set_text(s)\n\t\t@command_editor.set_focus()\n\tend", "def execute_command(cmd, options = {})\n context = options[:in] || active_tab\n context.write :text => cmd\n end", "def execEditorScript _obj, _args\n \"_obj execEditorScript _args;\" \n end", "def execute_command!(cmd)\r\n @command_win.set cmd\r\n @command_win.send_keys :return\r\n end", "def execute!\n \tsystem(\"vim #{file} -c 'execute \\\"normal i#{escaped_commands}\\\\<Esc>\\\"' -c 'execute \\\":wq\\\"'\")\n File.read(file)\n end", "def assert_editable input_locator\r\n command 'assertEditable', input_locator\r\n end", "def edit *args\n ::NERV::CLI::ReplHelpers.send :remove_method, :edit\n require 'interactive_editor'\n alias :edit :vim\n vim *args\n end", "def verify_editable input_locator\r\n command 'verifyEditable', input_locator\r\n end", "def execute(input: $stdin, output: $stdout)\n heading 'open hello.rb in your chosen editor'\n editor.open('hello.rb')\n\n heading 'open content in your chosen editor'\n editor.open(content: 'some text')\n\n heading 'open hello.rb in vim'\n editor.open('hello.rb', command: :nano)\n\n # Currently does not support vscode\n\n :gui\n end", "def call_command\n s1 = SynSaveBU::Confirm_text \n s2 = SynSaveBU::Delete_text\n s3 = SynSaveBU::Cancel_text\n @command_window = Window_Command.new(SynSaveBU::Command_width,[s1,s2,s3])\n @command_window.x = 240\n @command_window.y = 200\n end", "def process\r\n if @mode == EDIT && @line=='.'\r\n @mode = COMMAND\r\n elsif @mode == EDIT\r\n @buffer[@current_line_number-1] = @line+\"\\n\"\r\n @current_line_number += 1\r\n else\r\n process_command\r\n end\r\n end", "def a_textarea_editable(id, prefix, data_url, v, placeholder=\"--\")\n a_generic_editable('textarea_editable',id,prefix,data_url,v,placeholder)\n end", "def edit_custom_command(command_name, owner_user_id, new_command_content)\n return false if new_command_content.length > custom_command_content_max_length\n commands = USER_CUSTOM_COMMANDS.where{Sequel.&({owner_user_id: owner_user_id}, {command_name: command_name})}\n return false if commands.count() <= 0\n\n commands.update(command_content: new_command_content)\n return true\n end", "def editable(name, options = {}, &block)\n initial_content = block_given? ? capture(&block) : nil\n content = load_content(name, initial_content, options)\n output = silk_editable? ? content_wrapper(content) : render_content(content)\n block_given? ? concat(output) : output\n end", "def execute_command command_text\r\n #TODO: really, what is point of this \"convenience\" method!?\r\n create_command( command_text ).execute\r\n end", "def editor_insert_character!\n Vedeu.bind(:_editor_insert_character_) do |name, character|\n Vedeu.documents.by_name(name).insert_character(character)\n end\n end", "def command!\n Vedeu.bind(:_command_) { |command| Vedeu.trigger(:command, command) }\n end", "def editable!\n editable(true)\n end", "def edit(snippet)\n if editor && !editor.empty?\n snippet_file = file_for(snippet)\n Process.exec \"#{editor} '#{snippet_file}'\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an instance of SeriesIndex for each series page, renders it, and writes the output to a file. +series_prefix+ is the String path to the series folder. +series+ is the series currently being processed.
def write_series_index(series_prefix, series, posts, authors) index = SeriesIndex.new(self, source, series_prefix, series, posts, authors) index.render(layouts, site_payload) index.write(dest) # Record the fact that this page has been added, otherwise Site::cleanup will remove it. pages << index end
[ "def write_series(series) # :nodoc:\n write_ser(series)\n end", "def generate_indexes\n @indexes.each do |index|\n html_out = File.open \"#{@sitepath}/#{index}.html\",\"w\"\n layout_engine = Haml::Engine.new(\n File.read(\"#{@basepath}/_layouts/#{index}.haml\"))\n payload = layout_engine.render(Object.new,:posts=>@posts)\n html_out.write payload\n html_out.close\n end\n end", "def write\n if root?\n index_file = File.join(page_dir, 'index.html')\n notice \"Writing top level index file at #{index_file}\"\n File.open(index_file, 'w') {|f| f.puts content}\n else\n # First create the index page\n index_file = File.join(page_dir, name + '.html')\n notice \"Writing index file for directory #{path} at #{index_file}\"\n File.open(index_file, 'w') {|f| f.puts content}\n\n # Create a directory to contain index pages for any child directories\n Dir.mkdir(File.join(page_dir, name))\n end\n dirs.sort.each{|dir| dir.write}\n\n # Determine if the page assets directory is necessary, to avoid clutter\n writing_page_assets = true\n begin\n # Detect whether the write_page_assets method is overridden\n # In case this explodes in 1.8.6 we'll always create the directory\n writing_page_assets = renderer.class.instance_method(:write_page_assets).owner != DirRenderer\n rescue\n end\n\n # The renderer knows what assets are linked to and what needs to be available\n # to display the page properly\n if writing_page_assets\n Dir.mkdir(page_assets_dir)\n renderer.write_page_assets(self)\n end\n end", "def create_indices\n destination = File.join(@config[:site][:root], @config[:site][:posts], @config[:site][:index])\n Dir.mkdir(destination) if !Dir.exists?(destination)\n\n # Clear out the indices before making them\n Dir.entries(destination).each do |f|\n index = File.join(destination, f)\n File.delete(index) if File.file?(index)\n end\n\n temp_dir = File.join(\"templates\")\n template = Template.new(temp_dir, 'index.html', post_location=@config[:site][:posts])\n indices = []\n\n # Segment the posts into groups of 5\n @posts.each_slice(5) { |posts|\n indices << posts\n }\n\n # Create the indices and save them\n indices.length.times { |i|\n p_pg = nil\n n_pg = nil\n\n # Find the relative location (to the site) of the index\n rel_index = File.join(\"/\", @config[:site][:posts], @config[:site][:index])\n\n # Figure out the previous/next pages, if they exist\n p_pg = File.join(rel_index, i.to_s) if i > 0\n n_pg = File.join(rel_index, (i+2).to_s) if i + 1 < indices.length\n\n # Render the index page\n indices[i] = template.render(indices[i], prev_page=p_pg, next_page=n_pg)\n\n # Save the index page\n index_file = File.join(destination, (i+1).to_s)\n File.open(index_file, 'w') do |f|\n f.print(indices[i])\n end\n }\n end", "def index_pages\n debug_msg \" generating pages search index\"\n\n pages = @files.select do |file|\n file.text?\n end\n\n pages.each do |page|\n debug_msg \" #{page.page_name}\"\n record = page.search_record\n @index[:searchIndex] << search_string(record.shift)\n @index[:longSearchIndex] << ''\n record.shift\n @index[:info] << record\n end\n end", "def generate_index_files\n @folders.each do |folder, files|\n puts \" + Creating #{@dest}/#{folder}/index.html\" if @verbose\n File.open(\"#{@dest}/#{folder}/index.html\", \"w\") do |index|\n title = \"Rails Plug-in for #@name #@version\"\n index.write(\"<html><head><title>#{title}</title></head>\\n\")\n index.write(\"<body>\\n\")\n index.write(\"<h2>#{title}</h2>\\n\")\n extra_links = create_extra_links()\n index.write(\"<p>#{extra_links}</p>\\n\") if extra_links\n files.each { |fn|\n puts(\" - Adding #{fn}\") if @verbose\n index.write(\"&nbsp;&nbsp;<a href=\\\"#{fn}\\\">#{fn}</a><br/>\\n\")\n }\n index.write(\"<hr size=\\\"1\\\"/><p style=\\\"font-size: x-small\\\">Generated with RailsPluginPackageTask<p>\")\n index.write(\"</body>\\n\")\n index.write(\"</html>\\n\")\n end\n end\n end", "def write_index\n buffer = \"\"\n xml = Builder::XmlMarkup.new(:target => buffer)\n eval(SitemapGenerator.templates.sitemap_index, binding)\n filename = File.join(Rails.root, \"public\", index_file)\n write_file(filename, buffer)\n show_progress(\"Sitemap Index\", filename, buffer) if verbose\n links.clear\n sitemaps.clear\n end", "def index\n @series = Series.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @series }\n end\n end", "def write_index_page\n File.write(path.join('index.html'), index_page)\n\n self\n end", "def generate_index\n page = {}\n page[:title] = nil\n page[:body] = \"\"\n \n @posts.keys.sort.reverse.each_with_index do |date, i|\n if i >= @config[:front_page_entries]\n break\n else\n post = @posts[date]\n \n # Don't post the whole thing on the front page.\n unless post[:excerpt].nil?\n post[:body] = ''\n end\n\n page[:body] << generate_post(@posts[date])\n end\n end\n\n File.open(File.join(@site_path, 'index.html'), 'w') do |f|\n f << generate_page(page)\n end\n end", "def write\n if File.exist?(@dir)\n FileWriter.write File.join(@dir, 'index.html'), @index\n end\n end", "def exportIndex()\r\n indexFileName = @outputDir.join(\"index.html\")\r\n indexFile = HtmlOutputFile.new(indexFileName, @options[:title])\r\n @options[:log].begin(\"Exporting index to \\\"#{indexFileName.to_s}\\\"\")\r\n\r\n if @options[:title]\r\n htmlTitle = uniToHtml(@options[:title])\r\n indexFile.puts(\"<h1>#{htmlTitle}</h1>\")\r\n end\r\n\r\n years = @messages.getYears()\r\n years.each { |year|\r\n if @options[:split] == :Year\r\n indexFile.puts(\"<h1><a href=\\\"#{year}.html\\\">#{year}</a></h1>\")\r\n else\r\n indexFile.puts(\"<h1>#{year}</h1>\")\r\n end\r\n\r\n indexFile.puts(\"<dl>\")\r\n\r\n months = @messages.getMonths(year)\r\n months.each { |month|\r\n timestamp = Date.strptime(month, \"%Y-%m\")\r\n monthName = formatMonthAndYear(timestamp)\r\n\r\n if @options[:split] == :Year\r\n refFileName=\"#{year}.html\"\r\n else\r\n refFileName=\"#{month}.html\"\r\n end\r\n\r\n indexFile.puts(\"<dt>\")\r\n indexFile.puts(\"<a href=\\\"#{refFileName}##{month}\\\">#{monthName}</a>\")\r\n indexFile.puts(\"<dd>\")\r\n\r\n days = @messages.getDays(month)\r\n days.each { |day|\r\n indexFile.puts(\"<a href=\\\"#{refFileName}##{day}\\\">#{day[8,2]}</a>\")\r\n }\r\n }\r\n\r\n indexFile.puts(\"</dl>\")\r\n }\r\n\r\n indexFile.close()\r\n @options[:log].end()\r\n end", "def write_monthly_indexes\n if self.layouts.key? 'monthly_index'\n\n self.posts_group_by_year_and_month.each do |yearAndMonth, posts|\n \n year = yearAndMonth[0]\n month = yearAndMonth[1]\n \n template_path = File.join(self.source, '_layouts', 'monthly_index.html')\n index = MonthlyIndexPage.new(template_path, self, self.source, year, month, posts)\n if index.render?\n index.render(self.layouts, site_payload)\n index.write(self.dest)\n \n # Record the fact that this pages has been added, otherwise Site::cleanup will remove it.\n self.pages << index\n end\n end\n\n # Throw an exception if the layout couldn't be found.\n else\n throw \"No 'monthly_index' layout found.\"\n end\n end", "def render_pages\n pages.each do |page|\n page.save(output)\n end\n end", "def index\n authorize! :read, Roxiware::BookSeries\n @series = Roxiware::BookSeries.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @series }\n end\n end", "def write_products_index( data, products_src_dir, dest_dir, data_mtime )\n index = ProductPage.new( self, self.config['source'], dest_dir, 'index.html', products_src_dir, 'products', data_mtime )\n index.set_data( 'products', data )\n index.render(self.layouts, site_payload)\n index.write(self.dest)\n # Record the fact that this page has been added, otherwise Site::cleanup will remove it.\n self.pages << index\n end", "def write_index_html\n index_html = File.join(dir, INDEX_HTML)\n \n File.open(index_html, 'w') { |html|\n generate(html)\n }\n puts \"Generated #{index_html}\"\n end", "def generate_index(gallery_name, url, gen_page)\n File.open(gallery_name + \"/index.textile\", 'w') do |f|\n # header\n f.puts <<-eos\n---\ntitle: #{File.basename(gallery_name)}\nlayout: gallery\n---\neos\n #\n # list of images, using a gallerific compatible markup\n # (ul.gallery > li > ( a > img.thumb | div.caption))\n #\n f.puts \"<ul class=\\\"gallery\\\">\"\n Dir.glob(\"#{gallery_name}/*.{jpg,png}\").each do |file|\n\n if not is_suffixed?(file)\n f.puts <<-eos\n <li>\n <a href=\\\"#{gen_link(url, file, gen_page)}\\\">\n <img src=\\\"#{gen_link(url, thumb_filename(file), false)}\\\" class=\\\"thumb\\\">\n </a>\n <div class=\\\"caption\\\">\n <span class=\\\"title\\\">#{File.basename(file)}</span> <br />\n #{exif_data_to_html(file)}\n </div>\n </li>\neos\n end\n end\n f.puts \"</ul>\"\n end\nend", "def write_index(cameras)\n @title = \"Camera Index\"\n # order wasn't specified so just use the order they came in\n @thumbnail_urls = cameras.slice(0, 10).map do |camera|\n camera[:image_url]\n end\n\n @makes = extract_makes(cameras)\n\n index_page = @out_dir + '/index.html'\n File.open(index_page, 'w') do |f|\n template = File.open(\"templates/index.html.erb\").read\n erb = ERB.new(template, 0, '>')\n f.write(erb.result(binding))\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a series name, and pulls out a markdown header file returning either the rendered markdown, or an empty string
def series_bio(series) bio_path = "_includes/_series_bio/#{to_series_id(series)}.md" return "" unless File.exist?(bio_path) markdownify(File.read(bio_path)) end
[ "def extract_md_title(item)\n\t\tif (item[:extension] != 'md')\n\t\t\treturn nil\n\t\tend\n\n\t\tcontent = item.raw_content.lines.each{|l|\n\t\t\tif (l.start_with?('# '))\n\t\t\t\treturn l[2..-1].strip()\n\t\t\tend\n\t\t}\n\t\tnil\n\tend", "def slide_title\n title = @line[/^ *## (.*)/, 1]\n title.nil? ? nil : title.sub(/##/, '').strip\n end", "def markdown_section(name)\n markdown_sections.find { |s| s.name == name }\n end", "def title_helper(page = current_page)\n if page.directory_index? && page.path != \"index.html\"# dont be clever with indexes\n filename = page.url.split(\"/\").last.gsub('%20', ' ').titleize\n return filename.chomp(File.extname(filename))\n elsif page.try(:data).try(:title)\n return page.data.title # Frontmatter title\n elsif match = page.render({:layout => false, :no_images => true}).match(/<h.+>(.*?)<\\/h1>/)\n return match[1] # H1 title\n else\n filename = page.url.split(/\\//).last.gsub('%20', ' ').titleize\n return filename.chomp(File.extname(filename))\n end\n end", "def extract_default_title\n\t\treturn self.name unless self.readme&.table_of_contents&.first\n\t\ttitle = self.readme.table_of_contents.first.text\n\t\ttitle ||= self.name\n\tend", "def studyTitle\n $async::wait_until($janus::WAY_TOO_LONG_TO_LOAD) { page_header.visible? }\n sleep 1 #TODO Refactor methods, steps are failing due to recent update from imedidata\n $async::wait_until($janus::WAY_TOO_LONG_TO_LOAD) { !page_header.text.empty? }\n page_header.text\n end", "def to_markdown_heading\n heading = to_heading\n to_markdown heading\n end", "def markdown_heading_parser(content)\n content.gsub(/^.*#.*/) { |heading| \"<h1>#{heading[2..-1]}</h1>\" }\nend", "def series_title\n return title if series?\n @doc = SolrDocument.new(Blacklight.solr.select(:params => { :fq => \"#{SolrDocument.unique_key}:#{series}\" })[\"response\"][\"docs\"].first)\n @doc.title\n end", "def render_readme(content, extension)\n if %w(md mdown markdown).include?(extension.downcase)\n render_markdown(content)\n else\n content\n end\n end", "def render markdown_source\n markdown.render \"#{markdown_source}\"\n end", "def markdown\n return if changed_markdown_files.empty?\n\n output = `mdl #{changed_markdown_files.join(' ')}`\n return if output&.empty?\n\n heading('Markdown Linter', output)\n end", "def markdown(req)\n ::File.read(file_path(req))\n end", "def markdown_files; end", "def mdrender\n \t@markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true)\n end", "def frontmatter_title\n current_page.data.title\n end", "def discover_title(page = current_page)\n if page.data.title\n return page.data.title # Frontmatter title\n elsif match = page.render({:layout => false, :no_images => true}).match(/<h.+>(.*?)<\\/h1>/)\n return match[1] # H1 title\n elsif page.url == '/'\n return extensions[:navtree].options[:home_title]\n else\n filename = page.url.split(/\\//).last.gsub('%20', ' ').titleize\n return filename.chomp(File.extname(filename))\n end\n end", "def get_data(prefix, name)\n f = File.open(\"data/#{prefix}/#{name}.md\")\n contents = f.read\n f.close\n metadata = YAML.load(contents)\n metadata[\"text\"] = Redcarpet::Markdown.new(Redcarpet::Render::HTML).render(contents.gsub(/---(.|\\n)*---/, \"\"))\n return metadata\n end", "def md_path(name)\n Rails.root.join(ManPages::MARKDOWN_PATH, name + \".md\")\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the G of the memory_used
def memory_used_with_g self.memory_memused.map { |i| i / 1000000000.0} end
[ "def memused\n @memtotal - @memfree\n end", "def memory_used\n %x[free -ot].split[19]\n end", "def memory_total\n %x[free -ot].split[18]\n end", "def mem_used\n mem_total - mem_available\n end", "def ram_used\n %x[free -ot].split[8]\n end", "def memory_bytes_used\n get_device_info[:memory_used]\n end", "def used_space\n size - free_space\n end", "def memory_usage\n @memory_usage\n end", "def get_system_used_memory_mb\n # (`free -ml | grep 'Mem:' | awk -F' ' '{ print $3 }'`.strip.to_i rescue 0).round(MEMORY_PRECISION)\n get_system_memory_info_mb[:used_memory]\n end", "def memory_percent_used\n info = get_device_info\n 100.0 * info[:memory_used] / info[:memory_total]\n end", "def memory_bytes_total\n get_device_info[:memory_total]\n end", "def free_space\n sum = 0\n\n mount_points.each do |mount_point, values|\n sum += RelayRegister::Converter.convert_to_gb(values['size_available'])\n end\n\n \"#{sum.round(1)} GB\"\n end", "def get_system_used_swap_memory_mb\n # (`free -ml | grep 'Swap:' | awk -F' ' '{ print $3 }'`.strip.to_i rescue 0).round(MEMORY_PRECISION)\n get_system_memory_info_mb[:used_swap_memory]\n end", "def ram_total\n %x[free -ot].split[7]\n end", "def total_free_space\n self.free_spaces.reduce(0, :+)\n end", "def memory_free\n %x[free -ot].split[20]\n end", "def memsize\n \"Memory size: #{@sysHash[\"Memory\"]}\"\n end", "def _get_allocated_size; GC.stat(:malloc_increase_bytes); end", "def percent_used\n\t\t\t\treturn nil unless meminfo?\n\t\t\t\tmemory = IO.foreach('/proc/meminfo').first(3)\n\t\t\t\ttotal = memory[0].split[1].to_i\n\t\t\t\ttotal.-(memory[2].split[1].to_i).*(100).fdiv(total).round(2)\n\t\t\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get IPv6 addresses for given network interface
def ip6addr(iface=nil) @ip6addr[iface || default_iface] end
[ "def ipv_6_addresses\n data.ipv_6_addresses\n end", "def ipv_6_addresses\n data[:ipv_6_addresses]\n end", "def ipv6_addresses\n addresses.select { |address| address.match /:/ }\n end", "def ipv6\n @ipv6\n end", "def parse_ip6(ip_output, scope)\n cidr_ip = parse_ip_output(ip_output, /inet6 .* scope #{scope}/, 1)\n return unless cidr_ip\n\n parts = cidr_ip.split('/')\n @network_conf[\"address6_#{scope}\".to_sym] = parts[0]\n @network_conf[\"prefix6_#{scope}\".to_sym] = parts[1].to_i\n end", "def ipv_6_address\n data[:ipv_6_address]\n end", "def get_network_by_interface(interface)\n\n ifconfig = `ifconfig`.split(\"\\n\\n\").index_by{|x| x[/\\w+/,0]}\n inet = ifconfig[interface][/inet addr:([^\\s]*)/, 1].split('.')\n broadcast = ifconfig[interface][/Bcast:([^\\s]*)/, 1].split('.')\n mask = ifconfig[interface][/Mask:([^\\s]*)/, 1].split('.')\n\n start_first = inet[0].to_i & mask[0].to_i\n start_second = inet[1].to_i & mask[1].to_i\n start_third = inet[2].to_i & mask[2].to_i\n start_fourth = inet[3].to_i & mask[3].to_i\n\n first_range = start_first..broadcast[0].to_i\n second_range = start_second..broadcast[1].to_i\n third_range = start_third..broadcast[2].to_i\n fourth_range = start_fourth..broadcast[3].to_i\n \n @ips_to_check = []\n first_range.each do |first|\n second_range.each do |second|\n third_range.each do |third|\n fourth_range.each do |fourth|\n @ips_to_check << \"#{first}.#{second}.#{third}.#{fourth}\"\n end\n end\n end\n end\n puts \"Checking ips in (#{first_range}).(#{second_range}).(#{third_range}).(#{fourth_range})\"\n \n @ips_to_check\n end", "def to_net()\n\t\t\tNetAddr::IPv6Net.new(self,nil)\n\t\tend", "def ipv6_str2arr(ipv6_str)\n ipaddr = IPAddr.new ipv6_str\n ipaddr = ipaddr.hton.split(//)\n adr = []\n ipaddr.each do |x|\n adr << x.unpack(\"H*\").first.hex\n end\n adr\nend", "def all_bound_ips\n ip_list = []\n node['network']['interfaces'].each do |_ifce, attrs|\n next unless attrs['addresses'] #Not all interfaces have Addresses\n attrs['addresses'].each do |addr, _|\n ## Only take valid IPv4 and IPv6\n ip_list.push(addr) if !(IPAddr.new(addr) rescue nil).nil?\n end\n end\n ip_list\n end", "def ip_addresses(interface=nil, resolve_cache=nil, use_cache=nil)\n getaddrinfo(resolve_cache) unless use_cache\n if interface\n @interface_addresses[interface]\n else\n @interface_addresses.values.flatten\n end\n end", "def index\n @ipv6s = Ipv6.all\n end", "def public_ipv6\n get('tools/public_ipv6.xml').body['ipv6']\n end", "def summ_IPv6Net(list)\n\t\tlist = Util.filter_IPv6Net(list)\n\t\tif (list.length>1)\n\t\t\tlist = Util.discard_subnets(list)\n\t\t\treturn Util.summ_peers(list)\n\t\tend\n\t\treturn [].concat(list)\n\tend", "def get_ip_cidr6(c)\n return false unless c.include?(:ip6)\n return false unless c.include?(:ip6_cidr)\n begin\n return false unless IPAddr.new(c[:ip6])\n rescue IPAddr::Error\n raise Errors::VMConfigError,\n error_msg: \"Invalid IP-Address supplied: #{c[:ip6]}\"\n end\n \"#{c[:ip6]}/#{c[:ip6_cidr]}\"\n end", "def ipv_6_prefixes\n data[:ipv_6_prefixes]\n end", "def add_ipv6_multicast\n add_host '::1', ['ip6-localhost', 'ip6-loopback']\n add_host 'fe00::0', ['ip6-localnet']\n add_host 'ff00::0', ['ip6-mcastprefix']\n add_host 'ff02::1', ['ip6-allnodes']\n add_host 'ff02::2', ['ip6-allrouters']\n end", "def interface_private_ips(interface)\n mac = interface_mac_address(interface)\n ips = node['ec2']['network_interfaces_macs'][mac]['local_ipv4s']\n ips = ips.split(\"\\n\") if ips.is_a? String # ohai 14 will return an array\n Chef::Log.debug(\"#{interface} assigned local ipv4s addresses is/are #{ips.join(',')}\")\n ips\n end", "def to_ipv6(net)\n\t\t\tif (!net.kind_of?(IPv6Net))\n\t\t\t\traise ArgumentError, \"Expected an IPv6Net object for 'net' but got a #{net.class}.\"\n\t\t\tend\n\t\t\t\n\t\t\tif (net.netmask.prefix_len != 64)\n\t\t\t\treturn nil\n\t\t\tend\n\t\t\t\n\t\t\t# set u/l bit to 0\n\t\t\thostId = @addr ^ 0x0200000000000000\n\t\t\tipAddr = net.network.addr | hostId\n\t\t\treturn IPv6.new(ipAddr)\n\t\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /vertices_scene3s GET /vertices_scene3s.json
def index @vertices_scene3s = VerticesScene3.all end
[ "def index\n @scene3s = Scene3.all\n end", "def index\n @space_scene3s = SpaceScene3.all\n end", "def index\n @vertices_scenes = VerticesScene.all\n end", "def index\n @position_scene3s = PositionScene3.all\n end", "def index\n @vertices_scene1s = VerticesScene1.all\n end", "def create\n @vertices_scene3 = VerticesScene3.new(vertices_scene3_params)\n\n respond_to do |format|\n if @vertices_scene3.save\n format.html { redirect_to @vertices_scene3, notice: 'Vertices scene3 was successfully created.' }\n format.json { render :show, status: :created, location: @vertices_scene3 }\n else\n format.html { render :new }\n format.json { render json: @vertices_scene3.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @vertices_scene3.destroy\n respond_to do |format|\n format.html { redirect_to vertices_scene3s_url, notice: 'Vertices scene3 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def index\n @colour_scene3s = ColourScene3.all\n end", "def index\n @vertices_scene2s = VerticesScene2.all\n end", "def index\n @factorial_scene3s = FactorialScene3.all\n end", "def index\n @level3s = Level3.all\n end", "def create\n @vertices_scene = VerticesScene.new(vertices_scene_params)\n\n respond_to do |format|\n if @vertices_scene.save\n format.html { redirect_to @vertices_scene, notice: 'Vertices scene was successfully created.' }\n format.json { render :show, status: :created, location: @vertices_scene }\n else\n format.html { render :new }\n format.json { render json: @vertices_scene.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @vertices_scene3.update(vertices_scene3_params)\n format.html { redirect_to @vertices_scene3, notice: 'Vertices scene3 was successfully updated.' }\n format.json { render :show, status: :ok, location: @vertices_scene3 }\n else\n format.html { render :edit }\n format.json { render json: @vertices_scene3.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @vertices_scene.destroy\n respond_to do |format|\n format.html { redirect_to vertices_scenes_url, notice: 'Vertices scene was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def index\n @scene_objects = SceneObject.all\n end", "def update\n respond_to do |format|\n if @vertices_scene.update(vertices_scene_params)\n format.html { redirect_to @vertices_scene, notice: 'Vertices scene was successfully updated.' }\n format.json { render :show, status: :ok, location: @vertices_scene }\n else\n format.html { render :edit }\n format.json { render json: @vertices_scene.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @id3s = Id3.all\n end", "def destroy\n @scene3.destroy\n respond_to do |format|\n format.html { redirect_to scene3s_url, notice: 'Scene3 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def index\n @p3s = P3.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /vertices_scene3s POST /vertices_scene3s.json
def create @vertices_scene3 = VerticesScene3.new(vertices_scene3_params) respond_to do |format| if @vertices_scene3.save format.html { redirect_to @vertices_scene3, notice: 'Vertices scene3 was successfully created.' } format.json { render :show, status: :created, location: @vertices_scene3 } else format.html { render :new } format.json { render json: @vertices_scene3.errors, status: :unprocessable_entity } end end end
[ "def create\n @vertices_scene = VerticesScene.new(vertices_scene_params)\n\n respond_to do |format|\n if @vertices_scene.save\n format.html { redirect_to @vertices_scene, notice: 'Vertices scene was successfully created.' }\n format.json { render :show, status: :created, location: @vertices_scene }\n else\n format.html { render :new }\n format.json { render json: @vertices_scene.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @vertices_scene3s = VerticesScene3.all\n end", "def create\n @scene3 = Scene3.new(scene3_params)\n\n respond_to do |format|\n if @scene3.save\n format.html { redirect_to @scene3, notice: 'Scene3 was successfully created.' }\n format.json { render :show, status: :created, location: @scene3 }\n else\n format.html { render :new }\n format.json { render json: @scene3.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @vertices_scene1 = VerticesScene1.new(vertices_scene1_params)\n\n respond_to do |format|\n if @vertices_scene1.save\n format.html { redirect_to @vertices_scene1, notice: 'Vertices scene1 was successfully created.' }\n format.json { render :show, status: :created, location: @vertices_scene1 }\n else\n format.html { render :new }\n format.json { render json: @vertices_scene1.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @vertices_scene3.destroy\n respond_to do |format|\n format.html { redirect_to vertices_scene3s_url, notice: 'Vertices scene3 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def create\n @space_scene3 = SpaceScene3.new(space_scene3_params)\n\n respond_to do |format|\n if @space_scene3.save\n format.html { redirect_to @space_scene3, notice: 'Space scene3 was successfully created.' }\n format.json { render :show, status: :created, location: @space_scene3 }\n else\n format.html { render :new }\n format.json { render json: @space_scene3.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @position_scene3 = PositionScene3.new(position_scene3_params)\n\n respond_to do |format|\n if @position_scene3.save\n format.html { redirect_to @position_scene3, notice: 'Position scene3 was successfully created.' }\n format.json { render :show, status: :created, location: @position_scene3 }\n else\n format.html { render :new }\n format.json { render json: @position_scene3.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @scene3s = Scene3.all\n end", "def create\n @scene = Scene.new(scene_params)\n\n respond_to do |format|\n if @scene.save\n format.html { redirect_to @scene, notice: t(:successful_created, scope: :scenes) }\n format.json { render :show, status: :created, location: @scene }\n else\n format.html { render :new }\n format.json { render json: @scene.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @vertices_scene3.update(vertices_scene3_params)\n format.html { redirect_to @vertices_scene3, notice: 'Vertices scene3 was successfully updated.' }\n format.json { render :show, status: :ok, location: @vertices_scene3 }\n else\n format.html { render :edit }\n format.json { render json: @vertices_scene3.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @vertices_scene2 = VerticesScene2.new(vertices_scene2_params)\n\n respond_to do |format|\n if @vertices_scene2.save\n format.html { redirect_to @vertices_scene2, notice: 'Vertices scene2 was successfully created.' }\n format.json { render :show, status: :created, location: @vertices_scene2 }\n else\n format.html { render :new }\n format.json { render json: @vertices_scene2.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @scene_object = SceneObject.new(scene_object_params)\n\n respond_to do |format|\n if @scene_object.save\n format.html { redirect_to @scene_object, notice: 'Scene object was successfully created.' }\n format.json { render :show, status: :created, location: @scene_object }\n else\n format.html { render :new }\n format.json { render json: @scene_object.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @vertices_scene.update(vertices_scene_params)\n format.html { redirect_to @vertices_scene, notice: 'Vertices scene was successfully updated.' }\n format.json { render :show, status: :ok, location: @vertices_scene }\n else\n format.html { render :edit }\n format.json { render json: @vertices_scene.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @vertices_scene.destroy\n respond_to do |format|\n format.html { redirect_to vertices_scenes_url, notice: 'Vertices scene was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def create\n @scene = @act.scenes.build(scene_params)\n\n respond_to do |format|\n if @scene.save\n format.html { redirect_to @act, notice: 'Scene was successfully created.' }\n format.json { render :show, status: :created, location: @scene }\n else\n format.html { render :new }\n format.json { render json: @scene.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @scene = @scenario.scenes.build(scene_params)\n\n respond_to do |format|\n if @scene.save\n format.html { redirect_to scenario_scenes_path(@scenario), notice: \"Scene was successfully created.\" }\n format.json { render :show, status: :created, location: @scene }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @scene.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @space_scene = SpaceScene.new(space_scene_params)\n\n respond_to do |format|\n if @space_scene.save\n format.html { redirect_to @space_scene, notice: 'Space scene was successfully created.' }\n format.json { render :show, status: :created, location: @space_scene }\n else\n format.html { render :new }\n format.json { render json: @space_scene.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project = Project.find(params[:project_id])\n if !@project.owner?(session_obj)\n not_authorized and return\n end\n @scene = @project.scenes.new(params[:scene])\n #load up initial background and music\n @scene.load_initial_events\n respond_to do |format|\n if @scene.save!\n format.html { redirect_to edit_project_scene_path(@project, @scene) }\n format.json { render json: @scene, status: :created, location: @scene }\n else\n flash[:notice] = @scene.errors.full_messages\n format.html { redirect_to :back }\n format.json { render json: @scene.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @space_scene3s = SpaceScene3.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /vertices_scene3s/1 PATCH/PUT /vertices_scene3s/1.json
def update respond_to do |format| if @vertices_scene3.update(vertices_scene3_params) format.html { redirect_to @vertices_scene3, notice: 'Vertices scene3 was successfully updated.' } format.json { render :show, status: :ok, location: @vertices_scene3 } else format.html { render :edit } format.json { render json: @vertices_scene3.errors, status: :unprocessable_entity } end end end
[ "def update\n respond_to do |format|\n if @vertices_scene.update(vertices_scene_params)\n format.html { redirect_to @vertices_scene, notice: 'Vertices scene was successfully updated.' }\n format.json { render :show, status: :ok, location: @vertices_scene }\n else\n format.html { render :edit }\n format.json { render json: @vertices_scene.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @vertices_scene1.update(vertices_scene1_params)\n format.html { redirect_to @vertices_scene1, notice: 'Vertices scene1 was successfully updated.' }\n format.json { render :show, status: :ok, location: @vertices_scene1 }\n else\n format.html { render :edit }\n format.json { render json: @vertices_scene1.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @scene3.update(scene3_params)\n format.html { redirect_to @scene3, notice: 'Scene3 was successfully updated.' }\n format.json { render :show, status: :ok, location: @scene3 }\n else\n format.html { render :edit }\n format.json { render json: @scene3.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if params[:scene] then\n # Saving scene\n @scene.data = params[:scene]\n @scene.ui_log = params[:ui_log]\n if params['preview'] then\n preview_data = params['preview']\n image_data = Base64.decode64(preview_data['data:image/png;base64,'.length .. -1])\n @scene.preview = image_data\n @scene.preview.name = 'scene' + @scene.id.to_s + '.png'\n @scene.preview.meta = {\n \"name\" => @scene.preview.name,\n \"time\" => Time.now\n }\n end\n @scene.save!\n\n # send 200 response\n ok_JSON_response\n elsif params[:name] then\n # Saving meta data\n @scene.update_attributes!({\n :name => params[:name],\n :description => params[:description],\n :category => params[:category],\n :tag => params[:tag],\n :dataset => params[:dataset],\n :noedit => params[:noedit]\n })\n\n # send 200 response\n ok_JSON_response\n else\n # send error response\n fail_JSON_response\n end\n end", "def update\n\n respond_to do |format|\n if @scene.update_attributes(params[:scene])\n format.html { redirect_to edit_project_scene_path(@scene.project, @scene) }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @scene.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @vertices_scene2.update(vertices_scene2_params)\n format.html { redirect_to @vertices_scene2, notice: 'Vertices scene2 was successfully updated.' }\n format.json { render :show, status: :ok, location: @vertices_scene2 }\n else\n format.html { render :edit }\n format.json { render json: @vertices_scene2.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @position_scene3.update(position_scene3_params)\n format.html { redirect_to @position_scene3, notice: 'Position scene3 was successfully updated.' }\n format.json { render :show, status: :ok, location: @position_scene3 }\n else\n format.html { render :edit }\n format.json { render json: @position_scene3.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @scene.update(scene_params)\n format.html { redirect_to scenario_scenes_path(@scenario), notice: \"Scene was successfully updated.\" }\n format.json { render :show, status: :ok, location: @scene }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @scene.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @scene_object.update(scene_object_params)\n format.html { redirect_to @scene_object, notice: 'Scene object was successfully updated.' }\n format.json { render :show, status: :ok, location: @scene_object }\n else\n format.html { render :edit }\n format.json { render json: @scene_object.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @space_scene3.update(space_scene3_params)\n format.html { redirect_to @space_scene3, notice: 'Space scene3 was successfully updated.' }\n format.json { render :show, status: :ok, location: @space_scene3 }\n else\n format.html { render :edit }\n format.json { render json: @space_scene3.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @factorial_scene3.update(factorial_scene3_params)\n format.html { redirect_to @factorial_scene3, notice: 'Factorial scene3 was successfully updated.' }\n format.json { render :show, status: :ok, location: @factorial_scene3 }\n else\n format.html { render :edit }\n format.json { render json: @factorial_scene3.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @vertices_scene3 = VerticesScene3.new(vertices_scene3_params)\n\n respond_to do |format|\n if @vertices_scene3.save\n format.html { redirect_to @vertices_scene3, notice: 'Vertices scene3 was successfully created.' }\n format.json { render :show, status: :created, location: @vertices_scene3 }\n else\n format.html { render :new }\n format.json { render json: @vertices_scene3.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @vertex.update(vertex_params)\n format.html { redirect_to @vertex, notice: 'Vertex was successfully updated.' }\n format.json { render :show, status: :ok, location: @vertex }\n else\n format.html { render :edit }\n format.json { render json: @vertex.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @vertices_scene3.destroy\n respond_to do |format|\n format.html { redirect_to vertices_scene3s_url, notice: 'Vertices scene3 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def update\n respond_to do |format|\n if @colour_scene3.update(colour_scene3_params)\n format.html { redirect_to @colour_scene3, notice: 'Colour scene3 was successfully updated.' }\n format.json { render :show, status: :ok, location: @colour_scene3 }\n else\n format.html { render :edit }\n format.json { render json: @colour_scene3.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @vertices_scene3s = VerticesScene3.all\n end", "def update\n @scene.update_attributes(scene_params)\n respond_with @scene, location: backstage_scenes_path\n end", "def update\n respond_to do |format|\n if @scene1.update(scene1_params)\n format.html { redirect_to @scene1, notice: 'Scene1 was successfully updated.' }\n format.json { render :show, status: :ok, location: @scene1 }\n else\n format.html { render :edit }\n format.json { render json: @scene1.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @factorial_scene.update(factorial_scene_params)\n format.html { redirect_to @factorial_scene, notice: 'Factorial scene was successfully updated.' }\n format.json { render :show, status: :ok, location: @factorial_scene }\n else\n format.html { render :edit }\n format.json { render json: @factorial_scene.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /vertices_scene3s/1 DELETE /vertices_scene3s/1.json
def destroy @vertices_scene3.destroy respond_to do |format| format.html { redirect_to vertices_scene3s_url, notice: 'Vertices scene3 was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @vertices_scene.destroy\n respond_to do |format|\n format.html { redirect_to vertices_scenes_url, notice: 'Vertices scene was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @vertices_scene1.destroy\n respond_to do |format|\n format.html { redirect_to vertices_scene1s_url, notice: 'Vertices scene1 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @scene3.destroy\n respond_to do |format|\n format.html { redirect_to scene3s_url, notice: 'Scene3 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @vertices_scene2.destroy\n respond_to do |format|\n format.html { redirect_to vertices_scene2s_url, notice: 'Vertices scene2 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n\n @scene.destroy\n\n respond_to do |format|\n format.html { redirect_to action: \"index\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @scene = Scene.find(params[:id])\n @scene.destroy\n\n respond_to do |format|\n format.html { redirect_to scenes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @scene.destroy\n respond_to do |format|\n format.html { redirect_to scenes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @factorial_scene3.destroy\n respond_to do |format|\n format.html { redirect_to factorial_scene3s_url, notice: 'Factorial scene3 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @space_scene3.destroy\n respond_to do |format|\n format.html { redirect_to space_scene3s_url, notice: 'Space scene3 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @position_scene3.destroy\n respond_to do |format|\n format.html { redirect_to position_scene3s_url, notice: 'Position scene3 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @colour_scene3.destroy\n respond_to do |format|\n format.html { redirect_to colour_scene3s_url, notice: 'Colour scene3 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n delete_request($uri + \"/#{$key}/groups/#{group.id}/scenes/#{id}\")\n Scene.update_cache\n end", "def destroy\n @scene_object.destroy\n respond_to do |format|\n format.html { redirect_to scene_objects_url, notice: 'Scene object was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @lab_scene_resource = LabSceneResource.find(params[:id])\n @lab_scene_resource.destroy\n\n respond_to do |format|\n format.html { redirect_to lab_scene_resources_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @d3 = D3.find(params[:id])\n @d3.destroy\n\n respond_to do |format|\n format.html { redirect_to d3s_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @unity3d.destroy\n respond_to do |format|\n format.html { redirect_to unity3ds_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @scene1.destroy\n respond_to do |format|\n format.html { redirect_to scene1s_url, notice: 'Scene1 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @level3.destroy\n respond_to do |format|\n format.html { redirect_to level3s_url, notice: 'Level3 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @scene_node.destroy\n respond_to do |format|\n format.html { redirect_to scene_nodes_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute a read operation with retrying. This method performs server selection for the specified server selector and yields to the provided block, which should execute the initial query operation and return its result. The block will be passed the server selected for the operation. If the block raises an exception, and this exception corresponds to a read retryable error, and read retries are enabled for the client, this method will perform server selection again and yield to the block again (with potentially a different server). If the block returns successfully, the result of the block is returned. If modern retry reads are on (which is the default), the initial read operation will be retried once. If legacy retry reads are on, the initial read operation will be retried zero or more times depending on the :max_read_retries client setting, the default for which is 1. To disable read retries, turn off modern read retries by setting retry_reads: false and set :max_read_retries to 0 on the client.
def read_with_retry(session = nil, server_selector = nil, &block) if session.nil? && server_selector.nil? # Older versions of Mongoid call read_with_retry without arguments. # This is already not correct in a MongoDB 3.6+ environment with # sessions. For compatibility we emulate the legacy driver behavior # here but upgrading Mongoid is strongly recommended. unless $_mongo_read_with_retry_warned $_mongo_read_with_retry_warned = true Logger.logger.warn("Legacy read_with_retry invocation - please update the application and/or its dependencies") end # Since we don't have a session, we cannot use the modern read retries. # And we need to select a server but we don't have a server selector. # Use PrimaryPreferred which will work as long as there is a data # bearing node in the cluster; the block may select a different server # which is fine. server_selector = ServerSelector.get(mode: :primary_preferred) legacy_read_with_retry(nil, server_selector, &block) elsif session && session.retry_reads? modern_read_with_retry(session, server_selector, &block) elsif client.max_read_retries > 0 legacy_read_with_retry(session, server_selector, &block) else server = select_server(cluster, server_selector, session) yield server end end
[ "def read_with_retry(session = nil, server_selector = nil, &block)\n if session.nil? && server_selector.nil?\n deprecated_legacy_read_with_retry(&block)\n elsif session&.retry_reads?\n modern_read_with_retry(session, server_selector, &block)\n elsif client.max_read_retries > 0\n legacy_read_with_retry(session, server_selector, &block)\n else\n read_without_retry(session, server_selector, &block)\n end\n end", "def legacy_read_with_retry(session, server_selector, &block)\n attempt = attempt ? attempt + 1 : 1\n yield select_server(cluster, server_selector, session)\n rescue *retryable_exceptions, Error::OperationFailure, Error::PoolError => e\n e.add_notes('legacy retry', \"attempt #{attempt}\")\n \n if is_retryable_exception?(e)\n raise e if attempt > client.max_read_retries || session&.in_transaction?\n elsif e.retryable? && !session&.in_transaction?\n raise e if attempt > client.max_read_retries\n else\n raise e\n end\n \n log_retry(e, message: 'Legacy read retry')\n sleep(client.read_retry_interval) unless is_retryable_exception?(e)\n retry\n end", "def retry_read(original_error, session, server_selector, failed_server: nil, &block)\n begin\n server = select_server(cluster, server_selector, session, failed_server)\n rescue Error, Error::AuthError => e\n original_error.add_note(\"later retry failed: #{e.class}: #{e}\")\n raise original_error\n end\n \n log_retry(original_error, message: 'Read retry')\n \n begin\n yield server, true\n rescue *retryable_exceptions => e\n e.add_notes('modern retry', 'attempt 2')\n raise e\n rescue Error::OperationFailure, Error::PoolError => e\n e.add_note('modern retry')\n unless e.write_retryable?\n original_error.add_note(\"later retry failed: #{e.class}: #{e}\")\n raise original_error\n end\n e.add_note(\"attempt 2\")\n raise e\n rescue Error, Error::AuthError => e\n e.add_note('modern retry')\n original_error.add_note(\"later retry failed: #{e.class}: #{e}\")\n raise original_error\n end\n end", "def deprecated_legacy_read_with_retry(&block)\n deprecation_warning :read_with_retry,\n 'Legacy read_with_retry invocation - ' \\\n 'please update the application and/or its dependencies'\n\n # Since we don't have a session, we cannot use the modern read retries.\n # And we need to select a server but we don't have a server selector.\n # Use PrimaryPreferred which will work as long as there is a data\n # bearing node in the cluster; the block may select a different server\n # which is fine.\n server_selector = ServerSelector.get(mode: :primary_preferred)\n legacy_read_with_retry(nil, server_selector, &block)\n end", "def read(&block)\n conflict_retried = 0\n\n while host\n ensure_caching!\n\n begin\n connection = host.connection\n return yield connection\n rescue StandardError => error\n if primary_only?\n # If we only have primary configured, retrying is pointless\n raise error\n elsif serialization_failure?(error)\n # This error can occur when a query conflicts. See\n # https://www.postgresql.org/docs/current/static/hot-standby.html#HOT-STANDBY-CONFLICT\n # for more information.\n #\n # In this event we'll cycle through the secondaries at most 3\n # times before using the primary instead.\n will_retry = conflict_retried < @host_list.length * 3\n\n ::Gitlab::Database::LoadBalancing::Logger.warn(\n event: :host_query_conflict,\n message: 'Query conflict on host',\n conflict_retried: conflict_retried,\n will_retry: will_retry,\n db_host: host.host,\n db_port: host.port,\n host_list_length: @host_list.length\n )\n\n if will_retry\n conflict_retried += 1\n release_host\n else\n break\n end\n elsif connection_error?(error)\n host.offline!\n release_host\n else\n raise error\n end\n end\n end\n\n ::Gitlab::Database::LoadBalancing::Logger.warn(\n event: :no_secondaries_available,\n message: 'No secondaries were available, using primary instead',\n conflict_retried: conflict_retried,\n host_list_length: @host_list.length\n )\n\n read_write(&block)\n end", "def read_with_one_retry(options = nil)\n yield\n rescue Error::SocketError, Error::SocketTimeoutError => e\n retry_message = options && options[:retry_message]\n log_retry(e, message: retry_message)\n yield\n end", "def read_retry_interval\n options[:read_retry_interval] || Cluster::READ_RETRY_INTERVAL\n end", "def read(num_bytes)\n unless IO.select([@socket], nil, nil, @timeout)\n raise Errno::ETIMEDOUT\n end\n\n @socket.read(num_bytes)\n rescue IO::EAGAINWaitReadable\n retry\n end", "def read(len, timeout)\n socket.read_nonblock(len)\n rescue IO::WaitReadable\n retry if IO.select([socket], nil, nil, timeout)\n end", "def read_with_one_retry\n yield\n rescue Error::SocketError, Error::SocketTimeoutError\n yield\n end", "def receive_nonblock(options)\n return options[:socket].recvfrom_nonblock(USHRT_MAX)\n rescue IO::WaitReadable\n IO.select([options[:socket]])\n\n retry\n end", "def read_write\n connection = nil\n # In the event of a failover the primary may be briefly unavailable.\n # Instead of immediately grinding to a halt we'll retry the operation\n # a few times.\n retry_with_backoff do\n connection = pool.connection\n yield connection\n end\n end", "def read_using_load_balancer(...)\n if current_session.use_primary? &&\n !current_session.use_replicas_for_read_queries?\n @load_balancer.read_write do |connection|\n connection.send(...)\n end\n else\n @load_balancer.read do |connection|\n connection.send(...)\n end\n end\n end", "def with_raw_connection(allow_retry: false, materialize_transactions: true)\n @lock.synchronize do\n connect! if @raw_connection.nil? && reconnect_can_restore_state?\n\n self.materialize_transactions if materialize_transactions\n\n retries_available = allow_retry ? connection_retries : 0\n deadline = retry_deadline && Process.clock_gettime(Process::CLOCK_MONOTONIC) + retry_deadline\n reconnectable = reconnect_can_restore_state?\n\n if @verified\n # Cool, we're confident the connection's ready to use. (Note this might have\n # become true during the above #materialize_transactions.)\n elsif reconnectable\n if allow_retry\n # Not sure about the connection yet, but if anything goes wrong we can\n # just reconnect and re-run our query\n else\n # We can reconnect if needed, but we don't trust the upcoming query to be\n # safely re-runnable: let's verify the connection to be sure\n verify!\n end\n else\n # We don't know whether the connection is okay, but it also doesn't matter:\n # we wouldn't be able to reconnect anyway. We're just going to run our query\n # and hope for the best.\n end\n\n begin\n result = yield @raw_connection\n @verified = true\n result\n rescue => original_exception\n translated_exception = translate_exception_class(original_exception, nil, nil)\n invalidate_transaction(translated_exception)\n retry_deadline_exceeded = deadline && deadline < Process.clock_gettime(Process::CLOCK_MONOTONIC)\n\n if !retry_deadline_exceeded && retries_available > 0\n retries_available -= 1\n\n if retryable_query_error?(translated_exception)\n backoff(connection_retries - retries_available)\n retry\n elsif reconnectable && retryable_connection_error?(translated_exception)\n reconnect!(restore_transactions: true)\n # Only allowed to reconnect once, because reconnect! has its own retry\n # loop\n reconnectable = false\n retry\n end\n end\n\n unless retryable_query_error?(translated_exception)\n # Barring a known-retryable error inside the query (regardless of\n # whether we were in a _position_ to retry it), we should infer that\n # there's likely a real problem with the connection.\n @verified = false\n end\n\n raise translated_exception\n ensure\n dirty_current_transaction if materialize_transactions\n end\n end\n end", "def max_read_retries\n options[:max_read_retries] || Cluster::MAX_READ_RETRIES\n end", "def do_read\n read_action\n rescue IO::WaitReadable, Errno::EINTR, Errno::EAGAIN\n return\n end", "def read_with_one_retry(options = nil)\n yield\n rescue *retryable_exceptions, Error::PoolError => e\n raise e unless e.write_retryable?\n\n retry_message = options && options[:retry_message]\n log_retry(e, message: retry_message)\n yield\n end", "def read_retry_interval\n options[:read_retry_interval] || READ_RETRY_INTERVAL\n end", "def retry_reads?\n client.options[:retry_reads] != false\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute a read operation with a single retry on network errors. This method is used by the driver for some of the internal housekeeping operations. Applicationrequested reads should use read_with_retry rather than this method.
def read_with_one_retry(options = nil) yield rescue Error::SocketError, Error::SocketTimeoutError => e retry_message = options && options[:retry_message] log_retry(e, message: retry_message) yield end
[ "def read_with_one_retry\n yield\n rescue Error::SocketError, Error::SocketTimeoutError\n yield\n end", "def read_with_one_retry(options = nil)\n yield\n rescue *retryable_exceptions, Error::PoolError => e\n raise e unless e.write_retryable?\n\n retry_message = options && options[:retry_message]\n log_retry(e, message: retry_message)\n yield\n end", "def retry_read(original_error, session, server_selector, failed_server: nil, &block)\n begin\n server = select_server(cluster, server_selector, session, failed_server)\n rescue Error, Error::AuthError => e\n original_error.add_note(\"later retry failed: #{e.class}: #{e}\")\n raise original_error\n end\n \n log_retry(original_error, message: 'Read retry')\n \n begin\n yield server, true\n rescue *retryable_exceptions => e\n e.add_notes('modern retry', 'attempt 2')\n raise e\n rescue Error::OperationFailure, Error::PoolError => e\n e.add_note('modern retry')\n unless e.write_retryable?\n original_error.add_note(\"later retry failed: #{e.class}: #{e}\")\n raise original_error\n end\n e.add_note(\"attempt 2\")\n raise e\n rescue Error, Error::AuthError => e\n e.add_note('modern retry')\n original_error.add_note(\"later retry failed: #{e.class}: #{e}\")\n raise original_error\n end\n end", "def legacy_read_with_retry(session, server_selector, &block)\n attempt = attempt ? attempt + 1 : 1\n yield select_server(cluster, server_selector, session)\n rescue *retryable_exceptions, Error::OperationFailure, Error::PoolError => e\n e.add_notes('legacy retry', \"attempt #{attempt}\")\n \n if is_retryable_exception?(e)\n raise e if attempt > client.max_read_retries || session&.in_transaction?\n elsif e.retryable? && !session&.in_transaction?\n raise e if attempt > client.max_read_retries\n else\n raise e\n end\n \n log_retry(e, message: 'Legacy read retry')\n sleep(client.read_retry_interval) unless is_retryable_exception?(e)\n retry\n end", "def read_with_retry(session = nil, server_selector = nil, &block)\n if session.nil? && server_selector.nil?\n deprecated_legacy_read_with_retry(&block)\n elsif session&.retry_reads?\n modern_read_with_retry(session, server_selector, &block)\n elsif client.max_read_retries > 0\n legacy_read_with_retry(session, server_selector, &block)\n else\n read_without_retry(session, server_selector, &block)\n end\n end", "def do_read\n read_action\n rescue IO::WaitReadable, Errno::EINTR, Errno::EAGAIN\n return\n end", "def read_retry_interval\n options[:read_retry_interval] || READ_RETRY_INTERVAL\n end", "def retry_reads?\n client.options[:retry_reads] != false\n end", "def run\n fail_count = 0\n begin\n yield\n rescue StandardError => e\n fail_count += 1\n if fail_count < @max_retries && retriable?(e)\n sleep @delay if @delay\n retry\n end\n raise e\n end\n end", "def deprecated_legacy_read_with_retry(&block)\n deprecation_warning :read_with_retry,\n 'Legacy read_with_retry invocation - ' \\\n 'please update the application and/or its dependencies'\n\n # Since we don't have a session, we cannot use the modern read retries.\n # And we need to select a server but we don't have a server selector.\n # Use PrimaryPreferred which will work as long as there is a data\n # bearing node in the cluster; the block may select a different server\n # which is fine.\n server_selector = ServerSelector.get(mode: :primary_preferred)\n legacy_read_with_retry(nil, server_selector, &block)\n end", "def read_retry_interval\n options[:read_retry_interval] || Cluster::READ_RETRY_INTERVAL\n end", "def retry_read_events_forward(stream_name, start, count, poll = 0, max_retries: 0)\n retrying_on_network_failures(max_retries) do\n safe_read_events(stream_name, start, count, poll)\n end\n end", "def retry_request(http, *args)\n 5.times do\n begin\n return http.send(:send_request, *args)\n rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH\n Chef::Log.debug('couchdb connection failed')\n end\n sleep 1\n end\n Chef::Log.debug('failed to connect to couchdb after 5 tries ... failing chef run')\n fail 'unable to connect to couchdb'\n end", "def read_with_retry(session = nil, server_selector = nil, &block)\n if session.nil? && server_selector.nil?\n # Older versions of Mongoid call read_with_retry without arguments.\n # This is already not correct in a MongoDB 3.6+ environment with\n # sessions. For compatibility we emulate the legacy driver behavior\n # here but upgrading Mongoid is strongly recommended.\n unless $_mongo_read_with_retry_warned\n $_mongo_read_with_retry_warned = true\n Logger.logger.warn(\"Legacy read_with_retry invocation - please update the application and/or its dependencies\")\n end\n # Since we don't have a session, we cannot use the modern read retries.\n # And we need to select a server but we don't have a server selector.\n # Use PrimaryPreferred which will work as long as there is a data\n # bearing node in the cluster; the block may select a different server\n # which is fine.\n server_selector = ServerSelector.get(mode: :primary_preferred)\n legacy_read_with_retry(nil, server_selector, &block)\n elsif session && session.retry_reads?\n modern_read_with_retry(session, server_selector, &block)\n elsif client.max_read_retries > 0\n legacy_read_with_retry(session, server_selector, &block)\n else\n server = select_server(cluster, server_selector, session)\n yield server\n end\n end", "def do_read\n read_action\n rescue IO::WaitReadable, Errno::EINTR, Errno::EAGAIN\n @wait_readable = true\n else\n @wait_readable = false\n end", "def retry_on_transient_error\n (options.retry_count.to_i + 1).times do |n|\n logger.debug \"Attempt ##{n}\"\n begin\n result = yield\n rescue Fog::Compute::AWS::Error => e\n sleep_seconds = options.retry_interval * (n+1)\n logger.warn \"Received AWS error: #{e}\"\n logger.warn \"Sleeping #{sleep_seconds} seconds before retrying\"\n sleep sleep_seconds\n else\n return result\n end\n end\n nil\n end", "def retry_call endpoint\r\n\t \t@retries_left -= 1\r\n\r\n\t \tsleepTime = (50 + rand(950)) / 1000\r\n\t \tsleep(sleepTime)\r\n\r\n\t \tcall(endpoint)\r\n\t end", "def with_raw_connection(allow_retry: false, materialize_transactions: true)\n @lock.synchronize do\n connect! if @raw_connection.nil? && reconnect_can_restore_state?\n\n self.materialize_transactions if materialize_transactions\n\n retries_available = allow_retry ? connection_retries : 0\n deadline = retry_deadline && Process.clock_gettime(Process::CLOCK_MONOTONIC) + retry_deadline\n reconnectable = reconnect_can_restore_state?\n\n if @verified\n # Cool, we're confident the connection's ready to use. (Note this might have\n # become true during the above #materialize_transactions.)\n elsif reconnectable\n if allow_retry\n # Not sure about the connection yet, but if anything goes wrong we can\n # just reconnect and re-run our query\n else\n # We can reconnect if needed, but we don't trust the upcoming query to be\n # safely re-runnable: let's verify the connection to be sure\n verify!\n end\n else\n # We don't know whether the connection is okay, but it also doesn't matter:\n # we wouldn't be able to reconnect anyway. We're just going to run our query\n # and hope for the best.\n end\n\n begin\n result = yield @raw_connection\n @verified = true\n result\n rescue => original_exception\n translated_exception = translate_exception_class(original_exception, nil, nil)\n invalidate_transaction(translated_exception)\n retry_deadline_exceeded = deadline && deadline < Process.clock_gettime(Process::CLOCK_MONOTONIC)\n\n if !retry_deadline_exceeded && retries_available > 0\n retries_available -= 1\n\n if retryable_query_error?(translated_exception)\n backoff(connection_retries - retries_available)\n retry\n elsif reconnectable && retryable_connection_error?(translated_exception)\n reconnect!(restore_transactions: true)\n # Only allowed to reconnect once, because reconnect! has its own retry\n # loop\n reconnectable = false\n retry\n end\n end\n\n unless retryable_query_error?(translated_exception)\n # Barring a known-retryable error inside the query (regardless of\n # whether we were in a _position_ to retry it), we should infer that\n # there's likely a real problem with the connection.\n @verified = false\n end\n\n raise translated_exception\n ensure\n dirty_current_transaction if materialize_transactions\n end\n end\n end", "def retry_service(e) # e == rescued error\n\t\t\tif self.tries <= 10\n\t\t\t\tself.tries += 1\n\t\t\t\t# puts \"Connection issues... retrying in 3 seconds\"\n\t\t\t\tsleep(3)\n\t\t\t\tself.call_service\n\t\t\telse\n\t\t\t\tputs \"Backtrace: #{e.backtrace}\"\n\t\t\t\tputs \"BIG TIME ERROR getting: #{self.url}\"\n\t\t\tend\n\t\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retryable writes wrapper for operations not supporting modern retryable writes. If the driver is configured to use modern retryable writes, this method yields to the passed block exactly once, thus not retrying any writes. If the driver is configured to use legacy retryable writes, this method delegates to legacy_write_with_retry which performs write retries using legacy logic.
def nro_write_with_retry(session, write_concern, &block) if session && session.client.options[:retry_writes] server = select_server(cluster, ServerSelector.primary, session) yield server else legacy_write_with_retry(nil, session, &block) end end
[ "def nro_write_with_retry(write_concern, context:, &block)\n session = context.session\n server = select_server(cluster, ServerSelector.primary, session)\n \n if session&.client.options[:retry_writes]\n begin\n server.with_connection(connection_global_id: context.connection_global_id) do |connection|\n yield connection, nil, context\n end\n rescue *retryable_exceptions, Error::PoolError, Error::OperationFailure => e\n e.add_note('retries disabled')\n raise e\n end\n else\n legacy_write_with_retry(server, context: context, &block)\n end\n end", "def legacy_write_with_retry(server = nil, context:)\n session = context.session\n\n # This is the pre-session retry logic, and is not subject to\n # current retryable write specifications.\n # In particular it does not retry on SocketError and SocketTimeoutError.\n attempt = 0\n begin\n attempt += 1\n server ||= select_server(cluster, ServerSelector.primary, session)\n server.with_connection(connection_global_id: context.connection_global_id) do |connection|\n # Legacy retries do not use txn_num\n yield connection, nil, context.dup\n end\n rescue Error::OperationFailure => e\n e.add_note('legacy retry')\n e.add_note(\"attempt #{attempt}\")\n server = nil\n if attempt > client.max_write_retries\n raise e\n end\n if e.label?('RetryableWriteError')\n log_retry(e, message: 'Legacy write retry')\n cluster.scan!(false)\n retry\n else\n raise e\n end\n end\n end", "def write_with_retry\n attempt = 0\n begin\n attempt += 1\n yield\n rescue Error::OperationFailure => e\n raise(e) if attempt > Cluster::MAX_WRITE_RETRIES\n if e.write_retryable?\n log_retry(e)\n cluster.scan!\n retry\n else\n raise(e)\n end\n end\n end", "def legacy_write_with_retry(server = nil, session = nil)\n # This is the pre-session retry logic, and is not subject to\n # current retryable write specifications.\n # In particular it does not retry on SocketError and SocketTimeoutError.\n attempt = 0\n begin\n attempt += 1\n server ||= select_server(cluster, ServerSelector.primary, session)\n yield server\n rescue Error::OperationFailure => e\n server = nil\n if attempt > client.max_write_retries\n raise\n end\n if e.write_retryable? && !(session && session.in_transaction?)\n log_retry(e, message: 'Legacy write retry')\n cluster.scan!(false)\n retry\n else\n raise\n end\n end\n end", "def retry_write(original_error, txn_num, context:, failed_server: nil, &block)\n session = context.session\n\n # We do not request a scan of the cluster here, because error handling\n # for the error which triggered the retry should have updated the\n # server description and/or topology as necessary (specifically,\n # a socket error or a not master error should have marked the respective\n # server unknown). Here we just need to wait for server selection.\n server = select_server(cluster, ServerSelector.primary, session, failed_server)\n \n unless server.retry_writes?\n # Do not need to add \"modern retry\" here, it should already be on\n # the first exception.\n original_error.add_note('did not retry because server selected for retry does not support retryable writes')\n\n # When we want to raise the original error, we must not run the\n # rescue blocks below that add diagnostics because the diagnostics\n # added would either be rendundant (e.g. modern retry note) or wrong\n # (e.g. \"attempt 2\", we are raising the exception produced in the\n # first attempt and haven't attempted the second time). Use the\n # special marker class to bypass the ordinarily applicable rescues.\n raise Error::RaiseOriginalError\n end\n \n log_retry(original_error, message: 'Write retry')\n server.with_connection(connection_global_id: context.connection_global_id) do |connection|\n yield(connection, txn_num, context)\n end\n rescue *retryable_exceptions, Error::PoolError => e\n fail_on_retryable!(e, original_error)\n rescue Error::OperationFailure => e\n fail_on_operation_failure!(e, original_error)\n rescue Error, Error::AuthError => e\n fail_on_other_error!(e, original_error)\n rescue Error::RaiseOriginalError\n raise original_error\n end", "def ensure_retryable!(e)\n if e.unsupported_retryable_write?\n raise_unsupported_error(e)\n elsif !e.label?('RetryableWriteError')\n raise e\n end\n end", "def retry_writes?\n !!client.options[:retry_writes] && (cluster.replica_set? || cluster.sharded? || cluster.load_balanced?)\n end", "def retryable(&block)\n yield\n end", "def retry_writes?\n !!cluster.options[:retry_writes] && (cluster.replica_set? || cluster.sharded?)\n end", "def read_with_one_retry(options = nil)\n yield\n rescue *retryable_exceptions, Error::PoolError => e\n raise e unless e.write_retryable?\n\n retry_message = options && options[:retry_message]\n log_retry(e, message: retry_message)\n yield\n end", "def retry_write_allowed?(session, write_concern)\n return false unless session&.retry_writes?\n\n if write_concern.nil?\n true\n else\n WriteConcern.get(write_concern).acknowledged?\n end\n end", "def deprecated_legacy_read_with_retry(&block)\n deprecation_warning :read_with_retry,\n 'Legacy read_with_retry invocation - ' \\\n 'please update the application and/or its dependencies'\n\n # Since we don't have a session, we cannot use the modern read retries.\n # And we need to select a server but we don't have a server selector.\n # Use PrimaryPreferred which will work as long as there is a data\n # bearing node in the cluster; the block may select a different server\n # which is fine.\n server_selector = ServerSelector.get(mode: :primary_preferred)\n legacy_read_with_retry(nil, server_selector, &block)\n end", "def with_write_lock( blocking=true )\n\t\tbegin\n\t\t\tself.write_lock( blocking ) or raise Errno::EAGAIN\n\t\t\tyield\n\t\tensure\n\t\t\tself.release_write_lock\n\t\tend\n\tend", "def max_write_retries\n options[:max_write_retries] || Cluster::MAX_WRITE_RETRIES\n end", "def read_write\n connection = nil\n # In the event of a failover the primary may be briefly unavailable.\n # Instead of immediately grinding to a halt we'll retry the operation\n # a few times.\n retry_with_backoff do\n connection = pool.connection\n yield connection\n end\n end", "def legacy_read_with_retry(session, server_selector, &block)\n attempt = attempt ? attempt + 1 : 1\n yield select_server(cluster, server_selector, session)\n rescue *retryable_exceptions, Error::OperationFailure, Error::PoolError => e\n e.add_notes('legacy retry', \"attempt #{attempt}\")\n \n if is_retryable_exception?(e)\n raise e if attempt > client.max_read_retries || session&.in_transaction?\n elsif e.retryable? && !session&.in_transaction?\n raise e if attempt > client.max_read_retries\n else\n raise e\n end\n \n log_retry(e, message: 'Legacy read retry')\n sleep(client.read_retry_interval) unless is_retryable_exception?(e)\n retry\n end", "def while_preventing_writes(enabled = T.unsafe(nil), &block); end", "def await_written(string)\n write_nonblock(string)\n rescue IO::WaitWritable\n await_writable\n retry\n end", "def synchronize_write\n lock_write\n begin\n yield\n ensure\n unlock_write\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements legacy write retrying functionality by yielding to the passed block one or more times. This method is used for operations which are not supported by modern retryable writes, such as delete_many and update_many.
def legacy_write_with_retry(server = nil, session = nil) # This is the pre-session retry logic, and is not subject to # current retryable write specifications. # In particular it does not retry on SocketError and SocketTimeoutError. attempt = 0 begin attempt += 1 server ||= select_server(cluster, ServerSelector.primary, session) yield server rescue Error::OperationFailure => e server = nil if attempt > client.max_write_retries raise end if e.write_retryable? && !(session && session.in_transaction?) log_retry(e, message: 'Legacy write retry') cluster.scan!(false) retry else raise end end end
[ "def write_with_retry\n attempt = 0\n begin\n attempt += 1\n yield\n rescue Error::OperationFailure => e\n raise(e) if attempt > Cluster::MAX_WRITE_RETRIES\n if e.write_retryable?\n log_retry(e)\n cluster.scan!\n retry\n else\n raise(e)\n end\n end\n end", "def legacy_write_with_retry(server = nil, context:)\n session = context.session\n\n # This is the pre-session retry logic, and is not subject to\n # current retryable write specifications.\n # In particular it does not retry on SocketError and SocketTimeoutError.\n attempt = 0\n begin\n attempt += 1\n server ||= select_server(cluster, ServerSelector.primary, session)\n server.with_connection(connection_global_id: context.connection_global_id) do |connection|\n # Legacy retries do not use txn_num\n yield connection, nil, context.dup\n end\n rescue Error::OperationFailure => e\n e.add_note('legacy retry')\n e.add_note(\"attempt #{attempt}\")\n server = nil\n if attempt > client.max_write_retries\n raise e\n end\n if e.label?('RetryableWriteError')\n log_retry(e, message: 'Legacy write retry')\n cluster.scan!(false)\n retry\n else\n raise e\n end\n end\n end", "def retryable(&block)\n yield\n end", "def nro_write_with_retry(write_concern, context:, &block)\n session = context.session\n server = select_server(cluster, ServerSelector.primary, session)\n \n if session&.client.options[:retry_writes]\n begin\n server.with_connection(connection_global_id: context.connection_global_id) do |connection|\n yield connection, nil, context\n end\n rescue *retryable_exceptions, Error::PoolError, Error::OperationFailure => e\n e.add_note('retries disabled')\n raise e\n end\n else\n legacy_write_with_retry(server, context: context, &block)\n end\n end", "def nro_write_with_retry(session, write_concern, &block)\n if session && session.client.options[:retry_writes]\n server = select_server(cluster, ServerSelector.primary, session)\n yield server\n else\n legacy_write_with_retry(nil, session, &block)\n end\n end", "def retry_write(original_error, txn_num, context:, failed_server: nil, &block)\n session = context.session\n\n # We do not request a scan of the cluster here, because error handling\n # for the error which triggered the retry should have updated the\n # server description and/or topology as necessary (specifically,\n # a socket error or a not master error should have marked the respective\n # server unknown). Here we just need to wait for server selection.\n server = select_server(cluster, ServerSelector.primary, session, failed_server)\n \n unless server.retry_writes?\n # Do not need to add \"modern retry\" here, it should already be on\n # the first exception.\n original_error.add_note('did not retry because server selected for retry does not support retryable writes')\n\n # When we want to raise the original error, we must not run the\n # rescue blocks below that add diagnostics because the diagnostics\n # added would either be rendundant (e.g. modern retry note) or wrong\n # (e.g. \"attempt 2\", we are raising the exception produced in the\n # first attempt and haven't attempted the second time). Use the\n # special marker class to bypass the ordinarily applicable rescues.\n raise Error::RaiseOriginalError\n end\n \n log_retry(original_error, message: 'Write retry')\n server.with_connection(connection_global_id: context.connection_global_id) do |connection|\n yield(connection, txn_num, context)\n end\n rescue *retryable_exceptions, Error::PoolError => e\n fail_on_retryable!(e, original_error)\n rescue Error::OperationFailure => e\n fail_on_operation_failure!(e, original_error)\n rescue Error, Error::AuthError => e\n fail_on_other_error!(e, original_error)\n rescue Error::RaiseOriginalError\n raise original_error\n end", "def read_with_one_retry(options = nil)\n yield\n rescue *retryable_exceptions, Error::PoolError => e\n raise e unless e.write_retryable?\n\n retry_message = options && options[:retry_message]\n log_retry(e, message: retry_message)\n yield\n end", "def retry_transaction(&block)\n tries = 3\n begin\n yield\n rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique\n tries -= 1\n if tries > 0\n retry\n else\n raise\n end\n end\n end", "def with_retry #block\n num_attempts = 0\n begin\n num_attempts += 1\n yield\n rescue Twitter::Error::TooManyRequests => error\n if num_attempts <= MAX_RETRIES\n # NOTE: Your process could go to sleep for up to 15 minutes but if you\n # retry any sooner, it will almost certainly fail with the same exception.\n puts \"RETRY in #{error.rate_limit.reset_in}\"\n sleep error.rate_limit.reset_in\n retry\n else\n raise\n end\n end\n end", "def do_retries\n yield\n rescue @from => e\n raise e unless (@tries -= 1).positive?\n\n sleep (@sleep_duration += 1)**2 if @backoff # rubocop:disable Lint/ParenthesesAsGroupedExpression\n retry\n end", "def read_write\n connection = nil\n # In the event of a failover the primary may be briefly unavailable.\n # Instead of immediately grinding to a halt we'll retry the operation\n # a few times.\n retry_with_backoff do\n connection = pool.connection\n yield connection\n end\n end", "def attempt(&block)\n count = 1\n begin\n if @timeout\n File::ALT_SEPARATOR ? Timeout.timeout(@timeout, &block) : SafeTimeout.timeout(@timeout, &block)\n else\n yield\n end\n rescue @level => err\n @tries -= 1\n if @tries > 0\n msg = \"Error on attempt # #{count}: #{err}; retrying\"\n count += 1\n warn Warning, msg if @warnings\n\n if @log # Accept an IO or Logger object\n @log.respond_to?(:puts) ? @log.puts(msg) : @log.warn(msg)\n end\n\n @interval += @increment if @increment\n sleep @interval\n retry\n end\n raise\n end\n end", "def retry_read(original_error, session, server_selector, failed_server: nil, &block)\n begin\n server = select_server(cluster, server_selector, session, failed_server)\n rescue Error, Error::AuthError => e\n original_error.add_note(\"later retry failed: #{e.class}: #{e}\")\n raise original_error\n end\n \n log_retry(original_error, message: 'Read retry')\n \n begin\n yield server, true\n rescue *retryable_exceptions => e\n e.add_notes('modern retry', 'attempt 2')\n raise e\n rescue Error::OperationFailure, Error::PoolError => e\n e.add_note('modern retry')\n unless e.write_retryable?\n original_error.add_note(\"later retry failed: #{e.class}: #{e}\")\n raise original_error\n end\n e.add_note(\"attempt 2\")\n raise e\n rescue Error, Error::AuthError => e\n e.add_note('modern retry')\n original_error.add_note(\"later retry failed: #{e.class}: #{e}\")\n raise original_error\n end\n end", "def with_limited_retry(opts)\n tries = opts.fetch :tries\n exceptions = Array(opts.fetch(:exceptions))\n\n return if tries == 0\n\n begin\n yield\n rescue *exceptions\n Chef::Log.warn('Bad response, try again...')\n if (tries -= 1) > 0\n sleep 1\n retry\n end\n end\n end", "def ensure_retryable!(e)\n if e.unsupported_retryable_write?\n raise_unsupported_error(e)\n elsif !e.label?('RetryableWriteError')\n raise e\n end\n end", "def legacy_read_with_retry(session, server_selector, &block)\n attempt = attempt ? attempt + 1 : 1\n yield select_server(cluster, server_selector, session)\n rescue *retryable_exceptions, Error::OperationFailure, Error::PoolError => e\n e.add_notes('legacy retry', \"attempt #{attempt}\")\n \n if is_retryable_exception?(e)\n raise e if attempt > client.max_read_retries || session&.in_transaction?\n elsif e.retryable? && !session&.in_transaction?\n raise e if attempt > client.max_read_retries\n else\n raise e\n end\n \n log_retry(e, message: 'Legacy read retry')\n sleep(client.read_retry_interval) unless is_retryable_exception?(e)\n retry\n end", "def with_limited_retry(opts)\n tries = opts.fetch :tries\n wait_time = opts.fetch :wait_time, 2\n exceptions = Array(opts.fetch(:exceptions))\n\n return if tries == 0\n\n begin\n yield\n rescue *exceptions\n if (tries -= 1) > 0\n sleep wait_time\n retry\n end\n end\n end", "def batch(&block)\n @batch = true\n yield\n refresh_views\n document_store.write_indexes\n @batch = false\n end", "def perform(&block)\n response = nil\n tries = 0\n while response.blank?\n break if tries > @options[:max_retries]\n response = block.call\n tries += 1\n sleep @options[:sleep]\n end\n response\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
You are writing the user registration page for a secure web site. On the registration page, the user has to enter a user ID and a password, which has to adhere to the to following criteria: User ID and password cannot be the same User ID and password have to be at least six characters long Password has to contain at least one of: !$ User ID cannot contain the following characters: !$ and space Password cannot be the word "password" Challenge: Write a function called same that takes a user ID and a password, and returns true if they are, and false otherwise.
def same (user_id, password) if user_id.downcase == password.downcase puts "User ID and password cannot be the same" else puts "Acceptable" end end
[ "def user_registration\n\n puts \"Enter a user ID.\"\n user_id = gets.chomp\n\n puts \"Enter a password\"\n password = gets.chomp\n\n if !same?(user_id, password) && long_enough(user_id) && long_enough(password) && contains_special(password) && does_not_contain_special(user_id) && password != \"password\"\n \"Your user information is valid!\"\n else\n \"Invalid credentials! try again\"\n end\n\nend", "def same(user_id, password)\n if user_id == password\n 'True'\n else\n 'False'\n end\nend", "def same?(user_id, password)\n user_id.to_s == password.to_s ? true : false\nend", "def validate_password\n puts \"Enter your User ID and Password here.\"\n user_id = gets.chomp\n password = gets.chomp\n\n same(user_id, password)\n long_enough(user_id)\n long_enough(password)\n does_not_contain_special(user_id)\n contains_special(password)\n is_password(password)\nend", "def validate_password()\n puts 'Enter your User ID'\n user_id = gets\n puts 'Enter your password'\n password = gets\n if same(user_id,password) == 'True'\n p 'user ID and password cannot match'\n elsif long_enough(user_id, password) == 'False'\n p 'user ID and password must be at least 6 characters'\n elsif does_not_contain_special(password) == 'True'\n p 'password must include a symbol #, ! or $'\n elsif user_id.include?('#') or user_id.include?('!') or user_id.include?('$') or user_id.include?(' ')\n p 'user ID cannot include the following symbols #, ! or $'\n elsif password == 'password'\n p 'password cannot be the word \"password\"'\n else\n p 'User ID and password are acceptable'\n end\nend", "def input(user_id, password)\n if user_id == password\n 'Password and username cannot be the same'\n elsif user_id.length <= 6 && password.length <= 6\n 'Password and username must be at least six characters long'\n end\nend", "def valid_password?(password); end", "def Check(username, password)\n=begin Legacy Code Block\n table = @logindb.Load() # Load the table. We really need something that does this and the next line in one and more efficiently\n usernameID = table.each_index.select {|id| table[id][:username] == username } # should be a length=1 array\n # entry = table[usernameID[0]] # Get the actual entry\n=end\n\t\tentry = @logindb.LoadSingleByVar(:username, username)\n correct = entry[:processed] # the correct salted + hashed password\n salt = entry[:salt] # the salt\n input = Digest::SHA256.hexdigest(password+salt) # the processed password the user is using\n \n if input == correct\n return entry[:id] # the user ID\n end\n end", "def check_password_contents\n if /[a-zA-Z]+/.match(@password) && /\\d+/.match(@password) && /[[:punct:]]/.match(@password)\n else\n generate\n end\n end", "def password_match?\n @passwords.fetch(@username) == @password\n end", "def matching_password?(pass)\n self.password_hash == encrypt_password(pass)\n end", "def matches_pw?(submitted_pw)\n encrypted_pw == encrypt(submitted_pw)\n end", "def check_password\n unless self.server_device? or self.username.blank? or self.provider or [\"dahdi\", \"virtual\", \"h323\"].include?(self.device_type.downcase)\n if self.name and self.secret.to_s == self.name.to_s\n errors.add(:secret, _(\"Name_And_Secret_Cannot_Be_Equal\"))\n return false\n end\n\n if self.secret.to_s.length < 8 and Confline.get_value(\"Allow_short_passwords_in_devices\").to_i == 0\n errors.add(:secret, _(\"Password_is_too_short\"))\n return false\n end\n end\n end", "def password_match?\n self.password == self.password_confirmation\n end", "def password_equals?(value)\n return hash_string(value) == self.password\n end", "def check_password(password)\n @password = password\n @hsh == get_hash\n end", "def password(user, exists)\n if exists then\n puts \"Welcome #{user.name}, please enter your password.\"\n puts \"If you want to sign with on username type 'n'.\"\n else\n puts \"You created a new user with name #{user.name}.\"\n puts 'Please type a password or just press enter for no password.'\n end\n password = \"qwertyuiopa\"\n while password.length > 10\n puts \"The password must not be more then 10 symbols!\"\n password = gets.chomp\n end\n password\n end", "def authenticate(name, password)\n if name != \"Santa Claus\" || password != \"Ho Ho Ho!\"\n return false\n end\n true\nend", "def valid_password?(password)\n compare(password)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that accepts a password and determins if it is the word "password." If so, inform the user that the password cannot be the word "password." Else, return acceptable.
def is_password(password) if password.downcase == "password" puts "Password cannot be the word password" else puts "Acceptable" end end
[ "def valid_password?(password); end", "def check_for_password_string?(password)\n !password.downcase.include?(\"password\")\nend", "def valid_password?(password)\n true\n end", "def valid_password?(password)\n compare(password)\n end", "def password\n password = @prompt.mask(\"Enter password: \", required: true)\n if password == @current_user.password\n true\n else\n puts \"Password is invalid.\"\n sleep(1)\n false\n end\n end", "def password_validation\n password = \"123456\"\n p \"What is the password?\"\n password_attempt = gets.chomp.to_s\n password == password_attempt ? \"Welcome!\" : \"I don't know you\"\nend", "def is_valid_password?(password)\n return false unless password.is_a? String\n \n invalid_password_if /^([a-z]+|[A-Z]+|\\d+|\\W+)$/ =~ password, 'must contain characters from least two of the following categories: uppercase, lowercase, numbers & symbols'\n \n invalid_password_if password.size<5, 'must be 5 or more characters long'\n\n password_problems.blank?\n end", "def check_password_contents\n if /[a-zA-Z]+/.match(@password) && /\\d+/.match(@password) && /[[:punct:]]/.match(@password)\n else\n generate\n end\n end", "def validate_password()\n puts 'Enter your User ID'\n user_id = gets\n puts 'Enter your password'\n password = gets\n if same(user_id,password) == 'True'\n p 'user ID and password cannot match'\n elsif long_enough(user_id, password) == 'False'\n p 'user ID and password must be at least 6 characters'\n elsif does_not_contain_special(password) == 'True'\n p 'password must include a symbol #, ! or $'\n elsif user_id.include?('#') or user_id.include?('!') or user_id.include?('$') or user_id.include?(' ')\n p 'user ID cannot include the following symbols #, ! or $'\n elsif password == 'password'\n p 'password cannot be the word \"password\"'\n else\n p 'User ID and password are acceptable'\n end\nend", "def acceptable?(password)\n return false if min && password.size < min\n return false if max && password.size > max\n\n !pwned?(password)\n end", "def check_password(password)\n raise ArgumentError, 'Error. Requires string input.' unless password.respond_to?(:split) # check if input is string\n invalids = []\n\n invalids << ' be at least 6 characters' if password.length < 6\n invalids << ' be no more than 20 characters' if password.length > 20\n invalids << ' contain at least one uppercase letter' unless !!(password =~ /[A-Z]+/)\n invalids << ' contain at least one digit OR special character: ! @ # $ % & * + : ?' unless !!(password =~ /[0-9]|[!@#\\$%&\\*\\+:\\?]/)\n invalids << ' not contain invalid characters' if !!(password =~ /[^ !@#\\$%&\\*\\+:\\?[:alnum:]]/)\n\n return 'Valid Password' if invalids.empty?\n \"Error. Passwords must:\\n\" + invalids.join(\"\\n\")\nend", "def not_forbidden?(password)\n forbidden_words = [\"password\"] # can add words to this list as necessary.\n result = true\n forbidden_words.each {|word| result = false if password.downcase.include?(word)}\n result\nend", "def at_least_one_caps?(password)\n password != password.downcase\nend", "def check_password\n unless self.server_device? or self.username.blank? or self.provider or [\"dahdi\", \"virtual\", \"h323\"].include?(self.device_type.downcase)\n if self.name and self.secret.to_s == self.name.to_s\n errors.add(:secret, _(\"Name_And_Secret_Cannot_Be_Equal\"))\n return false\n end\n\n if self.secret.to_s.length < 8 and Confline.get_value(\"Allow_short_passwords_in_devices\").to_i == 0\n errors.add(:secret, _(\"Password_is_too_short\"))\n return false\n end\n end\n end", "def validatePassword(password)\n if /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).[[:alnum:]]{6,}$/.match(password)\n return true\n else\n return false\n end\nend", "def password_ok?\n\t\tif !password.present? || password.length < 6\n\t\t\t@errors.add(:password, \"must be at least 6 characters\");\n\t\telsif ! password.match(/.*[0-9].*/)\n\t\t\t@errors.add(:password, \"must contain at least one number\");\n\t\telsif not password.match(/.*\\w.*/)\n\t\t\t@error.add(:password, \"must contain at least one character\");\n\t\tend\n\tend", "def ask_password(password)\n if password =~ /^[a-zA-Z0-9]{8,16}$/\n puts \"Password valid\"\n else\n puts \"Password invalid\"\n end\nend", "def match_password_basic(p)\n puts \"p: #{p}\"\n puts \"password: #{password}\"\n p == password\n end", "def contains_password?(password)\n password.gsub(/password/i, \"\") == password\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Challenge Write a method that inputs user ID and password from the user, and then tells the user if the they are acceptable. Write a main method called validate_password that: First lets a user input both user ID and password, Then use the methods above to evaluate if the user ID and password combination is acceptable or not Tells user what the result is.
def validate_password puts "Enter your User ID and Password here." user_id = gets.chomp password = gets.chomp same(user_id, password) long_enough(user_id) long_enough(password) does_not_contain_special(user_id) contains_special(password) is_password(password) end
[ "def validate_password()\n puts 'Enter your User ID'\n user_id = gets\n puts 'Enter your password'\n password = gets\n if same(user_id,password) == 'True'\n p 'user ID and password cannot match'\n elsif long_enough(user_id, password) == 'False'\n p 'user ID and password must be at least 6 characters'\n elsif does_not_contain_special(password) == 'True'\n p 'password must include a symbol #, ! or $'\n elsif user_id.include?('#') or user_id.include?('!') or user_id.include?('$') or user_id.include?(' ')\n p 'user ID cannot include the following symbols #, ! or $'\n elsif password == 'password'\n p 'password cannot be the word \"password\"'\n else\n p 'User ID and password are acceptable'\n end\nend", "def input(user_id, password)\n if user_id == password\n 'Password and username cannot be the same'\n elsif user_id.length <= 6 && password.length <= 6\n 'Password and username must be at least six characters long'\n end\nend", "def user_registration\n\n puts \"Enter a user ID.\"\n user_id = gets.chomp\n\n puts \"Enter a password\"\n password = gets.chomp\n\n if !same?(user_id, password) && long_enough(user_id) && long_enough(password) && contains_special(password) && does_not_contain_special(user_id) && password != \"password\"\n \"Your user information is valid!\"\n else\n \"Invalid credentials! try again\"\n end\n\nend", "def valid_password?(password); end", "def same (user_id, password)\n if user_id.downcase == password.downcase\n puts \"User ID and password cannot be the same\"\n else \n puts \"Acceptable\"\n end\nend", "def password_valid_for? game_id, password=params[:p]\n @game = Game.find(game_id)\n\n # Private game, ask them for a password\n if !@game.password.blank? && password != @game.password\n @wrong_password = !password.blank?\n render 'games/enter_password'\n end\n\n password\n end", "def password\n password = @prompt.mask(\"Enter password: \", required: true)\n if password == @current_user.password\n true\n else\n puts \"Password is invalid.\"\n sleep(1)\n false\n end\n end", "def password_validation\n password = \"123456\"\n p \"What is the password?\"\n password_attempt = gets.chomp.to_s\n password == password_attempt ? \"Welcome!\" : \"I don't know you\"\nend", "def valid_password?(password)\n compare(password)\n end", "def valid_password?(user, password)\n\tuser.password == password\nend", "def get_password\n status = true\n while status == true\n @password = @@prompt.mask(\"Create a password with at least 5 character\") do |q|\n q.validate(/[a-z\\ ]{5,15}/)\n end\n @password_2 = @@prompt.mask(\"Retype your password\") do |q|\n q.validate(/[a-z\\ ]{5,15}/)\n end\n if @password == @password_2\n system(\"clear\")\n status = false \n break\n else @password != @password_2\n puts \"Wrong password, try again\".colorize(:red)\n status = true\n end\n end\n end", "def valid_password?(password, username)\nat_least_one_caps?(password) &&\nat_least_one_downcase?(password) &&\nat_least_eight_characters?(password) &&\nis_alphanumeric?(password) &&\nincludes_number?(password) &&\ndoesnt_include_password?(password) &&\nnot_including_username?(password, username)\nend", "def check_password(password)\n raise ArgumentError, 'Error. Requires string input.' unless password.respond_to?(:split) # check if input is string\n invalids = []\n\n invalids << ' be at least 6 characters' if password.length < 6\n invalids << ' be no more than 20 characters' if password.length > 20\n invalids << ' contain at least one uppercase letter' unless !!(password =~ /[A-Z]+/)\n invalids << ' contain at least one digit OR special character: ! @ # $ % & * + : ?' unless !!(password =~ /[0-9]|[!@#\\$%&\\*\\+:\\?]/)\n invalids << ' not contain invalid characters' if !!(password =~ /[^ !@#\\$%&\\*\\+:\\?[:alnum:]]/)\n\n return 'Valid Password' if invalids.empty?\n \"Error. Passwords must:\\n\" + invalids.join(\"\\n\")\nend", "def check_password\n\t\t\tpassword_attempts = 2\n\t\t\tputs \"Please enter your password: \"\n\t\t\tprompt\n\t\t\tanswer = gets.chomp\n\t\t\t#If answer matches password, calls atm_transactions method and customer can proceed.\n\t\t\tif answer == @password\n\t\t\t\tatm_transactions\n\t\t\telse\n\t\t\t\tuntil password_attempts == 0\n\t\t\t\t\tputs \"\\nYou did not enter the correct password.\"\n\t\t\t\t\tputs \"Please enter your password. You have #{password_attempts} password attempts left.\"\n\t\t\t\t\tprompt\n\t\t\t\t\tanswer = gets.chomp\n\t\t\t\t\tif answer == @password\n\t\t\t\t\t\tatm_transactions\n\t\t\t\t\t\texit\n\t\t\t\t\tend\n\t\t\t\t\tpassword_attempts -=1\n\t\t\t\tend\n\t\t\t\tputs \"\\nYou have no more password attempts. Please try again later.\"\n\t\t\tend\n\t\tend", "def validate_password(password, options = {})\n options[:password] = password\n validate(options)\n end", "def db_verify_user_password(userid, password)\n\t\t\n\t\t# SQL statement for selecting * given a userid and a hashed password\n \tquery = \"SELECT * FROM users\n\t\t\t\tWHERE userid='%%email%%'\n\t\t\t\tAND password='%%password%%';\"\n\t\t\n\t\t# Fill in userid and password values in the SQL statement\n \tquery = query.gsub(/%%email%%/, PG::Connection.escape_string(userid)).gsub(/%%password%%/, hashPassword(password))\n \t\n \t# Connect to the database\n \tconn = DBTools.new.connectToDB()\n \t\n \t# Execute SQL Statement\n results = conn.exec(query)\n \n # If there are 0 results\n if (results.ntuples == 0)\n \tresults.clear()\n conn.finish()\n return false\n\n # If there are too many results (this should never occur)\n elsif (results.ntuples > 1)\n \tresults.clear()\n \tconn.finish()\n raise \"Too many password matches.\"\n \n # Query successful\n else\n \tresults.clear()\n \tconn.finish()\n \treturn true\n end\n\tend", "def check_password\n student_id = params.require(:id)\n password = params.require(:password)\n login = Portal::Student.find(student_id).user.login\n return render :json => {'message' => 'ok'} if User.authenticate(login, password)\n return error({'password' => 'password incorrect'}, 401)\n end", "def check_password_contents\n if /[a-zA-Z]+/.match(@password) && /\\d+/.match(@password) && /[[:punct:]]/.match(@password)\n else\n generate\n end\n end", "def valid_password?(password)\n true\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Nokogiri XML DOM for the current Brominet XML representation of the GUI
def dom_for_gui @dom = Nokogiri::XML self.dump end
[ "def dom\r\n @dom = Nokogiri::XML @gui.dump\r\nend", "def get_xml_document\n Nokogiri::XML(self.body)\n end", "def document\n @doc ||= Nokogiri::XML(@xml)\n end", "def read_inner_xml()\n #This is a stub, used for indexing\n end", "def root_element\n root.xml \n end", "def xml_document\n xml = XML::Document.new\n xml.root = self.to_xml\n xml\n end", "def dom_root!\n result = @rpc.call 'DOM.getDocument'\n @dom_root = dom_update_node result['root']\n end", "def xml\n source_node\n end", "def doc\n @doc ||= Nokogiri::XML(@xml)\n end", "def inner_html\n self.inner_xml\n end", "def ownerDocument; @ownerDocument; end", "def get_root_element\n @root\n end", "def read_outer_xml()\n #This is a stub, used for indexing\n end", "def get_html_document\n Nokogiri::HTML(self.body)\n end", "def parse\n Ox.parse(@xml)\n end", "def document\n @web_view.mainFrame.DOMDocument\n end", "def createUIElements (xmlElement)\n\n if xmlElement.is_a? (Nokogiri::XML::Node)\n p 'XMLElement ' + xmlElement.name.to_s\n wrapper = nil\n\n #Create a xmlelementwrapper widget.\n wrapper = xmlelementwrapper :xmlElement => xmlElement, :doc => @xmlObject\n\n flow1 = flow :margin_left => 10 do\n\n\n #For each child, if it is an xml element recursively add to UI\n xmlElement.children.each do |node|\n\n if node.is_a? (Nokogiri::XML::Element)\n element = createUIElements(node)\n element.hideSelf()\n wrapper.addXMLElement(element)\n end\n end\n end\n\n\n #Set the flow\n wrapper.setFlow(flow1)\n\n return wrapper\n end\n\n end", "def root\n @xml.root\n end", "def getRootDomNode\n \n resultValue = false\n \n if @_domResultBody\n \n \n resultValue = @_domResultBody.root\n end\n return resultValue\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method will get the availability set using the resource group and availability set name will return whether or not the availability set exists.
def get(resource_group, availability_set) begin promise = @client.availability_sets.get(resource_group, availability_set).value! promise.body rescue MsRestAzure::AzureOperationError => e # if the error is that the availability set doesn't exist, # just return a nil if e.response.status == 404 puts 'Availability Set Not Found! Create It!' return nil end OOLog.fatal("Error getting availability set: #{e.body}") rescue => ex OOLog.fatal("Error getting availability set: #{ex.message}") end end
[ "def get\n begin\n promise = @client.availability_sets.get(@rg_name,@as_name).value!\n return promise\n rescue MsRestAzure::AzureOperationError => e\n # if the error is that the availability set doesn't exist,\n # just return a nil\n if e.response.status == 404\n puts 'Availability Set Not Found! Create It!'\n return nil\n end\n OOLog.fatal(\"Error getting availability set: #{e.body}\")\n rescue => ex\n OOLog.fatal(\"Error getting availability set: #{ex.message}\")\n end\n end", "def get\n begin\n @compute_client.availability_sets.get(@rg_name, @as_name)\n rescue MsRestAzure::AzureOperationError => e\n # if the error is that the availability set doesn't exist,\n # just return a nil\n if e.response.status == 404\n puts 'Availability Set Not Found! Create It!'\n return nil\n end\n OOLog.fatal(\"Error getting availability set: #{e.body}\")\n rescue => ex\n OOLog.fatal(\"Error getting availability set: #{ex.message}\")\n end\n end", "def add\n # check if it exists\n as = get\n if !as.nil?\n OOLog.info(\"Availability Set #{as.name} exists in the #{as.location} region.\")\n else\n # need to create the availability set\n OOLog.info(\"Creating Availability Set\n '#{@as_name}' in #{@location} region\")\n avail_set = get_avail_set_props\n begin\n response =\n @client.availability_sets.create_or_update(@rg_name,\n @as_name,\n avail_set).value!\n return response\n rescue MsRestAzure::AzureOperationError => e\n OOLog.fatal(\"Error adding an availability set: #{e.body}\")\n rescue => ex\n OOLog.fatal(\"Error adding an availability set: #{ex.message}\")\n end\n end\n end", "def get_availability_set(url)\n availability_set = nil\n result = get_resource_by_id(url)\n unless result.nil?\n availability_set = {}\n availability_set[:id] = result['id']\n availability_set[:name] = result['name']\n availability_set[:location] = result['location']\n availability_set[:tags] = result['tags']\n\n availability_set[:managed] = false\n availability_set[:managed] = true if !result['sku'].nil? && (result['sku']['name'] == 'Aligned')\n\n properties = result['properties']\n availability_set[:provisioning_state] = properties['provisioningState']\n availability_set[:platform_update_domain_count] = properties['platformUpdateDomainCount']\n availability_set[:platform_fault_domain_count] = properties['platformFaultDomainCount']\n availability_set[:virtual_machines] = []\n properties['virtualMachines']&.each do |vm|\n availability_set[:virtual_machines].push(id: vm['id'])\n end\n end\n availability_set\n end", "def create_availability_set\n t = Time.new\n puts \"#{t.hour}:#{t.min}:#{t.sec}\"\n puts \"\"\n puts \"Creating AvailabilitySet for Backend pool of Loadbalancer\"\n puts \"\"\n params = AvailabilitySet.new\n params.platform_update_domain_count = 5\n params.platform_fault_domain_count = 2\n params.managed = true\n params.location = \"CentralIndia\"\n promise = client.availability_sets.create_or_update(\"#{config[:resource_group]}\", \"#{config[:env]}_availability_set\", params)\n puts \"name = #{promise.name}\"\n puts \"id = #{promise.id}\"\n return promise.name\n end", "def add\n # check if it exists\n as_exist = @compute_client.availability_sets.check_availability_set_exists(@rg_name, @as_name)\n if as_exist\n OOLog.info(\"Availability Set #{@as_name} exists in the #{@location} region.\")\n else\n # need to create the availability set\n OOLog.info(\"Creating Availability Set '#{@as_name}' in #{@location} region\")\n\n begin\n #if we are using the managed disk attached to vm availability set needs to setup use_managed_disk to true\n\n\n @compute_client.availability_sets.create(resource_group: @rg_name, name: @as_name, location: @location, use_managed_disk: true, platform_fault_domain_count: Utils.get_fault_domains(@location\n ), platform_update_domain_count: Utils.get_update_domains)\n rescue MsRestAzure::AzureOperationError => e\n OOLog.fatal(\"Error adding an availability set: #{e.body}\")\n rescue => ex\n OOLog.fatal(\"Error adding an availability set: #{ex.message}\")\n end\n end\n end", "def create_availability_set(resource_group_name, params)\n url = rest_api_url(REST_API_PROVIDER_COMPUTE, REST_API_AVAILABILITY_SETS, resource_group_name: resource_group_name, name: params[:name])\n availability_set = {\n 'name' => params[:name],\n 'type' => \"#{REST_API_PROVIDER_COMPUTE}/#{REST_API_AVAILABILITY_SETS}\",\n 'location' => params[:location],\n 'tags' => params[:tags],\n 'properties' => {\n 'platformUpdateDomainCount' => params[:platform_update_domain_count],\n 'platformFaultDomainCount' => params[:platform_fault_domain_count]\n }\n }\n\n if params[:managed]\n availability_set['sku'] = {\n 'name' => 'Aligned'\n }\n end\n\n http_put(url, availability_set)\n end", "def add(resource_group, availability_set, location)\n # check if it exists\n existance_promise = get(resource_group, availability_set)\n if !existance_promise.nil?\n OOLog.info(\"Availability Set #{existance_promise.name} exists\n in the #{existance_promise.location} region.\")\n else\n # need to create the availability set\n OOLog.info(\"Creating Availability Set\n '#{availability_set}' in #{location} region\")\n avail_set = get_avail_set_props(location)\n begin\n start_time = Time.now.to_i\n response =\n @client.availability_sets.create_or_update(resource_group,\n availability_set,\n avail_set).value!\n response.body\n end_time = Time.now.to_i\n duration = end_time - start_time\n OOLog.info(\"Availability Set created in #{duration} seconds\")\n rescue MsRestAzure::AzureOperationError => e\n OOLog.fatal(\"Error adding an availability set: #{e.body}\")\n rescue => ex\n OOLog.fatal(\"Error adding an availability set: #{ex.message}\")\n end\n end\n end", "def resource_group?(name)\n resource_groups.map(&:name).include?(name)\n end", "def fetch_availability\n return unless supports_availability?\n index_availability || availability_service.get_availability(self)\n end", "def resource_group_exists?(group_name, system_config)\n cmdline = Schott::AzureCLI::Commandlines.resource_group_exists?(group_name)\n cmd = run_command(\"#{group_name} exists\", cmdline, system_config)\n return cmd.output.chomp == \"true\"\n end", "def get_avail_set_props\n avail_set_props =\n Azure::ARM::Compute::Models::AvailabilitySetProperties.new\n # At least two domain faults\n avail_set_props.platform_fault_domain_count = 2\n avail_set_props.platform_update_domain_count = 2\n # At this point we do not have virtual machines to include\n avail_set_props.virtual_machines = []\n avail_set_props.statuses = []\n avail_set = Azure::ARM::Compute::Models::AvailabilitySet.new\n avail_set.location = @location\n avail_set.properties = avail_set_props\n return avail_set\n end", "def exists\n Tapjoy::AutoscalingBootstrap::AWS::Autoscaling::Group.describe.nil? ? false : true\n end", "def delete_availability_set(resource_group_name, name)\n @logger.debug(\"delete_availability_set - trying to delete '#{name}' from resource group '#{resource_group_name}'\")\n url = rest_api_url(REST_API_PROVIDER_COMPUTE, REST_API_AVAILABILITY_SETS, resource_group_name: resource_group_name, name: name)\n http_delete(url)\n end", "def has_package_set?(name)\n each_package_set.find { |set| set.name == name }\n end", "def get_availability_set_properties(location, fault_domain_count, update_domain_count, use_managed_disk, tags)\n avail_set = Azure::ARM::Compute::Models::AvailabilitySet.new\n avail_set.location = location\n avail_set.sku = create_availability_set_sku(use_managed_disk)\n avail_set.platform_fault_domain_count = fault_domain_count.nil? ? FAULT_DOMAIN_COUNT : fault_domain_count\n avail_set.platform_update_domain_count = update_domain_count.nil? ? UPDATE_DOMAIN_COUNT : update_domain_count\n avail_set.tags = tags\n avail_set\n end", "def has_package_set?(name)\n !!find_package_set(name)\n end", "def availability\n STATUS_TO_AVAILABILITY[self.status]\n end", "def get_avail_set_properties(location)\n avail_set_props = Azure::ARM::Compute::Models::AvailabilitySetProperties.new\n # At least two domain faults\n avail_set_props.platform_fault_domain_count = 2\n avail_set_props.platform_update_domain_count = 2\n # At this point we do not have virtual machines to include\n avail_set_props.virtual_machines = []\n avail_set_props.statuses = []\n avail_set = Azure::ARM::Compute::Models::AvailabilitySet.new\n avail_set.location = location\n avail_set.properties = avail_set_props\n avail_set\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this method will add the availability set if needed. it first checks to make sure the availability set exists, if not, it will create it.
def add(resource_group, availability_set, location) # check if it exists existance_promise = get(resource_group, availability_set) if !existance_promise.nil? OOLog.info("Availability Set #{existance_promise.name} exists in the #{existance_promise.location} region.") else # need to create the availability set OOLog.info("Creating Availability Set '#{availability_set}' in #{location} region") avail_set = get_avail_set_props(location) begin start_time = Time.now.to_i response = @client.availability_sets.create_or_update(resource_group, availability_set, avail_set).value! response.body end_time = Time.now.to_i duration = end_time - start_time OOLog.info("Availability Set created in #{duration} seconds") rescue MsRestAzure::AzureOperationError => e OOLog.fatal("Error adding an availability set: #{e.body}") rescue => ex OOLog.fatal("Error adding an availability set: #{ex.message}") end end end
[ "def add\n # check if it exists\n as_exist = @compute_client.availability_sets.check_availability_set_exists(@rg_name, @as_name)\n if as_exist\n OOLog.info(\"Availability Set #{@as_name} exists in the #{@location} region.\")\n else\n # need to create the availability set\n OOLog.info(\"Creating Availability Set '#{@as_name}' in #{@location} region\")\n\n begin\n #if we are using the managed disk attached to vm availability set needs to setup use_managed_disk to true\n\n\n @compute_client.availability_sets.create(resource_group: @rg_name, name: @as_name, location: @location, use_managed_disk: true, platform_fault_domain_count: Utils.get_fault_domains(@location\n ), platform_update_domain_count: Utils.get_update_domains)\n rescue MsRestAzure::AzureOperationError => e\n OOLog.fatal(\"Error adding an availability set: #{e.body}\")\n rescue => ex\n OOLog.fatal(\"Error adding an availability set: #{ex.message}\")\n end\n end\n end", "def add\n # check if it exists\n as = get\n if !as.nil?\n OOLog.info(\"Availability Set #{as.name} exists in the #{as.location} region.\")\n else\n # need to create the availability set\n OOLog.info(\"Creating Availability Set\n '#{@as_name}' in #{@location} region\")\n avail_set = get_avail_set_props\n begin\n response =\n @client.availability_sets.create_or_update(@rg_name,\n @as_name,\n avail_set).value!\n return response\n rescue MsRestAzure::AzureOperationError => e\n OOLog.fatal(\"Error adding an availability set: #{e.body}\")\n rescue => ex\n OOLog.fatal(\"Error adding an availability set: #{ex.message}\")\n end\n end\n end", "def create_availability_set\n t = Time.new\n puts \"#{t.hour}:#{t.min}:#{t.sec}\"\n puts \"\"\n puts \"Creating AvailabilitySet for Backend pool of Loadbalancer\"\n puts \"\"\n params = AvailabilitySet.new\n params.platform_update_domain_count = 5\n params.platform_fault_domain_count = 2\n params.managed = true\n params.location = \"CentralIndia\"\n promise = client.availability_sets.create_or_update(\"#{config[:resource_group]}\", \"#{config[:env]}_availability_set\", params)\n puts \"name = #{promise.name}\"\n puts \"id = #{promise.id}\"\n return promise.name\n end", "def create_availability_set(resource_group_name, params)\n url = rest_api_url(REST_API_PROVIDER_COMPUTE, REST_API_AVAILABILITY_SETS, resource_group_name: resource_group_name, name: params[:name])\n availability_set = {\n 'name' => params[:name],\n 'type' => \"#{REST_API_PROVIDER_COMPUTE}/#{REST_API_AVAILABILITY_SETS}\",\n 'location' => params[:location],\n 'tags' => params[:tags],\n 'properties' => {\n 'platformUpdateDomainCount' => params[:platform_update_domain_count],\n 'platformFaultDomainCount' => params[:platform_fault_domain_count]\n }\n }\n\n if params[:managed]\n availability_set['sku'] = {\n 'name' => 'Aligned'\n }\n end\n\n http_put(url, availability_set)\n end", "def get_availability_set(url)\n availability_set = nil\n result = get_resource_by_id(url)\n unless result.nil?\n availability_set = {}\n availability_set[:id] = result['id']\n availability_set[:name] = result['name']\n availability_set[:location] = result['location']\n availability_set[:tags] = result['tags']\n\n availability_set[:managed] = false\n availability_set[:managed] = true if !result['sku'].nil? && (result['sku']['name'] == 'Aligned')\n\n properties = result['properties']\n availability_set[:provisioning_state] = properties['provisioningState']\n availability_set[:platform_update_domain_count] = properties['platformUpdateDomainCount']\n availability_set[:platform_fault_domain_count] = properties['platformFaultDomainCount']\n availability_set[:virtual_machines] = []\n properties['virtualMachines']&.each do |vm|\n availability_set[:virtual_machines].push(id: vm['id'])\n end\n end\n availability_set\n end", "def set_availabilities(availabilities)\n availabilities.each do |availability|\n date = availability['DATE']\n available = availability['MAX_LOS'].to_i > 0 && availability['AVAILABLE_UNITS'].to_i > 0\n entry = find_entry(date)\n\n unless entry\n entry = build_entry(date)\n entries << entry\n end\n\n entry.available = available\n end\n end", "def set_availability\n self.update(availability: self.bus.seats)\n end", "def get_avail_set_props\n avail_set_props =\n Azure::ARM::Compute::Models::AvailabilitySetProperties.new\n # At least two domain faults\n avail_set_props.platform_fault_domain_count = 2\n avail_set_props.platform_update_domain_count = 2\n # At this point we do not have virtual machines to include\n avail_set_props.virtual_machines = []\n avail_set_props.statuses = []\n avail_set = Azure::ARM::Compute::Models::AvailabilitySet.new\n avail_set.location = @location\n avail_set.properties = avail_set_props\n return avail_set\n end", "def get\n begin\n @compute_client.availability_sets.get(@rg_name, @as_name)\n rescue MsRestAzure::AzureOperationError => e\n # if the error is that the availability set doesn't exist,\n # just return a nil\n if e.response.status == 404\n puts 'Availability Set Not Found! Create It!'\n return nil\n end\n OOLog.fatal(\"Error getting availability set: #{e.body}\")\n rescue => ex\n OOLog.fatal(\"Error getting availability set: #{ex.message}\")\n end\n end", "def check_avail_overlap\n avails = current_user.availabilities.where(somewhat: @somewhat)\n\n # checks if start or end time of another availability is on top of the incoming availability\n start_overlap = avails.where(start: @start..@end)\n end_overlap = avails.where(end: @start..@end)\n\n # checks if incoming avail is on within of another avail\n # therefore it would not be needed\n inter_overlap = avails.where('start <= ?', @start).where('availabilities.end >= ?', @end)\n\n if inter_overlap.count > 0\n # if there are similar availabilities that already exist,\n # then there is no need to add another\n\n return\n elsif start_overlap.count > 0 || end_overlap.count > 0\n # any slight overlap from other availabilities go here\n\n # sets avail to be any start_overlap by default, but\n # it will change to end_overlap if start is empty\n avail = start_overlap.first\n avail = end_overlap.first if start_overlap.first.nil?\n\n avail.start = @start if avail.start > @start\n avail.end = @end if avail.end < @end\n avail.save\n else\n # unique availabilities go here (there are no overlaps)\n\n avails.create!(\n start: @start,\n end: @end,\n somewhat: @somewhat,\n )\n end\n end", "def initialize()\r\n\t\t@available_set_list = Hash.new\r\n\tend", "def ensure_rule_set()\n resp = @ses.list_receipt_rule_sets()\n add_new_rule_set = true\n resp.to_h[:rule_sets].each { |rule_set|\n add_new_rule_set = false if (rule_set[:name] =~ /^#{Regexp.escape(@receipt_rule.rule_set_name)}$/)\n }\n @ses.create_receipt_rule_set({rule_set_name: @receipt_rule.rule_set_name}) if add_new_rule_set\n end", "def assign_available_stock\n\n stock_detail, category_occupation = BookingDataSystem::Booking.categories_availability(self.rental_location_code,\n self.date_from,\n self.time_from,\n self.date_to,\n self.time_to,\n nil,\n {\n origin: 'booking',\n id: self.id\n })\n\n #p \"stock_detail: #{stock_detail.inspect}\"\n #p \"category_occupation: #{category_occupation.inspect}\"\n\n transaction do\n booking_lines.each do |booking_line|\n booking_line.booking_line_resources.each do |booking_line_resource|\n if booking_line_resource.booking_item_reference.nil?\n p \"assign_available_stock -- #{booking_line_resource.booking_item_reference} -- available: #{category_occupation[booking_line.item_id][:available_stock].inspect} -- available_assignable: #{category_occupation[booking_line.item_id][:available_assignable_stock].inspect}\"\n if booking_item_reference = category_occupation[booking_line.item_id][:available_assignable_stock].first and !booking_item_reference.nil?\n booking_line_resource.assign_resource(booking_item_reference)\n category_occupation[booking_line.item_id][:available_assignable_stock].delete_at(0)\n end\n end\n end\n end\n\n end\n\n end", "def ensure_data_bag_exists\n data_bag.create(name: DATA_BAG) unless locks\n end", "def recalculate_set_availability\n if ['new','pending','transit','trouble','unavailable'].include? status\n teacher_set.recalculate_availability\n end\n end", "def update_availability\n\t\ttimeslot = self.timeslot\n\t\ttimeslot_multiple_boats(timeslot)\n\tend", "def get_avail_set_properties(location)\n avail_set_props = Azure::ARM::Compute::Models::AvailabilitySetProperties.new\n # At least two domain faults\n avail_set_props.platform_fault_domain_count = 2\n avail_set_props.platform_update_domain_count = 2\n # At this point we do not have virtual machines to include\n avail_set_props.virtual_machines = []\n avail_set_props.statuses = []\n avail_set = Azure::ARM::Compute::Models::AvailabilitySet.new\n avail_set.location = location\n avail_set.properties = avail_set_props\n avail_set\n end", "def get\n begin\n promise = @client.availability_sets.get(@rg_name,@as_name).value!\n return promise\n rescue MsRestAzure::AzureOperationError => e\n # if the error is that the availability set doesn't exist,\n # just return a nil\n if e.response.status == 404\n puts 'Availability Set Not Found! Create It!'\n return nil\n end\n OOLog.fatal(\"Error getting availability set: #{e.body}\")\n rescue => ex\n OOLog.fatal(\"Error getting availability set: #{ex.message}\")\n end\n end", "def recalculate_availability\n copies = self.available_copies\n #Below code need to discuss with Darya.\n #copies -= self.new_or_pending_holds.count\n status = copies > 0 ? 'available' : 'unavailable'\n self.update_attribute :availability, status\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create the properties object for creating availability sets
def get_avail_set_props(location) avail_set_props = Azure::ARM::Compute::Models::AvailabilitySetProperties.new # At least two domain faults avail_set_props.platform_fault_domain_count = 2 avail_set_props.platform_update_domain_count = 2 # At this point we do not have virtual machines to include avail_set_props.virtual_machines = [] avail_set_props.statuses = [] avail_set = Azure::ARM::Compute::Models::AvailabilitySet.new avail_set.location = location avail_set.properties = avail_set_props avail_set end
[ "def get_availability_set_properties(location, fault_domain_count, update_domain_count, use_managed_disk, tags)\n avail_set = Azure::ARM::Compute::Models::AvailabilitySet.new\n avail_set.location = location\n avail_set.sku = create_availability_set_sku(use_managed_disk)\n avail_set.platform_fault_domain_count = fault_domain_count.nil? ? FAULT_DOMAIN_COUNT : fault_domain_count\n avail_set.platform_update_domain_count = update_domain_count.nil? ? UPDATE_DOMAIN_COUNT : update_domain_count\n avail_set.tags = tags\n avail_set\n end", "def get_avail_set_props\n avail_set_props =\n Azure::ARM::Compute::Models::AvailabilitySetProperties.new\n # At least two domain faults\n avail_set_props.platform_fault_domain_count = 2\n avail_set_props.platform_update_domain_count = 2\n # At this point we do not have virtual machines to include\n avail_set_props.virtual_machines = []\n avail_set_props.statuses = []\n avail_set = Azure::ARM::Compute::Models::AvailabilitySet.new\n avail_set.location = @location\n avail_set.properties = avail_set_props\n return avail_set\n end", "def get_avail_set_properties(location)\n avail_set_props = Azure::ARM::Compute::Models::AvailabilitySetProperties.new\n # At least two domain faults\n avail_set_props.platform_fault_domain_count = 2\n avail_set_props.platform_update_domain_count = 2\n # At this point we do not have virtual machines to include\n avail_set_props.virtual_machines = []\n avail_set_props.statuses = []\n avail_set = Azure::ARM::Compute::Models::AvailabilitySet.new\n avail_set.location = location\n avail_set.properties = avail_set_props\n avail_set\n end", "def create_availability_set\n t = Time.new\n puts \"#{t.hour}:#{t.min}:#{t.sec}\"\n puts \"\"\n puts \"Creating AvailabilitySet for Backend pool of Loadbalancer\"\n puts \"\"\n params = AvailabilitySet.new\n params.platform_update_domain_count = 5\n params.platform_fault_domain_count = 2\n params.managed = true\n params.location = \"CentralIndia\"\n promise = client.availability_sets.create_or_update(\"#{config[:resource_group]}\", \"#{config[:env]}_availability_set\", params)\n puts \"name = #{promise.name}\"\n puts \"id = #{promise.id}\"\n return promise.name\n end", "def create_availability_set(resource_group_name, params)\n url = rest_api_url(REST_API_PROVIDER_COMPUTE, REST_API_AVAILABILITY_SETS, resource_group_name: resource_group_name, name: params[:name])\n availability_set = {\n 'name' => params[:name],\n 'type' => \"#{REST_API_PROVIDER_COMPUTE}/#{REST_API_AVAILABILITY_SETS}\",\n 'location' => params[:location],\n 'tags' => params[:tags],\n 'properties' => {\n 'platformUpdateDomainCount' => params[:platform_update_domain_count],\n 'platformFaultDomainCount' => params[:platform_fault_domain_count]\n }\n }\n\n if params[:managed]\n availability_set['sku'] = {\n 'name' => 'Aligned'\n }\n end\n\n http_put(url, availability_set)\n end", "def create\n @property_hash = {\n name: @resource[:name],\n ensure: :present,\n primitive: @resource[:primitive],\n group: @resource[:group],\n clone_max: @resource[:clone_max],\n clone_node_max: @resource[:clone_node_max],\n notify_clones: @resource[:notify_clones],\n globally_unique: @resource[:globally_unique],\n ordered: @resource[:ordered],\n interleave: @resource[:interleave]\n }\n end", "def get_availability_set(url)\n availability_set = nil\n result = get_resource_by_id(url)\n unless result.nil?\n availability_set = {}\n availability_set[:id] = result['id']\n availability_set[:name] = result['name']\n availability_set[:location] = result['location']\n availability_set[:tags] = result['tags']\n\n availability_set[:managed] = false\n availability_set[:managed] = true if !result['sku'].nil? && (result['sku']['name'] == 'Aligned')\n\n properties = result['properties']\n availability_set[:provisioning_state] = properties['provisioningState']\n availability_set[:platform_update_domain_count] = properties['platformUpdateDomainCount']\n availability_set[:platform_fault_domain_count] = properties['platformFaultDomainCount']\n availability_set[:virtual_machines] = []\n properties['virtualMachines']&.each do |vm|\n availability_set[:virtual_machines].push(id: vm['id'])\n end\n end\n availability_set\n end", "def build_properties\n properties.each do |key,val|\n prop = listing_properties.find_or_initialize_by(key:key)\n prop.value = val\n\n end\n end", "def create\n @property_hash = {\n :name => @resource[:name],\n :ensure => :present,\n :first => @resource[:first],\n :second => @resource[:second],\n :score => @resource[:score],\n :symmetrical => @resource[:symmetrical],\n :cib => @resource[:cib],\n :new => true,\n }\n end", "def create\n @property_hash = {\n name: @resource[:name],\n ensure: :present,\n primitive: @resource[:primitive],\n clone_max: @resource[:clone_max],\n clone_node_max: @resource[:clone_node_max],\n notify_clones: @resource[:notify_clones],\n globally_unique: @resource[:globally_unique],\n ordered: @resource[:ordered],\n interleave: @resource[:interleave],\n cib: @resource[:cib],\n existing_resource: :false\n }\n end", "def create\n @property_hash = {\n name: @resource[:name],\n ensure: :present,\n first: @resource[:first],\n second: @resource[:second],\n kind: @resource[:kind],\n symmetrical: @resource[:symmetrical],\n new: true\n }\n end", "def create\n @property_hash = {\n name: @resource[:name],\n ensure: :present,\n primitive_class: @resource[:primitive_class],\n provided_by: @resource[:provided_by],\n primitive_type: @resource[:primitive_type],\n promotable: @resource[:promotable],\n existing_resource: :false\n }\n @property_hash[:parameters] = @resource[:parameters] unless @resource[:parameters].nil?\n @property_hash[:operations] = @resource[:operations] unless @resource[:operations].nil?\n @property_hash[:utilization] = @resource[:utilization] unless @resource[:utilization].nil?\n @property_hash[:metadata] = @resource[:metadata] unless @resource[:metadata].nil?\n @property_hash[:ms_metadata] = @resource[:ms_metadata] unless @resource[:ms_metadata].nil?\n @property_hash[:existing_metadata] = {}\n end", "def wb_create_properties(props)\n properties = Hash.new\n\n props.each do |prop|\n handle = prop[0]\n type = prop[1]\n data = '{\"labels\":{\"en\":{\"language\":\"en\",\"value\":\"' + generate_random_string(8) +\n '\"}},\"descriptions\":{\"en\":{\"language\":\"en\",\"value\":\"' + generate_random_string(20) +\n '\"}},\"datatype\":\"' + type + '\"}'\n property = wb_create_entity(data, \"property\")\n properties[handle] = property\n end\n\n properties\n end", "def create\n @property_hash = {\n name: @resource[:name],\n ensure: :present,\n primitive_class: @resource[:primitive_class],\n provided_by: @resource[:provided_by],\n primitive_type: @resource[:primitive_type],\n existing_resource: :false\n }\n @property_hash[:parameters] = @resource[:parameters] unless @resource[:parameters].nil?\n @property_hash[:operations] = @resource[:operations] unless @resource[:operations].nil?\n @property_hash[:utilization] = @resource[:utilization] unless @resource[:utilization].nil?\n @property_hash[:metadata] = @resource[:metadata] unless @resource[:metadata].nil?\n @property_hash[:existing_metadata] = {}\n end", "def build_property\n property = Entities::Property.new(\n id: property_hash.get(\"ID\"),\n title: property_hash.get(\"Name\"),\n lat: property_hash.get(\"Coordinates.Latitude\").to_f,\n lng: property_hash.get(\"Coordinates.Longitude\").to_f,\n address: property_hash.get(\"Street\"),\n postal_code: property_hash.get(\"ZipCode\").to_s.strip,\n max_guests: property_hash.get(\"CanSleepMax\").to_i,\n bedroom_type_id: property_hash.get(\"PropertyTypeID\"),\n property_type_id: property_hash.get(\"ObjectTypeID\"),\n active: property_hash.get(\"IsActive\"),\n archived: property_hash.get(\"IsArchived\"),\n surface: property_hash.get(\"Space\").to_i,\n owner_id: property_hash.get(\"OwnerID\"),\n security_deposit_amount: property_hash.get(\"SecurityDeposit\").to_f,\n security_deposit_type: security_deposit_type,\n check_in_time: check_in_time,\n check_out_time: check_out_time,\n check_in_instructions: check_in_instructions,\n floor: floor,\n description: en_description(property_hash),\n images: build_images,\n amenities: build_amenities,\n number_of_bathrooms: number_of_bathrooms,\n number_of_single_beds: beds_count(SINGLE_BED_CODES),\n number_of_double_beds: beds_count(DOUBLE_BED_CODES),\n number_of_sofa_beds: beds_count(SOFA_BED_CODES),\n late_arrival_fees: late_arrival_fees,\n early_departure_fees: early_departure_fees,\n )\n\n property\n end", "def initialize()\r\n\t\t@available_set_list = Hash.new\r\n\tend", "def add\n # check if it exists\n as_exist = @compute_client.availability_sets.check_availability_set_exists(@rg_name, @as_name)\n if as_exist\n OOLog.info(\"Availability Set #{@as_name} exists in the #{@location} region.\")\n else\n # need to create the availability set\n OOLog.info(\"Creating Availability Set '#{@as_name}' in #{@location} region\")\n\n begin\n #if we are using the managed disk attached to vm availability set needs to setup use_managed_disk to true\n\n\n @compute_client.availability_sets.create(resource_group: @rg_name, name: @as_name, location: @location, use_managed_disk: true, platform_fault_domain_count: Utils.get_fault_domains(@location\n ), platform_update_domain_count: Utils.get_update_domains)\n rescue MsRestAzure::AzureOperationError => e\n OOLog.fatal(\"Error adding an availability set: #{e.body}\")\n rescue => ex\n OOLog.fatal(\"Error adding an availability set: #{ex.message}\")\n end\n end\n end", "def get_available_properties(check_in, check_out, properties)\n result_properties = []\n property_available = false\n properties.each do |property|\n if !@cal_hash[property[0]].nil?\n property_cals = @cal_hash[property[0]]\n property_cals.each do |cal|\n date = Date.parse(cal[1])\n property_available = !(( date >= check_in && date < check_out ) && cal[2].to_i == 0) \n break unless property_available \n end\n else\n property_available = true\n end\n\n result_properties << property if property_available\n end\n puts \"found #{result_properties.size} properties available for the dates\"\n result_properties\n end", "def add\n # check if it exists\n as = get\n if !as.nil?\n OOLog.info(\"Availability Set #{as.name} exists in the #{as.location} region.\")\n else\n # need to create the availability set\n OOLog.info(\"Creating Availability Set\n '#{@as_name}' in #{@location} region\")\n avail_set = get_avail_set_props\n begin\n response =\n @client.availability_sets.create_or_update(@rg_name,\n @as_name,\n avail_set).value!\n return response\n rescue MsRestAzure::AzureOperationError => e\n OOLog.fatal(\"Error adding an availability set: #{e.body}\")\n rescue => ex\n OOLog.fatal(\"Error adding an availability set: #{ex.message}\")\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Marks the current model as a canhaz subject for authorizations
def acts_as_canhaz_object include Canhaz::Mongoid::ObjectExtensions class_eval do has_many :permissions_subjects, :class_name => 'Canhaz::Mongoid::Permission', :inverse_of => 'cobject' end end
[ "def acts_as_canhaz_subject\n include CanHaz::ModelExtensions::Subject\n extend CanHaz::ModelExtensions::Subject::ClassMethods\n before_destroy :can_do_nothing # Removes permission before deleting the subject\n end", "def acts_as_authorization_subject?\n acts_as_authorization_model? :subject\n end", "def author\n self.role = :author\n save\n end", "def type_authorization!()\n @type = TAC_PLUS_AUTHOR\n end", "def edit\n authorize! :update, @subject\n end", "def authorize_set!\n @_user_authorized = true\n @_current_token = request_token\n @_current_user = request_user\n end", "def author\n if @subject.user_id > 0\n unless (current_user.sk == @subject.user || (current_user.sk.admin && !@subject.user.admin) || current_user.sk.root)\n render 'errors/access_refused' and return\n end\n else # Message automatique\n unless current_user.sk.root\n render 'errors/access_refused' and return\n end\n end\n end", "def set_authorization\n @user ||= current_user\n authorize @user\n end", "def set_acl_statement\n super\n end", "def set_author_on_subject(author, subject)\n if content = subject.contents.first\n content.update_attributes(\n authorable_id: author.id,\n authorable_type: author.class.name\n )\n end\n end", "def authorize_author\n redirect_to '/login' unless self.user_access > 1 || current_user.access == 3\n end", "def acts_as_authorization_role_subject?\n acts_as_authorization_model? :role_subject\n end", "def course_batch\n authorize! :read, GeneralSetting\n end", "def authorize\n @analytics.authorization = GaAuthorizer.token\n end", "def set_author\n author_reference.reference = \"Patient/#{user.icn}\"\n end", "def elective_subject\n @elective_group = ElectiveGroup.shod(params[:id])\n @elective_subjects ||= @elective_group.subjects\n authorize! :read, @elective_group\n end", "def authorize!(action, subject = nil)\n\n\n\n unless authorized? action, subject\n\n\n\n raise ActiveAdmin::AccessDenied.new(current_active_admin_user,\n\n\n\n action,\n\n\n\n subject)\n\n\n\n end\n\n\n\n end", "def set_subject(subject)\n @subject = subject\n self\n end", "def acts_as_authorization_permission_subject?\n acts_as_authorization_model? :permission_subject\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /ingresos GET /ingresos.xml
def index @ingresos = Ingreso.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @ingresos } end end
[ "def show\n @ingreso = Ingreso.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @ingreso }\n end\n end", "def index\n @pings = Ping.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @pings }\n end\n end", "def index\n @ingresos = Ingreso.all\n end", "def index\n @generaciones = Generacion.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @generaciones }\n end\n end", "def index\n @artigos = Artigo.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @artigos }\n end\n end", "def index\n @requests = Request.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @requests }\n end\n end", "def index\n @waxings = Waxing.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @waxings }\n end\n end", "def show\n @gigaso = Gigaso.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @gigaso }\n end\n end", "def timeline\n @bookings = Booking.find_waiting_pickup\n respond_to do |format|\n format.xml\n end\n end", "def show\n @inning = Inning.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @inning }\n end\n end", "def index\n @callings = Calling.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @callings }\n end\n end", "def index\n @retencionganancias = Retencionganancia.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @retencionganancias }\n end\n end", "def xml(options = {})\n host = Picasa.host\n path = Picasa.path(options)\n url = URI(\"#{host}#{path}\")\n\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n\n req = add_auth_headers(Net::HTTP::Get.new url.path)\n\n response = http.request(req)\n if response.code =~ /20[01]/\n response.body\n end\n end", "def show\n @glosentry = Glosentry.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @glosentry }\n end\n end", "def show\n @owning = Owning.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @owning }\n end\n end", "def show\n @soon = Soon.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @soon }\n end\n end", "def index\n retrieve_vtodos\n\n respond_to do |format|\n format.html # index.html.erb\n format.rdf { render :xml => ICAL::Vtodo.to_xml }\n end\n end", "def index\n @oils = Oil.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @oils }\n end\n end", "def index\n @gigs = Gig.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @gigs }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /ingresos/1 GET /ingresos/1.xml
def show @ingreso = Ingreso.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @ingreso } end end
[ "def index\n @ingresos = Ingreso.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @ingresos }\n end\n end", "def xml(id)\n http.get(\"/nfse/#{id}/xml\") do |response|\n response.headers.fetch(\"Location\") { \"\" }\n end\n end", "def show\n @soon = Soon.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @soon }\n end\n end", "def show\n @nossos_servico = NossosServico.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @nossos_servico }\n end\n end", "def show\n\n @puntuacione = Puntuacione.find(params[:id])\n respond_to do |format| \n format.xml { render xml: @puntuacione }\n end\n end", "def show\n @gigaso = Gigaso.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @gigaso }\n end\n end", "def index\n @generaciones = Generacion.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @generaciones }\n end\n end", "def show\n @glosentry = Glosentry.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @glosentry }\n end\n end", "def show\n @tipo_gasto = TipoGasto.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tipo_gasto }\n end\n end", "def show\n @inning = Inning.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @inning }\n end\n end", "def show\n @gallion = Gallion.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @gallion }\n end\n end", "def show\n @ingredient = Ingredient.find(params[:id])\n\n respond_to do |format|\n format.xml { render :xml => @ingredient }\n end\n end", "def show\n @etiquetaing = Etiquetaing.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @etiquetaing }\n end\n end", "def index\n retrieve_vtodos\n\n respond_to do |format|\n format.html # index.html.erb\n format.rdf { render :xml => ICAL::Vtodo.to_xml }\n end\n end", "def index\n @pings = Ping.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @pings }\n end\n end", "def show\n @gloscon = Gloscon.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @gloscon }\n end\n end", "def xml_for(action) rio(url_for(action)).read end", "def show\n @topogra = Topogra.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @topogra }\n end\n end", "def xml(options = {})\n host = Picasa.host\n path = Picasa.path(options)\n url = URI(\"#{host}#{path}\")\n\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n\n req = add_auth_headers(Net::HTTP::Get.new url.path)\n\n response = http.request(req)\n if response.code =~ /20[01]/\n response.body\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /ingresos/new GET /ingresos/new.xml
def new @ingreso = Ingreso.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @ingreso } end end
[ "def new\n @soon = Soon.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @soon }\n end\n end", "def new\n @newstuff = Newstuff.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @newstuff }\n end\n end", "def new\n @processing_node = ProcessingNode.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @processing_node }\n end\n end", "def new\n @generacion = Generacion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @generacion }\n end\n end", "def new\n @owning = Owning.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @owning }\n end\n end", "def new\n @genero = Genero.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @genero }\n end\n end", "def new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @coating }\n end\n end", "def new\n @nossos_servico = NossosServico.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @nossos_servico }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @instituto }\n end\n end", "def new\n @glosentry = Glosentry.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @glosentry }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => new_vurl }\n end\n end", "def new\n @printing = Printing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @printing }\n end\n end", "def new\n @topping = Topping.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @topping }\n end\n end", "def new\n @listing = Listing.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @listing }\n end\n end", "def new\n @gigaso = Gigaso.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @gigaso }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @ontology }\n end\n end", "def new\n @request_sending = RequestSending.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @request_sending }\n end\n end", "def new\n @spiga = Spiga.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @spiga }\n end\n end", "def new\n @tipo_gasto = TipoGasto.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tipo_gasto }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /ingresos POST /ingresos.xml
def create @ingreso = Ingreso.new(params[:ingreso]) respond_to do |format| if @ingreso.save format.html { redirect_to(@ingreso, :notice => 'Ingreso was successfully created.') } format.xml { render :xml => @ingreso, :status => :created, :location => @ingreso } else format.html { render :action => "new" } format.xml { render :xml => @ingreso.errors, :status => :unprocessable_entity } end end end
[ "def do_POST(request, response)\n content_type, params = parse_content_type(request)\n\n # In SOAP 1.1, the action is sent in the SOAPAction header. In\n # SOAP 1.2, it's sent as a parameter to the Content-Type header.\n # Savon sends SOAPAction (even though it's SOAP 1.2), so we need to\n # accept it. That's okay, because it appears Epic InterConnect\n # (WCF) also will accept the SOAP 1.1 method.\n namespaced_action_name = request['SOAPAction'] || params['action']\n action_name = namespaced_action_name.gsub('\"', '').split(':')[-1]\n\n action = @actions[action_name]\n\n if not action then\n # Unknown action; send back a 400\n response.status = 400\n\n else\n body = Nokogiri::XML(request.body)\n @received << body if @keep_received\n\n xml, status = action.call(body, response)\n\n response.status = status\n response['Content-Type'] = 'text/xml'\n response.body = xml\n end\n end", "def send_request( xml )\n write( xml )\n read\n end", "def post_expense_xml(xml)\n #request header bekommt Content-type = xml\n header \"Content-Type\", \"text/xml\" \n #expense daten werden alsl xml per Post request an den Server gesendet\n post '/expenses', xml\n #es wird erwartet das dies erfolgreich war\n expect(last_response.status).to eq(200)\n\n parsed = Ox.load(last_response.body, mode: :hash)\n expect(parsed).to include('expense_id' => a_kind_of(Integer))\n #adds an id key to the expense hash, containing the id from the database, after an expense is succesfully stored\n expense.merge('id' => parsed['expense_id'])\nend", "def post\n resource.post(request, response)\n end", "def POST; end", "def post(resource, params)\n case resource\n when \"pedidos\", \"place_order\", \"new_order\" then url = \"/pedidos\"\n when \"envios\", \"shipping\" then url = \"/envios\"\n else url = \"/#{resource}\"\n end\n\n post_request(url, params)\n end", "def post_config(url_prefix, xml)\n post_data(url_prefix, xml, 'application/xml;charset=UTF-8')\n end", "def post_save xml, options={:mapping=>:_default}\n # using REXML's element namespace method doesn't seem to set the namespace correctly...?\n xml.root.add_attributes(\"xmlns\"=>\"http://schema.intuit.com/platform/fdatafeed/institutionlogin/v1\")\n xml.root.add_namespace \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\"\n xml.root.add_namespace \"xsd\", \"http://www.w3.org/2001/XMLSchema\"\n # for challengeResponses/response\n xml.each_element(\"//response\") do |x|\n x.add_namespace \"v11\", \"http://schema.intuit.com/platform/fdatafeed/challenge/v1\"\n x.name = \"v11:response\"\n end\n # for challengeResponses root\n xml.each_element(\"//challengeResponses\") do |x|\n x.add_namespace \"v1\", \"http://schema.intuit.com/platform/fdatafeed/institutionlogin/v1\"\n x.name = \"challengeResponses\"\n end\n end", "def post_save xml, options={:mapping=>:_default}\n # using REXML's element namespace method doesn't seem to set the namespace correctly...?\n xml.root.add_attributes(\"xmlns\"=>\"http://schema.intuit.com/platform/fdatafeed/institutionlogin/v1\")\n xml.root.add_namespace \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\"\n xml.root.add_namespace \"xsd\", \"http://www.w3.org/2001/XMLSchema\"\n # for challengeResponses/response\n xml.each_element(\"//response\") do |x| \n x.add_namespace \"v11\", \"http://schema.intuit.com/platform/fdatafeed/challenge/v1\"\n x.name = \"v11:response\"\n end\n # for challengeResponses root\n xml.each_element(\"//challengeResponses\") do |x| \n x.add_namespace \"v1\", \"http://schema.intuit.com/platform/fdatafeed/institutionlogin/v1\"\n x.name = \"challengeResponses\"\n end\n end", "def test_should_create_status_post_via_API_XML\r\n get \"/logout\"\r\n post \"/status_posts.xml\", :api_key=>'testapikey',\r\n :status_post => {:body => 'API Status Post 1' }\r\n assert_response :created\r\n end", "def post_spoonacular\n # %encode ingredients to url\n encoded_ingr = URI.escape(@translated_recipe[:ingredients_list])\n # post call block :\n url = URI(\"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/parseIngredients?includeNutrition=true\")\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Post.new(url)\n request[\"content-type\"] = \"application/x-www-form-urlencoded\"\n request[\"x-rapidapi-key\"] = ENV[\"X_RAPIDAPI_KEY\"]\n request[\"x-rapidapi-host\"] = \"spoonacular-recipe-food-nutrition-v1.p.rapidapi.com\"\n # body of the call with ingredients and servings\n request.body = \"ingredientList=#{encoded_ingr}&#{@recipe_hash[:servings]}\"\n # response\n response = http.request(request)\n end", "def create\n @etiquetaing = Etiquetaing.new(params[:etiquetaing])\n\n respond_to do |format|\n if @etiquetaing.save\n flash[:notice] = 'Etiquetaing was successfully created.'\n format.html { redirect_to(@etiquetaing) }\n format.xml { render :xml => @etiquetaing, :status => :created, :location => @etiquetaing }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @etiquetaing.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @ingreso = Ingreso.new(ingreso_params)\n\n respond_to do |format|\n if @ingreso.save\n format.html { redirect_to @ingreso, notice: 'Ingreso was successfully created.' }\n format.json { render :show, status: :created, location: @ingreso }\n else\n format.html { render :new }\n format.json { render json: @ingreso.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_xmlrpc\n xml = request.body.read\n \n if(xml.empty?)\n error = 400\n return\n end\n \n # Parse xml\n method, arguments = XMLRPC::Marshal.load_call(xml)\n arg = arguments[0]\n response = create_report(arg)\n \n redirect_to retrieve_response_url(iform_xml_feed, :format => 'xml') \n end", "def create\n doc = Nokogiri::XML(request.body.read)\n cvNode = doc.xpath('elwak/checklisten_vorlage')\n cv = ChecklistenVorlage.new({\n objekt_id: cvNode.xpath('objekt_id').text.to_s, \n bezeichner: cvNode.xpath('bezeichner').text.to_s, \n version: cvNode.xpath('version').text.to_s.to_i, \n inaktiv: cvNode.xpath('inaktiv').text.to_s.to_bool \n })\n cv.save\n\n cvNode.xpath('checklisten_eintrags/checklisten_eintrag').each do |ceNode|\n ce = ChecklistenEintrag.new({\n checklisten_vorlage_id: cv.id,\n bezeichner: ceNode.xpath('bezeichner').text.to_s,\n was: ceNode.xpath('was').text.to_s,\n wann: ceNode.xpath('wann').text.to_s,\n typ: ceNode.xpath('typ').text.to_s.to_i,\n position: ceNode.xpath('position').text.to_s.to_i\n })\n ce.save\n end\n\n respond_to do |format|\n format.xml {render :xml => '<?xml version=\"1.0\" encoding=\"UTF-8\"?><success />'}\n end\n end", "def post *args\n make_request :post, *args\n end", "def do_submission(path, xml = nil)\n if xml.nil?\n form = create(:form, question_types: %w(integer integer))\n form.publish!\n xml = build_odk_submission(form)\n end\n\n # write xml to file\n require 'fileutils'\n FileUtils.mkpath('test/fixtures')\n fixture_file = Rails.root.join('test/fixtures/', ODK_XML_FILE)\n File.open(fixture_file.to_s, 'w') { |f| f.write(xml) }\n\n # Upload and do request.\n uploaded = fixture_file_upload(fixture_file, 'text/xml')\n post(path, {:xml_submission_file => uploaded, :format => 'xml'}, 'HTTP_AUTHORIZATION' => encode_credentials(@user.login, 'password'))\n assigns(:response)\n end", "def post(data, tags_in = {}) ; post_to nil, data, tags_in end", "def to_xml\n set_common_nodes\n set_nodes_contents\n process_signature\n @application_request.to_xml\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /ingresos/1 DELETE /ingresos/1.xml
def destroy @ingreso = Ingreso.find(params[:id]) @ingreso.destroy respond_to do |format| format.html { redirect_to(ingresos_url) } format.xml { head :ok } end end
[ "def del\n @status1 = Status1.find(params[:id])\n @status1.destroy\n\n respond_to do |format|\n format.html { redirect_to(status1s_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @scrap_xml = ScrapXml.find(params[:id])\n @scrap_xml.destroy\n\n respond_to do |format|\n format.html { redirect_to(scrap_xmls_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @tipo_gasto = TipoGasto.find(params[:id])\n @tipo_gasto.destroy\n\n respond_to do |format|\n format.html { redirect_to(tipo_gastos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @gigaso = Gigaso.find(params[:id])\n @gigaso.destroy\n\n respond_to do |format|\n format.html { redirect_to(gigasos_url) }\n format.xml { head :ok }\n end\n end", "def del\n @office1 = Office1.find(params[:id])\n @office1.destroy\n\n respond_to do |format|\n format.html { redirect_to(office1s_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @gestion = Gestion.find(params[:id])\n @gestion.destroy\n\n respond_to do |format|\n format.html { redirect_to(gestiones_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @ingredience = Ingredience.find(params[:id])\n @ingredience.destroy\n\n respond_to do |format|\n format.html { redirect_to(ingrediences_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @transaction_xml = Transaction::Xml.find(params[:id])\n @transaction_xml.destroy\n\n respond_to do |format|\n format.html { redirect_to(transaction_xmls_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @ngo = Ngo.find(params[:id])\n @ngo.destroy\n\n respond_to do |format|\n format.html { redirect_to(ngos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @estagiario = Estagiario.find(params[:id])\n @estagiario.destroy\n\n respond_to do |format|\n format.html { redirect_to(estagiarios_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @documento = @externo.documentos.find(params[:id])\n @documento.destroy\n\n respond_to do |format|\n format.html { redirect_to(documentos_url(@externo)) }\n format.xml { head :ok }\n end\n end", "def destroy\n @relatestagiario = Relatestagiario.find(params[:id])\n @relatestagiario.destroy\n\n respond_to do |format|\n format.html { redirect_to(relatestagiarios_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @config_xml = ConfigXml.find(params[:id])\n @config_xml.destroy\n\n respond_to do |format|\n format.html { redirect_to(config_xmls_url) }\n format.xml { head :ok }\n end\n rescue ActiveRecord::RecordNotFound => e\n prevent_access(e)\n end", "def destroy\n @segmento = Segmento.find(params[:id])\n @segmento.destroy\n\n respond_to do |format|\n format.html { redirect_to(segmentos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n \n # need to delete on current user for security\n current_user.readings.delete_all(:listing_id=>params[:listing_id])\n \n respond_to do |format|\n format.xml { head :ok }\n end\n end", "def destroy\n @estatu = Estatu.find(params[:id])\n @estatu.destroy\n\n respond_to do |format|\n format.html { redirect_to(estatus_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @obrasproyecto = Obrasproyecto.find(params[:id])\n @obrasproyecto.destroy\n\n respond_to do |format|\n format.html { redirect_to(obrasproyectos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @invoice_operation = InvoiceOperation.find(params[:id])\n @invoice_operation.destroy\n\n respond_to do |format|\n format.html { redirect_to(invoice_operations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @nagios_service_escalation = NagiosServiceEscalation.find(params[:id])\n @nagios_service_escalation.destroy\n\n respond_to do |format|\n format.html { redirect_to(nagios_service_escalations_url) }\n format.xml { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RESTful DELETE of the node resource
def destroy n = Node.find_key(params[:id] || params[:name]) render api_delete Node end
[ "def destroy\n @node = Node.find(params[:id])\n @node.destroy\n\n respond_to do |format|\n format.html { redirect_to \"/\" }\n format.json { head :ok }\n end\n end", "def destroy\n @node = Node.find(params[:id])\n @node.destroy\n\n respond_to do |format|\n format.html { redirect_to nodes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @node = Node.find(params[:id])\n @node.destroy\n\n respond_to do |format|\n format.html { redirect_to(nodes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @node = Node.find(params[:id])\n @node.destroy\n\n respond_to do |format|\n format.html { redirect_to nodes_url }\n format.json { head :ok }\n end\n end", "def destroy\n @node = Node.find(params[:id])\n @node.destroy\n\n respond_to do |format|\n format.html { redirect_to nodes_path }\n format.json { head :ok }\n end\n end", "def delete\n @client.delete_node(@node)\n end", "def delete node\n end", "def delete endpoint\n do_request :delete, endpoint\n end", "def delete\n request_method('DELETE')\n end", "def ajax_delete_node\n\n # Get the Node from the DB\n node = Node.find(params[:node_id])\n\n # If node exits, then remove the node\n if !node.nil?\n node.destroy\n end\n\n end", "def destroy\n @retain_node = RetainNode.find(params[:id])\n @retain_node.destroy\n\n respond_to do |format|\n format.html { redirect_to(retain_nodes_url) }\n format.xml { head :ok }\n format.json { head :ok }\n end\n end", "def destroy\n @gnode = Gnode.find(params[:id])\n @gnode.destroy\n\n respond_to do |format|\n format.html { redirect_to gnodes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @info_node = InfoNode.find(params[:id])\n @info_node.destroy\n\n respond_to do |format|\n format.html { redirect_to info_nodes_url }\n format.json { head :no_content }\n end\n end", "def delete(node_id)\n Httpu.delete(\"#{$root_url}/db/data/node/#{node_id}\")\n end", "def destroy\n @node_incident = NodeIncident.find(params[:id])\n @node_incident.destroy\n\n respond_to do |format|\n format.html { redirect_to node_incidents_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @node_registration = NodeRegistration.find(params[:id])\n @node_registration.destroy\n\n respond_to do |format|\n format.html { redirect_to(node_registrations_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @node_link = NodeLink.find(params[:id])\n @node_link.destroy\n\n respond_to do |format|\n format.html { redirect_to node_links_url }\n format.json { head :ok }\n end\n end", "def destroy\n @server_node = ServerNode.find(params[:id])\n @server_node.destroy\n\n respond_to do |format|\n format.html { redirect_to server_nodes_url }\n format.json { head :no_content }\n end\n end", "def delete_node(node_id)\n @options = {:path => '/nodes/#{node_id}',\n :body => Megam::JSONCompat.to_json({\"node_id\" => \"#{node_id}\"})}.merge(@options)\n\n request(\n :expects => 200,\n :method => :delete,\n #:path => @options[:path],\n :body => @options[:body]\n )\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formula for side (2 cos[((n2) pi)/ (2 n)]
def side_length top = (@num_sides - 2) * Math::PI angle = top / (2 * @num_sides) @side_length = 2 * Math.cos(angle) end
[ "def calculate_two_sides\n calculate_last_angle\n v, r = first(sides.known)\n\n each sides.unknown(r) do |v2|\n side[v2] = sin(angle(v2)) * side(v) / sin(angle(v))\n equation('$2=\\frac{\\sin(@2) * $1}{\\sin(@1)}', v, v2)\n end\n end", "def side_from_sas(side1, angle, side2)\n Math.sqrt(\n (\n side1**2 + side2**2\n ) - (\n 2 * side1 * side2 * Math.cos(\n (angle * (Math::PI / 180))\n )\n )\n )\n end", "def calculate_side_and_angle\n calculate_two_sides\n end", "def cos\n math :cos\n end", "def cos\n math :cos\n end", "def trapezoid(t1, t2, n, &f)\n d=(t2-t1) / n.to_f\n (d/2.0)*(f[t1]+\n 2*(1..(n-1)).inject(0){|ac,i| \n ac+f[t1+d*i]\n }+f[t2])\n end", "def pentagonal(n)\n n*(3*n-1)/2\n end", "def calculate_two_angles\n v, r = first(angles.known)\n \n unless side(v)\n side[v] = sqrt sq(sides(r)).inject(&:+) -\n 2 * sides(r).inject(&:*) * cos(angle(v))\n equation('$1=\\sqrt{$2^2+$3^2-2 * $2 * $3 * \\cos(@1)}', v, *r)\n calculate_three_angles\n return\n end\n \n v2, r2 = first sides.known(r)\n angle[v2] = asin sin(angle(v)) * side(v2) / side(v)\n equation('@2=\\arcsin\\left(\\frac{\\sin(@1) * $2}{$1}\\right)', v, v2)\n \n if ambiguous_case?(v, v2)\n @alt = CosSinCalc::Triangle.new(sides, angles, self)\n @alt.angle[v2] = PI - angle(v2)\n @alt.equation('@2=@pi-\\arcsin\\left(\\frac{\\sin(@1) * $2}{$1}\\right)', v, v2)\n @alt.calculate_side_and_angle\n end\n \n calculate_two_sides\n end", "def calculate_angle_by_sides(v, r)\n acos (sq(sides(r)).inject(&:+) - sq(side(v))) / (2 * sides(r).inject(&:*))\n end", "def circumference\n require_calculation\n sides(VARIABLES).inject(&:+)\n end", "def circle_side_edge(radius, side_number)\n angle = (DEGREES_PER_STEP * side_number).gosu_to_radians\n CP::Vec2.new(radius, 0).rotate(CP::Vec2.for_angle(angle))\n end", "def volume_of_cube(side)\n return ( side ** 3 )\nend", "def cos\n apply_lambda_flat(->(x){Math.cos(x)})\n end", "def my_pi(n)\n\treturn Math::PI.round(n)\nend", "def rad\r\n return 1 if self == 1\r\n return self.prime_division.map{|x,y| x}.reduce(:*)\r\n end", "def c_radius\r\n s_radius*Math.sin(phi)\r\n end", "def circle_of_numbers(n, fst)\n half = n/2 \n if fst < half\n return fst + n/2\n else \n return fst - n/2\n end\nend", "def phi_norm(n)\n primes = n.prime_division.map(&:first)\n primes.map { |p| 1.0 - 1.0 / p }.inject(:*)\nend", "def theta(n,teeth)\n n.to_f/teeth * (2*Math::PI)\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Agent filters are always present no matter what, so we cant raise an error if the capabilities suggest the discovery method cant do agents we just have to rely on the discovery plugin to not do stupid things in the presense of a agent filter
def check_capabilities(filter) capabilities = ddl.discovery_interface[:capabilities] unless capabilities.include?(:classes) raise "Cannot use class filters while using the '%s' discovery method" % discovery_method unless filter["cf_class"].empty? end unless capabilities.include?(:facts) raise "Cannot use fact filters while using the '%s' discovery method" % discovery_method unless filter["fact"].empty? end unless capabilities.include?(:identity) raise "Cannot use identity filters while using the '%s' discovery method" % discovery_method unless filter["identity"].empty? end unless capabilities.include?(:compound) raise "Cannot use compound filters while using the '%s' discovery method" % discovery_method unless filter["compound"].empty? end end
[ "def set_filter(agent, filters, vars)\n agent.reset\n if filters[:discovery]\n agent.discover({:nodes => filters[:discovery]})\n else\n ['identity', 'fact', 'class', 'compound'].each do |kind|\n next unless filters[kind]\n add_filter = agent.method(\"#{kind}_filter\".to_sym)\n if filters[kind].is_a?(String)\n add_filter.call(interpolate(filters[kind], vars))\n else\n filters[kind].each do |filter|\n add_filter.call(interpolate(filter, vars))\n end\n end\n end\n end\n agent\nend", "def agents filters = {}\n # Log command run by the client\n if filters[:command]\n @logger.info filters[:command]\n filters.delete :command\n end\n\n filters = {:set => :all} if (filters.empty? or filters.nil?)\n\n filter = Galaxy::Filter.new filters\n @logger.debug \"Filtering agents by #{filter}\"\n\n @mutex.synchronize do\n @db.values.select(& filter)\n end\n end", "def agent_filter(agent)\n @filter[\"agent\"] = @filter[\"agent\"] | [agent]\n @filter[\"agent\"].compact!\n reset\n end", "def agent_eligible?(agents)\n agent = agents.find { |a|\n a['role'] == \"source\" and a['_resolved']['display_name']['software_name'] == \"Islandora\"\n }\n debug \"Islandora agent eligible: #{agent}\" if agent\n agent\n end", "def identity_filter_discovery_optimization\n if !options[:filter][\"identity\"].empty? && @discovery_method == \"mc\"\n regex_filters = options[:filter][\"identity\"].select {|i| i.match(\"^\\/\")}.size\n\n if regex_filters == 0\n @discovered_agents = options[:filter][\"identity\"].clone\n @force_direct_request = true if Config.instance.direct_addressing\n end\n end\n end", "def run_discovery\n discovered = {}\n\n ::Instana.logger.debug \"#{__method__}: Running agent discovery...\"\n\n # Try default location or manually configured (if so)\n uri = URI.parse(\"http://#{::Instana.config[:agent_host]}:#{::Instana.config[:agent_port]}/\")\n req = Net::HTTP::Get.new(uri)\n\n ::Instana.logger.debug \"#{__method__}: Trying #{::Instana.config[:agent_host]}:#{::Instana.config[:agent_port]}\"\n\n response = make_host_agent_request(req)\n\n if response && (response.code.to_i == 200)\n discovered[:agent_host] = ::Instana.config[:agent_host]\n discovered[:agent_port] = ::Instana.config[:agent_port]\n ::Instana.logger.debug \"#{__method__}: Found #{discovered[:agent_host]}:#{discovered[:agent_port]}\"\n return discovered\n end\n\n return nil unless @is_linux\n\n # We are potentially running on Docker in bridged networking mode.\n # Attempt to contact default gateway\n uri = URI.parse(\"http://#{@default_gateway}:#{::Instana.config[:agent_port]}/\")\n req = Net::HTTP::Get.new(uri)\n\n ::Instana.logger.debug \"#{__method__}: Trying default gateway #{@default_gateway}:#{::Instana.config[:agent_port]}\"\n\n response = make_host_agent_request(req)\n\n if response && (response.code.to_i == 200)\n discovered[:agent_host] = @default_gateway\n discovered[:agent_port] = ::Instana.config[:agent_port]\n ::Instana.logger.debug \"#{__method__}: Found #{discovered[:agent_host]}:#{discovered[:agent_port]}\"\n return discovered\n end\n nil\n end", "def agent_only(host)\n host['roles'].length == 1 && host['roles'].include?('agent')\n end", "def agents(args)\n # Convert filter string ({:set=>:all}) to URI string (/set=all)\n # XXX Built-in method to do that?\n filter = \"\"\n args.each do |key, value|\n filter += url_escape(key.to_s) + \"=\" + url_escape(value.to_s) + \"&\"\n end\n filter.chomp!(\"&\")\n\n begin\n Net::HTTP.start(@uri.host, @uri.port) do |http|\n headers = {'Content-Type' => 'text/plain; charset=utf-8', 'Connection' => 'close'}\n start_time = Time.now\n response = http.send_request('GET', @uri.request_uri + filter, headers)\n @log.debug \"Announcement send response time for #{agent.host} = #{Time.now-start_time}\" if @log\n return JSON.parse(response.body).collect { |x| OpenStruct.new(x) }\n end\n rescue Exception => e\n # If the json gem is not loaded, we will log the issue here.\n @log.warn \"Client side error: #{e}\" if @log\n end\n end", "def discover(flags={})\n flags.each_key do |key|\n raise \"Unknown option #{key} passed to discover\" unless [:verbose, :hosts, :nodes, :json].include?(key)\n end\n\n flags.include?(:verbose) ? verbose = flags[:verbose] : verbose = @verbose\n\n verbose = false unless @output_format == :console\n\n # flags[:nodes] and flags[:hosts] are the same thing, we should never have\n # allowed :hosts as that was inconsistent with the established terminology\n flags[:nodes] = flags.delete(:hosts) if flags.include?(:hosts)\n\n reset if flags[:nodes] || flags[:json]\n\n unless @discovered_agents\n # if either hosts or JSON is supplied try to figure out discovery data from there\n # if direct_addressing is not enabled this is a critical error as the user might\n # not have supplied filters so raise an exception\n if flags[:nodes] || flags[:json]\n raise \"Can only supply discovery data if direct_addressing is enabled\" unless Config.instance.direct_addressing\n\n hosts = []\n\n if flags[:nodes]\n hosts = Helpers.extract_hosts_from_array(flags[:nodes])\n elsif flags[:json]\n hosts = Helpers.extract_hosts_from_json(flags[:json])\n end\n\n raise \"Could not find any hosts in discovery data provided\" if hosts.empty?\n\n @discovered_agents = hosts\n @force_direct_request = true\n\n else\n identity_filter_discovery_optimization\n end\n end\n\n # All else fails we do it the hard way using a traditional broadcast\n unless @discovered_agents\n raise(\"Invalid discovery method %s\" % discovery_method) unless @client.discoverer.find_known_methods.include?(discovery_method)\n\n @stats.time_discovery :start\n\n @client.options = options\n\n # if compound filters are used the only real option is to use the mc\n # discovery plugin since its the only capable of using data queries etc\n # and we do not want to degrade that experience just to allow compounds\n # on other discovery plugins the UX would be too bad raising complex sets\n # of errors etc.\n @client.discoverer.force_discovery_method_by_filter(options[:filter])\n\n if verbose\n actual_timeout = @client.discoverer.discovery_timeout(discovery_timeout, options[:filter])\n\n if actual_timeout > 0\n @stderr.print(\"Discovering hosts using the %s method for %d second(s) .... \" % [discovery_method, actual_timeout])\n else\n @stderr.print(\"Discovering hosts using the %s method .... \" % discovery_method)\n end\n end\n\n # if the requested limit is a pure number and not a percent\n # and if we're configured to use the first found hosts as the\n # limit method then pass in the limit thus minimizing the amount\n # of work we do in the discover phase and speeding it up significantly\n filter = @filter.merge({\"collective\" => @collective})\n if (@limit_method == :first) && @limit_targets.is_a?(Integer)\n @discovered_agents = @client.discover(filter, discovery_timeout, @limit_targets)\n else\n @discovered_agents = @client.discover(filter, discovery_timeout)\n end\n\n @stderr.puts(@discovered_agents.size) if verbose\n\n @force_direct_request = @client.discoverer.force_direct_mode?\n\n @stats.time_discovery :end\n end\n\n @stats.discovered_agents(@discovered_agents)\n RPC.discovered(@discovered_agents)\n\n @discovered_agents\n end", "def facterdb_filter(_args = [])\n dynamic_facterdb_filter.ai\n end", "def force_discovery_method_by_filter(filter)\n false\n end", "def before_starting_agents\n end", "def filter\n do_authorize_class\n get_project_if_exists\n get_harvest_if_exists\n\n filter_response, opts = Settings.api_response.response_advanced(\n api_filter_params,\n list_permissions,\n HarvestItem,\n HarvestItem.filter_settings\n )\n respond_filter(filter_response, opts)\n end", "def is_agent?\n self.dig_for_boolean(\"agentSummary\", \"isAgent\")\n end", "def test_filters\n accepted = []\n rejected = []\n self.get_torrents.each do |new_torrent|\n if allowed_by_filters?(new_torrent)\n accepted << new_torrent\n else\n rejected << new_torrent\n end\n end\n \n return {:accepted => accepted, :rejected => rejected}\n end", "def agent_interface\n super\n end", "def agent?\n true\n end", "def findAttackAgent(run)\n run.society.each_node do |node|\n mgmtComp = false\n node.each_facet(:role) do |facet|\n if facet[:role] == $facetManagement ||\n facet[:role] == $facetSubManagement ||\n facet[:role] == $facetRootManagement ||\n facet[:role] == 'RootCertificateAuthority' ||\n facet[:role] == 'CertificateAuthority' ||\n facet[:role] == 'RedundantCertificateAuthority' ||\n facet[:role] == 'AR-Management'\n mgmtComp = true\n break \n end \n end\n if mgmtComp == false\n node.each_agent do |agent|\n # get the first agent from this non-management node\n return agent\n end \n end # if securityComp == false\n end # run.society.each_node\nend", "def capabilities; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if compound filters are used and then forces the 'mc' discovery plugin
def force_discovery_method_by_filter(filter) unless discovery_method == "mc" unless filter["compound"].empty? Log.info "Switching to mc discovery method because compound filters are used" @client.options[:discovery_method] = "mc" return true end end return false end
[ "def force_discovery_method_by_filter(filter)\n false\n end", "def initialize_filter_set_if_needed\n helper = \"#{controller.controller_name.singularize}_filters\"\n send(helper) unless @filter_set\n end", "def global_filter; end", "def identity_filter_discovery_optimization\n if !options[:filter][\"identity\"].empty? && @discovery_method == \"mc\"\n regex_filters = options[:filter][\"identity\"].select {|i| i.match(\"^\\/\")}.size\n\n if regex_filters == 0\n @discovered_agents = options[:filter][\"identity\"].clone\n @force_direct_request = true if Config.instance.direct_addressing\n end\n end\n end", "def platform_filters_available?\n !options.platform.nil?\n end", "def prepare_example_filtering; end", "def check_capabilities(filter)\n capabilities = ddl.discovery_interface[:capabilities]\n\n unless capabilities.include?(:classes)\n raise \"Cannot use class filters while using the '%s' discovery method\" % discovery_method unless filter[\"cf_class\"].empty?\n end\n\n unless capabilities.include?(:facts)\n raise \"Cannot use fact filters while using the '%s' discovery method\" % discovery_method unless filter[\"fact\"].empty?\n end\n\n unless capabilities.include?(:identity)\n raise \"Cannot use identity filters while using the '%s' discovery method\" % discovery_method unless filter[\"identity\"].empty?\n end\n\n unless capabilities.include?(:compound)\n raise \"Cannot use compound filters while using the '%s' discovery method\" % discovery_method unless filter[\"compound\"].empty?\n end\n end", "def strict_filters; end", "def strict_filters=(_arg0); end", "def config_filter(conf, filters=nil)\n\t\t\tconf = conf.clone\n\t\t\tfilters = (conf[:use].rfm_force_array | filters.rfm_force_array).compact\n\t\t\tfilters.each{|f| next unless conf[f]; conf.merge!(conf[f] || {})} if !filters.blank?\n\t\t\tconf.delete(:use)\n\t\t\tconf\n\t\tend", "def add_filters\n if self.meta_tag.canonical?\n self.sub_tag.filtered_works.each do |work| \n unless work.filters.include?(self.meta_tag)\n work.filter_taggings.create!(:inherited => true, :filter_id => self.meta_tag.id)\n end\n end\n end \n end", "def request_filters\n if(self.config_setup[:request_filters])\n @request_filters = (self.config_setup[:request_filters][@product] ? self.config_setup[:request_filters][@product] : {})\n else\n @request_filters = {}\n end\n @request_filters\n end", "def ensure_filters\n # private_methods returns the list of private methods accessible to obj. If the all parameter is set to\n # false, only those methods in the receiver will be listed.\n private_methods(false).grep(/\\Afilter_by_/)&.each { |filter| send(filter) }\n end", "def set_filter(agent, filters, vars)\n agent.reset\n if filters[:discovery]\n agent.discover({:nodes => filters[:discovery]})\n else\n ['identity', 'fact', 'class', 'compound'].each do |kind|\n next unless filters[kind]\n add_filter = agent.method(\"#{kind}_filter\".to_sym)\n if filters[kind].is_a?(String)\n add_filter.call(interpolate(filters[kind], vars))\n else\n filters[kind].each do |filter|\n add_filter.call(interpolate(filter, vars))\n end\n end\n end\n end\n agent\nend", "def applicable_filters\n fs = []\n #fs << Spree::Core::ProductFilters.taxons_below(self)\n #fs << Spree::Core::ProductFilters.brand_filter if Spree::Core::ProductFilters.respond_to?(:brand_filter)\n #fs << Spree::Core::ProductFilters.selective_brand_filter(self) if Spree::Core::ProductFilters.respond_to?(:selective_brand_filter)\n\n fs << Spree::Core::ProductFilters.sort_scope if Spree::Core::ProductFilters.respond_to?(:sort_scope)\n fs << Spree::Core::ProductFilters.price_range_filter if Spree::Core::ProductFilters.respond_to?(:price_range_filter)\n\n\n Spree::Property.all.each do |p|\n method_any = p.name.downcase + \"_any\"\n if Spree::Core::ProductFilters.respond_to?(\"#{method_any}_filter\")\n fs << Spree::Core::ProductFilters.send(\"#{method_any}_filter\", self)\n end\n end\n fs\n end", "def each_module_filter(opts, name, entry)\n\t\treturn false\n\tend", "def filter(*confs)\n filter = confs.last.kind_of?(Hash) ? confs.pop : {}\n unless (filter.keys - (TYPES - [:conf])).empty?\n raise ArgumentError, \"Invalid filter use :include and/or :exclude only: given #{filter.keys.inspect}\"\n end\n includes, excludes, types = filter[:include] || [], filter[:exclude] || [], filter[:type] || []\n \n artifacts = deps(confs.flatten, types.flatten)\n if artifacts\n artifacts = artifacts.find_all do |lib|\n lib = File.basename(lib)\n includes = includes.reject {|i| i.nil? || (i.respond_to?(:empty?) && i.empty?) || (i.respond_to?(:source) && i.source.empty?) }\n should_include = includes.empty? || includes.any? {|include| include === lib }\n should_include && !excludes.any? {|exclude| exclude === lib}\n end\n end\n \n artifacts\n end", "def deep_filters?; end", "def setup_filters\n @filter = {}\n @filter[:bloques] = params[:bloques]\n @filter[:distritos] = params[:distritos]\n @bloques = load_political_parties\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if a compound filter is specified and it has any function then we read the DDL for each of those plugins and sum up the timeout declared in the DDL
def timeout_for_compound_filter(compound_filter) return 0 if compound_filter.nil? || compound_filter.empty? timeout = 0 compound_filter.each do |filter| filter.each do |statement| if statement["fstatement"] pluginname = Data.pluginname(statement["fstatement"]["name"]) ddl = DDL.new(pluginname, :data) timeout += ddl.meta[:timeout] end end end timeout end
[ "def ts_apply_filters\n # TODO: Make filters for Thinking Sphinx\n end", "def initialize_available_filters\n add_available_filter \"spent_on\", :type => :date_past\n\n add_available_filter(\"project_id\",\n :type => :list, :values => lambda { project_values }\n ) if project.nil?\n\n if project && !project.leaf?\n ################\n # Smile specific #768560: V4.0.0 : Time entries list : access to hidden BAR values\n # Smile specific : subproject_values + current project param\n add_available_filter \"subproject_id\",\n :type => :list_subprojects,\n :values => lambda { subproject_values(true) }\n end\n\n ################\n # Smile specific #271407 Time Entries : filter by BU\n # + BU\n unless project\n bu_projects = Project.bu_projects.sort\n\n if bu_projects.any?\n add_available_filter \"bu_project\",\n :label => :label_bu,\n :type => :list_optional,\n :values => ( bu_projects.collect{|p| [p.name, p.id.to_s]} )\n end\n end\n # END -- Smile specific #271407 Time Entries : filter by BU\n #######################\n\n ################\n # Smile specific #355842 Rapport temps passé : filtre projet mis-à-jour\n # No way to filter projects of sub-request for project_updated_on, if no project\n # + PROJECT UPDATED ON\n add_available_filter('project_updated_on',\n :type => :date_past,\n :name => \"#{l(:label_project)} #{l(:field_updated_on)}\"\n ) if project\n # END -- Smile specific #355842 Rapport temps passé : filtre projet mis-à-jour\n #######################\n\n ################\n # Smile specific : new filters, only if on project\n # Smile comment : Too heavy for all projects query\n if advanced_filters\n if project\n ################\n # Smile specific #423277 Rapport : Filtre sur tâche parente et racine\n # + ROOT_ID, PARENT_ID\n add_available_filter 'root_id',\n :name => l('field_issue_root_id'),\n :type => :list_optional,\n :values => lambda {\n calc_project_and_children_issues\n @children_root_issues_id_and_label\n }\n\n add_available_filter 'parent_id',\n :name => l('field_issue_parent_id'),\n :type => :list_optional,\n :values => lambda {\n calc_project_and_children_issues\n @children_parent_issues_id_and_label\n }\n\n ################\n # Smile specific #247451 Entrées de temps et Rapport : filtre par demande\n # * Unable to know if we are on an issue :\n # scope modified afterwards by the controller to filter on issue\n # => possible to filter on an issue that is not the current one\n # => obviously will return no result\n # + ISSUE_ID\n add_available_filter 'issue_id',\n :type => :list_optional,\n :values => lambda {\n calc_project_and_children_issues\n @children_issues_id_and_label\n }\n # END -- Smile specific #247451 Entrées de temps et Rapport : filtre par demande\n #######################\n\n #---------------\n # Smile specific #147568 Filter on parent task\n # children_count\n # Works even if NO project specified\n add_available_filter 'children_count', :type => :integer\n\n #---------------\n # Smile specific #226967 Filter 'number of parents'\n add_available_filter 'level_in_tree',\n :type => :integer\n end\n else\n # NATIVE source code\n add_available_filter(\"issue_id\", :type => :tree, :label => :label_issue)\n end\n # END -- Smile specific : new filters, only if on project\n #######################\n\n\n ################\n # Smile specific : issue created on filter\n # + ISSUE CREATED ON\n add_available_filter \"issue_created_on\", :type => :date_past, :name =>\"#{l(:field_issue)} #{l(:field_created_on)}\"\n\n add_available_filter(\"issue.tracker_id\",\n :type => :list,\n :name => l(\"label_attribute_of_issue\", :name => l(:field_tracker)),\n :values => lambda { trackers.map {|t| [t.name, t.id.to_s]} })\n add_available_filter(\"issue.status_id\",\n :type => :list,\n :name => l(\"label_attribute_of_issue\", :name => l(:field_status)),\n :values => lambda { issue_statuses_values })\n add_available_filter(\"issue.fixed_version_id\",\n :type => :list,\n :name => l(\"label_attribute_of_issue\", :name => l(:field_fixed_version)),\n :values => lambda { fixed_version_values })\n add_available_filter \"issue.category_id\",\n :type => :list_optional,\n :name => l(\"label_attribute_of_issue\", :name => l(:field_category)),\n :values => lambda { project.issue_categories.collect{|s| [s.name, s.id.to_s] } } if project\n\n add_available_filter(\"user_id\",\n :type => :list_optional, :values => lambda { author_values }\n )\n\n ################\n # Smile specific #831010: Time Report Query : new time entry user filter, me\n if User.current.logged?\n add_available_filter(\"user_id_me\",\n :type => :list_optional, :values => lambda { [[\"<< #{l(:label_me)} >>\", 'me']] }, :name =>\"#{l(:field_user)} (#{l(:label_me)})\"\n )\n end\n\n ################\n # Smile specific : starting from Redmine ~ 4\n if TimeEntry.instance_methods.include?(:author)\n add_available_filter(\"author_id\",\n :type => :list_optional, :values => lambda { author_values }\n )\n end\n\n ################\n # Smile specific #831010: Time Report Query : new time entry user filter, me\n # + AUTHOR_ID_ME\n if Redmine::VERSION::MAJOR >= 4\n if User.current.logged?\n add_available_filter(\"author_id_me\",\n :type => :list_optional, :values => lambda { [[\"<< #{l(:label_me)} >>\", 'me']] }, :name =>\"#{l(:field_author)} (#{l(:label_me)})\"\n )\n end\n end\n\n ################\n # Smile specific #473776 Spent Time Report : Filter on Assignee's group\n # + MEMBER OF GROUP\n add_available_filter(\"member_of_group\",\n :type => :list_optional, :values => lambda { Group.givable.order(:lastname).collect {|g| [g.name, g.id.to_s]} }\n )\n # END -- Smile specific #473776 Spent Time Report : Filter on Assignee's group\n #######################\n\n activities = (project ? project.activities : TimeEntryActivity.shared)\n add_available_filter(\"activity_id\",\n :type => :list, :values => activities.map {|a| [a.name, a.id.to_s]}\n )\n\n add_available_filter(\"project.status\",\n :type => :list,\n :name => l(:label_attribute_of_project, :name => l(:field_status)),\n :values => lambda { project_statuses_values }\n ) if project.nil? || !project.leaf?\n\n add_available_filter \"comments\", :type => :text\n\n ################\n # Smile specific\n # + ESTIMATED HOURS\n add_available_filter \"estimated_hours\", :type => :float\n\n ################\n # Smile specific #994 Budget and Remaining enhancement\n # If we display all issue, display budget_hours and remaining_hours columns\n # + BUDGET HOURS\n budget_and_remaining_enabled = Project.respond_to?('b_a_r_module') &&\n ( self.project.nil? || self.project.budget_and_remaining_enabled )\n\n add_available_filter \"budget_hours\", :type => :float if budget_and_remaining_enabled\n # END -- Smile specific #994 Budget and Remaining enhancement\n #######################\n\n add_available_filter \"hours\", :type => :float\n\n add_available_filter \"spent_hours_for_issue_and_user\", :type => :float\n add_available_filter \"spent_hours_for_issue\", :type => :float\n add_available_filter \"spent_hours_for_user\", :type => :float\n\n add_available_filter \"spent_hours_for_issue_and_user_this_month\", :type => :float\n add_available_filter \"spent_hours_for_issue_this_month\", :type => :float\n add_available_filter \"spent_hours_for_user_this_month\", :type => :float\n\n add_available_filter \"spent_hours_for_issue_and_user_previous_month\", :type => :float\n add_available_filter \"spent_hours_for_issue_previous_month\", :type => :float\n add_available_filter \"spent_hours_for_user_previous_month\", :type => :float\n\n ################\n # Smile specific #994 Budget and Remaining enhancement\n # + REMAINING HOURS\n add_available_filter \"remaining_hours\", :type => :float if budget_and_remaining_enabled\n # END -- Smile specific #994 Budget and Remaining enhancement\n #######################\n\n #################\n # Added by plugin\n list_yes_no =\n [\n [l(:general_text_Yes), '1'], # index must be a string !\n [l(:general_text_No), '0'],\n ]\n\n add_available_filter \"is_last_time_entry_for_issue_and_user\", :type => :list_optional, :values => list_yes_no\n add_available_filter \"is_last_time_entry_for_issue\", :type => :list_optional, :values => list_yes_no\n add_available_filter \"is_last_time_entry_for_user\", :type => :list_optional, :values => list_yes_no\n\n add_custom_fields_filters(TimeEntryCustomField)\n add_associations_custom_fields_filters :project\n add_custom_fields_filters(issue_custom_fields, :issue)\n add_associations_custom_fields_filters :user\n end", "def length(filter_name = nil, &block)\n filter_proc = @filters[filter_name] \n \n @filters.synchronize do\n filter_proc ? @tasks.count(&filter_proc) : nil\n end\n end", "def reset_filter type\n ## transform date into timestamp\n min_date = @opts[:min_date] || '02/01/1970' ## if no min date, delete \n ## all before max_date then \n min_date = Util.date(min_date,format: \"%Y-%m-%d %H:%M:%S\") \n max_date = @opts[:max_date] || 'now'\n max_date = Util.date(max_date,format: \"%Y-%m-%d %H:%M:%S\")\n min_ts = Util.date(min_date,format: \"%s\")\n max_ts = Util.date(max_date,format: \"%s\")\n ## create & query sql§\n if type == :files\n sql = \"DELETE FROM #{@table_files} WHERE timest BETWEEN \" +\n \" '#{min_date}' AND '#{max_date}'\"\n puts sql if @opts[:v]\n @db.connect { @db.query(sql) }\n elsif type == :records\n time_field = @source.flow.time_field_records\n sql_id = \"SELECT distinct file_id from #{@table_records_union}\" +\n \" WHERE #{time_field} BETWEEN #{min_ts} AND #{max_ts}\"\n @db.connect do\n puts sql_id if @opts[:v]\n res = @db.query(sql_id)\n ids = []\n ## take the ids that we will remove, so we can mark them as unprocesse\n res.each_hash { |row| ids << row['file_id'] }\n sql = \"DELETE FROM %s WHERE #{@source.flow.time_field_records} \" +\n \"BETWEEN #{min_ts} AND #{max_ts}\"\n sql_unproc = \"UPDATE #{@table_files} SET processed = 0 WHERE file_id IN (#{RubyUtil::sqlize(ids,:no_parenthesis => true, :no_quotes => true)})\"\n @db.query(sql % @table_records)\n @db.query(sql % @table_records_union)\n @db.query(sql_unproc) unless ids.empty?\n end\n end\n end", "def create_query_hints\n if actions.any?\n actions.each do |action,queries|\n queries.each do |query|\n duration=query.duration.to_i\n if query.explain_issues? # slow & explain issues. we can give more details.\n importance = 0\n importance += 1 if duration > 100\n importance += 1 if duration > 200\n importance += 1 if duration > 300\n importance = 3 if importance > 3 # importance maxes out at 3\n add_hint(\n :title => \"A #{duration}ms query in the #{query.table} table may be able to be optimized.\",\n :description => \"The query #{query.explain_issues.size > 1 ? 'has the following issues:' : 'is'} #{query.explain_issues.join(', ')}\",\n :grouping => action,\n :token => \"explain #{query.sanitized_sql}\",\n :additional_info => query.sanitized_sql,\n :importance=>importance,\n :tag_list=>'slow,explain_issues'\n \n )\n else # just slow\n # calculate importance\n importance = 0\n importance += 1 if duration > 100\n importance += 1 if duration > 200\n importance += 1 if duration > 300\n add_hint(\n :title => \"A slow query occurred (#{duration} ms).\",\n :description => \"This query exceeds the maximum specified duration of #{MAX_QUERY_TIME}ms.\",\n :grouping => action,\n :token => \"slow #{query.sanitized_sql}\",\n :additional_info => query.sanitized_sql,\n :importance=>importance,\n :tag_list=>'slow'\n )\n end\n end\n end\n end # actions.any?\n end", "def add_filters(type, sql)\n @filter_opts.each do |opt, arg|\n case opt\n when :css\n sql += \"AND lower(css.name) LIKE lower('#{arg}') \"\n when :partition\n sql += \"AND lower(rp.name) LIKE lower('#{arg}') \"\n when :pattern\n sql += \"AND lower(pattern) LIKE lower('#{arg}') \"\n when :route_list\n sql += \"AND lower(d.name) LIKE lower('#{arg}') \" unless type.eq('trunk')\n when :route_group\n sql += \"AND lower(rg.name) LIKE lower('#{arg}') \" unless type.eq('trunk')\n when :device\n sql += \"AND lower(dd.name) LIKE lower('#{arg}') \"\n end\n end\n sql\nend", "def check_timer_plugins\n @timer_plugins.each do |plugin|\n begin\n # Need to refer directly to the array since we'll be changing its values\n # plugin[0]: name\n # plugin[1]: interval\n # plugin[2]: next_run_at\n # plugin[3]: block\n # plugin[4]: options\n \n if plugin[2] < Time.now\n plugin[3].call()\n plugin[2] = Time.now + plugin[1]\n end\n rescue Exception => e\n e.dump(@logger)\n end\n end\n end", "def select_stats(dispatcher, *filter)\n lf = []\n while q = filter.shift\n lf << \n case q\n when 'on_node' then\n n = filter.shift \n lambda { |req| req.rjr_node_type.to_s == n}\n\n when \"for_method\" then\n m = filter.shift\n lambda { |req| req.rjr_method == m}\n\n when 'successful' then\n lambda { |req| req.result.success }\n\n when 'failed' then\n lambda { |req| req.result.failed }\n\n end\n end\n\n dispatcher.requests.select { |ds| lf.all? { |lfi| lfi.call(ds) } }\nend", "def get_filtering_module(db,plugin)\t\t \n\t\t # Creates a hash to store modules options\n\t\tmodule_options = {}\n\t\tbooleans = []\n\t\t # Add minratio to modules options\n\t\tmodule_options['minratio'] = @params.get_param(\"#{plugin}_minratio\")\n\t\t # Path to database\n\t\tmodule_options['path'] = @stbb_db.get_info(db,'index')\n\t\t # Name and path for the statistics to be generated in the decontamination process\n\t\tmodule_options['refstats'] = File.join(File.expand_path(OUTPUT_PATH),'plugins_logs',\"#{@stbb_db.get_info(db,'name')}_#{plugin}_filtering_stats.txt\")\n\t\t # Adding #{plugin} aditional params\n\t\tbooleans << @params.get_param(\"#{plugin}_aditional_params\") if !@params.get_param(\"#{plugin}_aditional_params\").nil? \n\t\t # Adding booleans to module_options\n\t\tmodule_options['booleans'] = booleans if !booleans.empty?\n\t\t # Adding commandline redirection\n\t\tmodule_options['redirection'] = [\"2>\",File.join(File.expand_path(OUTPUT_PATH),'plugins_logs',\"#{@stbb_db.get_info(db,'name')}_#{plugin}_filtering_stats_cmd.txt\")] \n\t\t # Change pipe\n\t\tmodule_options['out'] = nil\n\t\tmodule_options['outu'] = 'stdout.fastq'\n\t\t # Return\n\t\treturn module_options\n\tend", "def apply_filter\n end", "def facterdb_filter(_args = [])\n dynamic_facterdb_filter.ai\n end", "def prepare_example_filtering; end", "def getFacts(elapsedTime=-1,tagConds=[],timeStr=\"\",pivotTime=\"\")\n filtered=@facts.dup\n #filtering based on tag conditions\n if tagConds.length > 0\n tagConds.each do |query|\n root,subclause = query.split(',')\n if subclause == '*'\n filtered.select! do |fact|\n fact.tags.keys.include?(root)\n end\n else\n invert = subclause[0] == '~' #will be xor'd with the conditional\n conditions = (invert ? subclause[1...subclause.length].split('|') : subclause.split('|'))\n filtered.select! do |fact|\n #(fact.tags.keys.include?(root) and (conditions.include?(fact.tags[root][:subclass]))) ^ invert COMMENT:this is for when root tag hashes weren't arrays\n (fact.tags.keys.include?(root) and (fact.tags[root].inject(false) { |cum,tg| (cum or conditions.include?(tg[:subclass])) })) ^ invert \n end\n end\n end\n end\n\n #filtering based on time string\n if timeStr != \"\"\n mdy,tod,dow = timeStr.split(',')\n m,d,y = mdy.split('/')\n #TODO: currently searches for exact hours and minutes, but in the future it might be useful to create a pivot around the hour and minutes for more flexible searches\n h,mi = tod.split(':')\n checkConds = {dow => :dow,m => :month,d => :day,y => :year,h => :hour,mi => :minute}.select { |strk,strv| strk != '*' }\n\n filtered.select! do |fact|\n keep = true\n checkConds.each do |strk,strv|\n keep = (keep and fact.timestamp[strv] == strk)\n end\n keep\n end\n end\n\n #filtering based on elapsed time\n #must create a DateTime\n #then pivot around that DateTime\n if elapsedTime > 0\n now = Time.now\n mdy_star = false\n hmi_star = false\n if pivotTime != \"\"\n mdy,tod = pivotTime.split(',')\n m,d,y = (mdy == '*' ? [now.month,now.day,now.year] : mdy.split('/'))\n h,mi = (tod == '*' ? [0,0] : tod.split(':'))\n hmi_star = tod == '*'\n mdy_star = mdy == '*'\n now = Time.new(y,m,d,h,mi)\n end\n #TODO: note--currently only considers one timezone\n if mdy_star and not hmi_star and elapsedTime < 24 * 60 * 60\n filtered.select! do |fact|\n tmp = Time.new(fact.timestamp[:year],fact.timestamp[:month],fact.timestamp[:day],now.hour,now.min)\n (tmp - Time.new(fact.timestamp[:year],fact.timestamp[:month],fact.timestamp[:day],fact.timestamp[:hour],fact.timestamp[:minute])).abs <= elapsedTime\n end\n else\n filtered.select! do |fact|\n tmp = now - Time.new(fact.timestamp[:year],fact.timestamp[:month],fact.timestamp[:day],fact.timestamp[:hour],fact.timestamp[:minute])\n tmp.abs <= elapsedTime\n end\n end\n end\n\n return filtered\n end", "def filters_description\n if filters[:boot].to_s == \"-1\"\n desc_boot = _(\"from previous boot\")\n else\n desc_boot = _(\"since system's boot\")\n end\n\n strings = [\n [:unit, _(\"unit (%s)\")],\n [:match, _(\"file (%s)\")],\n [:priority, _(\"priority (%s)\")]\n ]\n others = []\n\n strings.each do |filter, string|\n if value = filters[filter]\n others << string % value\n end\n end\n\n if others.empty?\n desc_others = _(\"with no additional conditions\")\n else\n desc_others = _(\"filtering by %s\") % others.join(\", \")\n end\n\n \"#{desc_boot} #{desc_others}\"\n end", "def filter_by_time \n\t\t#filtered_by_time logic moved to index in order to avoid duplicated code\n\tend", "def Header_SetFilterChangeTimeout(hwnd, i) send_header_message(hwnd, :SETFILTERCHANGETIMEOUT, lparam: i) end", "def parse_filters\n if raw_filters = @options[:filter]\n filters = {}\n #load predefined filters\n predef_filters = (File.exists?(FILTER_FILE) ? YAML.load_file(FILTER_FILE).merge(PREDEFINED_FILTERS) : PREDEFINED_FILTERS)\n\n raw_filters.each do |f|\n f.strip!\n #only the first colon matters here\n split_pos = f.index(\":\")\n node_key, raw_regexps = f[0...split_pos], f[split_pos + 1..-1]\n \n node = TRAVERSAL_ORDER.find {|n| node_key.index(n.to_s) == 0 }.to_s\n #TODO: make a lookup table for the keys to avoid syntax checks\n key = node_key[node.length + 1..-1]\n unless node && raw_regexps\n STDERR.puts \"Attn: invalid filter <#{f}>\"\n next\n end\n\n #sort positive and negative filters\n node = node.to_sym\n filters[node] ||= {:pos => {}, :neg => {}}\n\n #check for predefined filters\n if raw_regexps =~ /\\A\\/([^\\/]*\\/)*\\Z/\n regexps = raw_regexps.split(\"/\").delete_if {|s| s.empty?}\n if key[-1..-1] == '^'\n filters[node][:neg][key[0...-1].to_sym] = regexps\n else\n filters[node][:pos][key.to_sym] = regexps\n end\n elsif predef_filter = PREDEFINED_FILTERS[raw_regexps.to_sym]\n filters[node][predef_filter[0]][key.to_sym] = predef_filter[1]\n else next\n end\n end\n\n if DEBUG\n puts \"Raw filters: \" \n pp raw_filters\n puts \"Parsed filters: \"\n pp filters \n end\n\n filters\n else {}\n end\nend", "def load_filters(*args)\n require_rel 'filters'\n ::TeeLogger::Filter.constants.collect {|const_sym|\n ::TeeLogger::Filter.const_get(const_sym)\n }.each do |filter|\n begin\n register_filter(filter)\n if not ENV['TEELOGGER_VERBOSE'].nil? and ENV['TEELOGGER_VERBOSE'].to_i > 0\n puts \"Registered filter #{filter}.\"\n end\n rescue StandardError => err\n if not ENV['TEELOGGER_VERBOSE'].nil? and ENV['TEELOGGER_VERBOSE'].to_i > 0\n puts \"Not registering filter: #{err}\"\n end\n end\n end\n end", "def check_capabilities(filter)\n capabilities = ddl.discovery_interface[:capabilities]\n\n unless capabilities.include?(:classes)\n raise \"Cannot use class filters while using the '%s' discovery method\" % discovery_method unless filter[\"cf_class\"].empty?\n end\n\n unless capabilities.include?(:facts)\n raise \"Cannot use fact filters while using the '%s' discovery method\" % discovery_method unless filter[\"fact\"].empty?\n end\n\n unless capabilities.include?(:identity)\n raise \"Cannot use identity filters while using the '%s' discovery method\" % discovery_method unless filter[\"identity\"].empty?\n end\n\n unless capabilities.include?(:compound)\n raise \"Cannot use compound filters while using the '%s' discovery method\" % discovery_method unless filter[\"compound\"].empty?\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This should be called if you cannot find a paper through other means.
def fallback_to_first_possible_paper_reference model = @model_hash.values.detect { |model| model.try(:paper) } model.try(:paper) end
[ "def for_paper(paper)\n where(paper_id: paper.id)\n end", "def double_review\n @paper = Paper.find(params[:paper_id])\n @paper.reviews.each do |r|\n if r.user == current_user\n redirect_to paper_path(@paper)\n flash[:error] = \"You have already made a review for this paper. Please edit the current review.\"\n end\n end\n end", "def scited_by_uid(papers)\n map_exists :paper_uid, scites.where(paper_uid: papers.map(&:uid))\n end", "def pmid\n pmid = params[:pmid].to_i\n @paper = Paper.find_or_create_by_pubmed_id(pmid)\n if @paper.title.nil?\n @paper.lookup_info\n end\n @paper.save\n\n if @error\n flash[:error] = @error\n redirect_to :back\n else\n respond_to do |format|\n format.html { redirect_to @paper}\n format.xml { render :xml => @paper.xml_hash}\n end\n\n end\n end", "def first_reference_paper\n reference_papers[0]\n end", "def find_book(permalink)\n @book = Book.find_by_permalink(permalink) || raise(ActiveRecord::RecordNotFound)\n end", "def ocr_with_mistakes\n \n end", "def pre_art_pcb(design_review, review_results)\n return (review_results.find { |rr| rr.role.name == \"PCB Design\" } &&\n design_review.review_type.name == \"Pre-Artwork\")\nend", "def find_media_in_passerelle research_name\n\t\tcandidates = BienPhoto.where(:passerelle_id => @passerelle.id).select{ |bp| bp.bien_id == nil }\n\t\tcandidates.each { |bp|\n\t\t\tnext unless bp.attributs\n\t\t\tbp.attributs.split('|').each{ |n|\n\t\t\treturn bp if research_name.to_s.downcase == n.to_s.downcase\n\t\t\t}\n\t\t}\n\n\t\t# @medias[p.attributs] = p\n\n\t\tLogger.send(\"warn\", \"Media not found in orphan passerelle medias!\")\n\t\treturn nil\n\tend", "def correction_existent_check\n # Check first if there is a correction\n page_content = PageContent.where(:page_id => self.id).where(:content_type => 'correction').order(id: :asc).last\n\n # If there isn't a correction,\n # Go to the ocr or text extraction\n if !page_content \n page_content = PageContent.where(:page_id => self.id).first\n end\n\n return page_content\n end", "def default_card\n name = if paper.uses_research_article_reviewer_report\n \"ReviewerReport\"\n else\n # note: this AR model does not yet exist, but\n # is being done as preparatory / consistency for\n # card config work\n \"TahiStandardTasks::FrontMatterReviewerReport\"\n end\n Card.find_by(name: name)\n end", "def index\n # cancan 인증으로 필요 없음.\n # 모든 사용장의 논문을 보여준다.\n #@papers = Paper.all\n \n #현재 사용자의 논문만 보여준다. \n @papers = current_user.papers.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @papers }\n end\n end", "def proposed_negative_statutory_instrument_papers\n respond_to?(:statutoryInstrumentPaperFollowsProposedNegativeStatutoryInstrumentPaper) ? statutoryInstrumentPaperFollowsProposedNegativeStatutoryInstrumentPaper : []\n end", "def find_by_pid(pid)\n find(pid)\n rescue Hyacinth::Exceptions::DigitalObjectNotFoundError\n return nil\n end", "def find(term)\n\n\t raise NoWordnetConnection, \"There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object.\" unless connected?\n\t homographs = @wordnet_connection.homographs(term)\n\t Homographs.new(homographs, @wordnet_connection) unless homographs.nil?\n\n\tend", "def find_a_park\n # prompt = TTY::Prompt.new\n temp = @prompt.ask(\"⛰ Which park do you want to learn about?🏕 \", required: true)\n\n if Park.all.find { |park| park.name == temp} == nil\n puts \"Please input an actual park\"\n else\n list_info(temp, 0)\n\n end\n\n menu\n end", "def last_chance_find_media research_name\n\t@passerelle.biens.each{ |b|\n\t\tb.bien_photos.each{ |p|\n\t\t\tnext unless p.attributs\n\t\t\tp.attributs.split('|').each{ |n|\n\t\t\t\treturn p if research_name.to_s.downcase == n.to_s.downcase\n\t\t\t}\n\t\t\t@medias[p.attributs] = p\n\t\t}\n\t}\n\treturn nil\n end", "def original_manifestation_for_publication\n find_related_frbr_objects( :is_the_publication_of, :which_manifestations?) \n end", "def recipe_not_found(exception); end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read a yaml file containing a menu
def read_yml_menu(filename) # Load the yaml file into a hash settings = YAML::load_file filename # These are now hashes with ingredient name as key # with hashes representing ingredients, that contain metadata such as prices meats = settings[:ingredients][:meats] vegetables = settings[:ingredients][:vegetables] dressings = settings[:ingredients][:dressings] leaf = settings[:ingredients][:leaf] # Convert to format using ingredient classes ingredients = { :meats => hash_to_ingredient(meats), :vegetables => hash_to_ingredient(vegetables), :dressings => hash_to_ingredient(dressings), :leaf => hash_to_ingredient(leaf)} sizes = settings[:sizes] return ingredients, sizes end
[ "def yaml\n File.read(@name)\n end", "def read file=STDIN\n\n yaml = case file\n when String\n raise \"Input file not defined\" unless file\n raise \"Input file does not exist\" unless File.exist? file\n raise \"Input file is not readable \" unless File.readable? file\n \n File.read(file)\n when IO\n file.read\n end\n\n raise \"Cannot read YAML data\" unless yaml\n load yaml\n end", "def load_yml(filename); end", "def get_menu_path\n until @yaml\n Yuyi.say 'Navigate to a menu file...', :type => :success\n Yuyi.ask \"...or just press enter to load `#{Yuyi::DEFAULT_MENU}`\", :readline => true do |user_path|\n menu_path = user_path.empty? ? Yuyi::DEFAULT_MENU : user_path\n load_from_file menu_path\n end\n end\n end", "def read_yaml(path)\n data = File.read path\n\n # Necessary to be backward-compatible with documentation generated\n # by earliar RDoc versions.\n data = data.gsub(/ \\!ruby\\/(object|struct):(RDoc::RI|RI).*/, '')\n data = data.gsub(/ \\!ruby\\/(object|struct):SM::(\\S+)/,\n ' !ruby/\\1:RDoc::Markup::\\2')\n\n OpenStructHash.convert YAML.load(data)\n end", "def load_from_file menu_path = @menu_path\n if !menu_path || menu_path.empty?\n get_menu_path\n return\n end\n\n unless @menu_path\n # check if path is local first\n begin\n File.open(File.expand_path(menu_path))\n\n @menu_path = File.expand_path(menu_path)\n\n # otherwise assume it is remote and try to download it\n rescue\n # try to download the menu path\n response = Yuyi.run \"curl -sS #{menu_path}\"\n\n # save a local copy of the remote menu\n if $?.success?\n # if a menu was downloaded, save the response to a local file\n local_file_name = Yuyi::DEFAULT_MENU.clone << '_remote'\n\n File.open local_file_name, 'w+' do |f|\n f.write response\n end\n\n @menu_path = local_file_name\n end\n end\n end\n\n begin\n @yaml = YAML.load(File.open(@menu_path)).deep_symbolize_keys!\n rescue\n Yuyi.say \"No menu could be loaded from `#{menu_path}`\", :type => :fail\n get_menu_path\n end\n end", "def yaml(*files, **options, &block) = read(*files, parse: :yaml, ext: ['.yml', '.yaml'], **options, &block)", "def generate_menu \n # logger.warn(\"Rails-Root is: #{Rails.root}\")\n Menu.new(YAML::load_file(\"#{Rails.root}/config/menu.yml\"))\n end", "def read_definitions_file\n if ::File.exist?(definitions_file_path)\n ::YAML.safe_load(File.read(definitions_file_path)) || []\n else\n raise LoadError, \"Could not find menus.yml file! Please run `rails generate alchemy:install`\"\n end\n end", "def read_definitions_file\n if ::File.exist?(definitions_file_path)\n ::YAML.safe_load_file(definitions_file_path) || []\n else\n raise LoadError, \"Could not find menus.yml file! Please run `rails generate alchemy:install`\"\n end\n end", "def data\n YAML.load ERB.new(File.read File.expand_path yaml_path).result\n rescue StandardError, SyntaxError => e\n {}\n end", "def read_yaml(base, name)\n self.content = File.read(File.join(base, name))\n \n if self.content =~ /^(---\\s*\\n.*?)\\n---\\s*\\n/m\n self.content = self.content[($1.size + 5)..-1]\n \n self.data = YAML.load($1)\n end\n end", "def configure_by_yaml(path=nil)\n unless path\n # Display file explorer\n path = Qt::FileDialog.getOpenFileName(self, \"Open configuration file\", \".\", \"YAML Files (*.yml *.yaml)\")\n end\n\n begin \n # Load configuration from YAML\n hash = YAML.load(open(path))\n \n # Sanity checks:\n error = nil\n \n if hash.keys.max > @container_hash.keys.max\n error = \"Higher position value in file than #containers available.\"\n elsif hash.size > @container_hash.size\n error = \"More config items in file than containers available.\"\n end\n \n if error\n msg_box = Qt::MessageBox.new\n msg_box.set_text(\"Problem with YAML import:\")\n msg_box.set_informative_text(error)\n msg_box.exec\n return\n end\n \n # Disconnect, update configuration and connect for each container\n hash.each do |pos, config|\n container = @container_hash[pos]\n container.disconnect\n container.configure_by_obj(config)\n container.connect if config\n end\n rescue Exception => e\n Vizkit.error \"A problem occured while trying to open '#{path}': \\n#{e.message}\"\n Vizkit.error e.backtrace.inspect \n end\n end", "def read_yaml(base, name)\n self.content = File.read(File.join(base, name))\n \n if self.content =~ /^(---\\s*\\n.*?\\n?)^(---\\s*$\\n?)/m\n self.content = self.content[($1.size + $2.size)..-1]\n \n self.data = YAML.load($1)\n end\n \n self.data ||= {}\n end", "def read_config name\n\tpath = absolutePath()\n\tpath = path+\"/support/\"+\"roster.yml\"\n\tconfig = YAML.load_file(path)\n\t@title = config[name]\n\treturn @title\t\nend", "def load_yaml(file_name)\n index_data = YAML.load_file(file_name)\n return index_data\nend", "def from_yaml(filename); end", "def yaml(key)\n d = self.details\n return [] if d.nil?\n \n meta = YAML::load(d)\n meta[key]\n end", "def read_yaml(base, name, opts = {})\n begin\n self.content = File.read(File.join(base, name),\n merged_file_read_opts(opts))\n if content =~ /\\A(---\\s*\\n.*?\\n?)^((---|\\.\\.\\.)\\s*$\\n?)/m\n self.content = $POSTMATCH\n self.data = SafeYAML.load($1)\n end\n rescue SyntaxError => e\n Jekyll.logger.warn \"YAML Exception reading #{File.join(base, name)}: #{e.message}\"\n rescue Exception => e\n Jekyll.logger.warn \"Error reading file #{File.join(base, name)}: #{e.message}\"\n end\n\n self.data ||= {}\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a hash of ingredients with metadata to a list of Ingredient objects
def hash_to_ingredient(dict) ingredients = Array.new # Each ingredient has name as key, and metadata as a dictionary. # At this point, we just extract the price, but we can expand this later dict.each do |name,ingr| ingredients.push(Salads::Ingredient.new(name, ingr["price"])) end return ingredients end
[ "def ingredients\n recipe_ingredients.map do |r|\n r.ingredient\n end\n end", "def ingredients\n recipeingredient.map {|ri| ri.ingredient}\n end", "def ingredients\n self.recipe_ingredients.map do |recipe_ingredient|\n recipe_ingredient.ingredient\n end\n end", "def ingredients\n ingredients = db_connection do |conn|\n conn.exec(\"SELECT ingredients.name FROM recipes\n JOIN ingredients ON ingredients.recipe_id = recipes.id\n WHERE recipes.id = ($1)\", [@id])\n end\n ingredients_list = []\n ingredients.to_a.each do |ingredient|\n ingredients_list << Ingredient.new(ingredient[\"name\"])\n end\n ingredients_list\n end", "def parse_ingredients(ingredients)\n ret = {}\n ingredients.each do |ingredient|\n ing = parse_ingredient ingredient\n ret[ing.name.downcase] = ing\n end\n ret\n end", "def extract_ingredients(input)\n ingredients = {}\n input.map do |ingredient|\n matches = ingredient.match(/(.*): \\w* (-?\\d+), \\w* (-?\\d+), \\w* (-?\\d+), \\w* (-?\\d+), \\w* (-?\\d+)/)\n ingredients[matches[1]] = { capacity: matches[2].to_i, durability: matches[3].to_i, flavor: matches[4].to_i, texture: matches[5].to_i, calories: matches[6].to_i }\n end\n ingredients\n end", "def get_recipe_ingredients(recipe)\n ing_quant_pairs = []\n Recipe2Ingredient.where(recipe_id: recipe.id).each do |link_id|\n\n ing = Ingredient.find(link_id.ing_id).ing_name\n quant = link_id.quantity\n\n ing_quant_pairs.push([ing, quant])\n end\n ing_quant_pairs\n end", "def setup_ingredients(left_over_meal_hash)\n @ingredient = {}\n left_over_meal_hash.each do |key, value|\n next if value == '' || value == ' ' || value.nil? # prevent blank entries\n\n case key\n when /strIngredient.+/\n location = key.to_s.gsub('strIngredient', '')\n measure = 'strMeasure' + location.to_s\n @ingredient[value] = left_over_meal_hash[measure.to_sym]\n end\n end\n @ingredient.compact!\n end", "def cookbook_ingredients\n @cookbook.map do |recipe|\n recipe.ingredients\n end\n end", "def ingredients\n desserts.map {|dessert| dessert.ingredients}.flatten\n end", "def ingredients\n desserts.map do |dessert|\n dessert.ingredients\n end.flatten\n end", "def ingredients\n self.dessert_ingredients.map {|di| di.ingredient}\n end", "def ingredients\n element.definition.fetch(:ingredients, []).map do |ingredient|\n Alchemy::IngredientEditor.new(find_or_create_ingredient(ingredient))\n end\n end", "def ingredients\n {\n malts: { #colour vals in SRM\n :acid_malt=>{:name=>\"Acid Malt\", :origin=>\"Germany\", :type=>\"Grain\", :colour=>3, :must_mash=>true, :ppg=>1.027},\n :amber_dry_extract=>{:name=>\"Amber Dry Extract\", :origin=>\"US\", :type=>\"Dry Extract\", :colour=>13, :must_mash=>false, :ppg=>1.044},\n :amber_liquid_extract=>{:name=>\"Amber Liquid Extract\", :origin=>\"US\", :type=>\"Extract\", :colour=>13, :must_mash=>false, :ppg=>1.036},\n :amber_malt=>{:name=>\"Amber Malt\", :origin=>\"United Kingdom\", :type=>\"Grain\", :colour=>22, :must_mash=>true, :ppg=>1.035},\n :aromatic_malt=>{:name=>\"Aromatic Malt\", :origin=>\"Belgium\", :type=>\"Grain\", :colour=>26, :must_mash=>true, :ppg=>1.036},\n :barley_hulls=>{:name=>\"Barley Hulls\", :origin=>\"US\", :type=>\"Adjunct\", :colour=>0, :must_mash=>false, :ppg=>1.0},\n :barley_flaked=>{:name=>\"Barley, Flaked\", :origin=>\"US\", :type=>\"Grain\", :colour=>2, :must_mash=>true, :ppg=>1.032},\n :barley_raw=>{:name=>\"Barley, Raw\", :origin=>\"US\", :type=>\"Grain\", :colour=>2, :must_mash=>true, :ppg=>1.028},\n :barley_torrefied=>{:name=>\"Barley, Torrefied\", :origin=>\"US\", :type=>\"Grain\", :colour=>2, :must_mash=>true, :ppg=>1.036},\n :biscuit_malt=>{:name=>\"Biscuit Malt\", :origin=>\"Belgium\", :type=>\"Grain\", :colour=>23, :must_mash=>false, :ppg=>1.036},\n :black_patent_malt=>{:name=>\"Black Patent Malt\", :origin=>\"US\", :type=>\"Grain\", :colour=>500, :must_mash=>false, :ppg=>1.025},\n :black_barley_stout=>{:name=>\"Black Barley (Stout)\", :origin=>\"US\", :type=>\"Grain\", :colour=>500, :must_mash=>false, :ppg=>1.025},\n :brown_malt=>{:name=>\"Brown Malt\", :origin=>\"United Kingdom\", :type=>\"Grain\", :colour=>65, :must_mash=>true, :ppg=>1.032},\n :brown_sugar_dark=>{:name=>\"Brown Sugar, Dark\", :origin=>\"US\", :type=>\"Sugar\", :colour=>50, :must_mash=>false, :ppg=>1.046},\n :brown_sugar_light=>{:name=>\"Brown Sugar, Light\", :origin=>\"US\", :type=>\"Sugar\", :colour=>8, :must_mash=>false, :ppg=>1.046},\n :brumalt=>{:name=>\"Brumalt\", :origin=>\"Germany\", :type=>\"Grain\", :colour=>23, :must_mash=>true, :ppg=>1.033},\n :candi_sugar_amber=>{:name=>\"Candi Sugar, Amber\", :origin=>\"Belgium\", :type=>\"Sugar\", :colour=>75, :must_mash=>false, :ppg=>1.036},\n :candi_sugar_clear=>{:name=>\"Candi Sugar, Clear\", :origin=>\"Belgium\", :type=>\"Sugar\", :colour=>1, :must_mash=>false, :ppg=>1.036},\n :candi_sugar_dark=>{:name=>\"Candi Sugar, Dark\", :origin=>\"Belgium\", :type=>\"Sugar\", :colour=>275, :must_mash=>false, :ppg=>1.036},\n :cane_sugar=>{:name=>\"Cane (Beet) Sugar\", :origin=>\"US\", :type=>\"Sugar\", :colour=>0, :must_mash=>false, :ppg=>1.046},\n :cara_pils_dextrine=>{:name=>\"Cara-Pils/Dextrine\", :origin=>\"US\", :type=>\"Grain\", :colour=>2, :must_mash=>false, :ppg=>1.033},\n :cara_amber=>{:name=>\"Caraamber\", :origin=>\"US\", :type=>\"Grain\", :colour=>30, :must_mash=>false, :ppg=>1.035},\n :carafoam=>{:name=>\"Carafoam\", :origin=>\"US\", :type=>\"Grain\", :colour=>2, :must_mash=>false, :ppg=>1.033},\n :crystal_malt_10L=>{:name=>\"Crystal Malt 10L\", :origin=>\"US\", :type=>\"Grain\", :colour=>10, :must_mash=>false, :ppg=>1.035},\n :crystal_malt_20L=>{:name=>\"Crystal Malt 20L\", :origin=>\"US\", :type=>\"Grain\", :colour=>20, :must_mash=>false, :ppg=>1.035},\n :crystal_malt_30L=>{:name=>\"Crystal Malt 30L\", :origin=>\"US\", :type=>\"Grain\", :colour=>30, :must_mash=>false, :ppg=>1.035},\n :crystal_malt_40L=>{:name=>\"Crystal Malt 40L\", :origin=>\"US\", :type=>\"Grain\", :colour=>40, :must_mash=>false, :ppg=>1.034},\n :crystal_malt_60L=>{:name=>\"Crystal Malt 60L\", :origin=>\"US\", :type=>\"Grain\", :colour=>60, :must_mash=>false, :ppg=>1.034},\n :crystal_malt_80L=>{:name=>\"Crystal Malt 80L\", :origin=>\"US\", :type=>\"Grain\", :colour=>80, :must_mash=>false, :ppg=>1.034},\n :crystal_malt_120L=>{:name=>\"Crystal Malt 120L\", :origin=>\"US\", :type=>\"Grain\", :colour=>120, :must_mash=>false, :ppg=>1.033},\n :caramunich_malt=>{:name=>\"Caramunich Malt\", :origin=>\"Belgium\", :type=>\"Grain\", :colour=>56, :must_mash=>false, :ppg=>1.033},\n :carared=>{:name=>\"Carared\", :origin=>\"US\", :type=>\"Grain\", :colour=>20, :must_mash=>false, :ppg=>1.035},\n :caravienne_malt=>{:name=>\"Caravienne Malt\", :origin=>\"Belgium\", :type=>\"Grain\", :colour=>22, :must_mash=>false, :ppg=>1.034},\n :chocolate_malt=>{:name=>\"Chocolate Malt\", :origin=>\"United Kingdom\", :type=>\"Grain\", :colour=>450, :must_mash=>false, :ppg=>1.034},\n :corn_sugar=>{:name=>\"Corn Sugar (Dextrose)\", :origin=>\"US\", :type=>\"Sugar\", :colour=>0, :must_mash=>false, :ppg=>1.046},\n :corn_syrup=>{:name=>\"Corn Syrup\", :origin=>\"US\", :type=>\"Sugar\", :colour=>1, :must_mash=>false, :ppg=>1.036},\n :corn_flaked=>{:name=>\"Corn, Flaked\", :origin=>\"US\", :type=>\"Grain\", :colour=>1, :must_mash=>true, :ppg=>1.037},\n :dark_dry_extract=>{:name=>\"Dark Dry Extract\", :origin=>\"US\", :type=>\"Dry Extract\", :colour=>18, :must_mash=>false, :ppg=>1.044},\n :dark_liquid_extract=>{:name=>\"Dark Liquid Extract\", :origin=>\"US\", :type=>\"Extract\", :colour=>18, :must_mash=>false, :ppg=>1.036},\n :dememera_sugar=>{:name=>\"Dememera Sugar\", :origin=>\"United Kingdom\", :type=>\"Sugar\", :colour=>2, :must_mash=>false, :ppg=>1.046},\n :extra_light_dry_extract=>{:name=>\"Extra Light Dry Extract\", :origin=>\"US\", :type=>\"Dry Extract\", :colour=>3, :must_mash=>false, :ppg=>1.044},\n :grits=>{:name=>\"Grits\", :origin=>\"US\", :type=>\"Adjunct\", :colour=>1, :must_mash=>false, :ppg=>1.037},\n :honey=>{:name=>\"Honey\", :origin=>\"US\", :type=>\"Extract\", :colour=>1, :must_mash=>false, :ppg=>1.035},\n :invert_sugar=>{:name=>\"Invert Sugar\", :origin=>\"United Kingdom\", :type=>\"Sugar\", :colour=>0, :must_mash=>false, :ppg=>1.046},\n :light_dry_extract=>{:name=>\"Light Dry Extract\", :origin=>\"US\", :type=>\"Dry Extract\", :colour=>8, :must_mash=>false, :ppg=>1.044},\n :maple_syrup=>{:name=>\"Maple Syrup\", :origin=>\"US\", :type=>\"Sugar\", :colour=>35, :must_mash=>false, :ppg=>1.030},\n :melanoiden_malt=>{:name=>\"Melanoiden Malt\", :origin=>\"Germany\", :type=>\"Grain\", :colour=>20, :must_mash=>true, :ppg=>1.037},\n :mild_malt=>{:name=>\"Mild Malt\", :origin=>\"United Kingdom\", :type=>\"Grain\", :colour=>4, :must_mash=>true, :ppg=>1.037},\n :lactose=>{:name=>\"Milk Sugar (Lactose)\", :origin=>\"US\", :type=>\"Sugar\", :colour=>0, :must_mash=>false, :ppg=>1.035},\n :molasses=>{:name=>\"Molasses\", :origin=>\"US\", :type=>\"Sugar\", :colour=>80, :must_mash=>false, :ppg=>1.036},\n :munich_malt=>{:name=>\"Munich Malt\", :origin=>\"Germany\", :type=>\"Grain\", :colour=>9, :must_mash=>true, :ppg=>1.037},\n :munich_malt_10L=>{:name=>\"Munich Malt 10L\", :origin=>\"US\", :type=>\"Grain\", :colour=>10, :must_mash=>true, :ppg=>1.035},\n :munich_malt_20L=>{:name=>\"Munich Malt 20L\", :origin=>\"US\", :type=>\"Grain\", :colour=>20, :must_mash=>true, :ppg=>1.035},\n :oats_flaked=>{:name=>\"Oats, Flaked\", :origin=>\"US\", :type=>\"Grain\", :colour=>1, :must_mash=>true, :ppg=>1.037},\n :oats_malted=>{:name=>\"Oats, Malted\", :origin=>\"US\", :type=>\"Grain\", :colour=>1, :must_mash=>true, :ppg=>1.037},\n :pale_liquid_extract=>{:name=>\"Pale Liquid Extract\", :origin=>\"US\", :type=>\"Extract\", :colour=>8, :must_mash=>false, :ppg=>1.036},\n :pale_malt_2=>{:name=>\"Pale Malt (2 Row)\", :origin=>\"US\", :type=>\"Grain\", :colour=>3, :must_mash=>true, :ppg=>1.037},\n :pale_malt_6=>{:name=>\"Pale Malt (6 Row)\", :origin=>\"US\", :type=>\"Grain\", :colour=>2, :must_mash=>true, :ppg=>1.035},\n :peat_smoked_malt=>{:name=>\"Peat Smoked Malt\", :origin=>\"United Kingdom\", :type=>\"Grain\", :colour=>3, :must_mash=>true, :ppg=>1.034},\n :pilsner_2=>{:name=>\"Pilsner (2 Row)\", :origin=>\"Germany\", :type=>\"Grain\", :colour=>2, :must_mash=>true, :ppg=>1.037},\n :pilsner_liquid_extract=>{:name=>\"Pilsner Liquid Extract\", :origin=>\"US\", :type=>\"Extract\", :colour=>4, :must_mash=>false, :ppg=>1.036},\n :rice_extract_syrup=>{:name=>\"Rice Extract Syrup\", :origin=>\"US\", :type=>\"Extract\", :colour=>7, :must_mash=>false, :ppg=>1.032},\n :rice_hulls=>{:name=>\"Rice Hulls\", :origin=>\"US\", :type=>\"Adjunct\", :colour=>0, :must_mash=>false, :ppg=>1.0},\n :rice_flaked=>{:name=>\"Rice, Flaked\", :origin=>\"US\", :type=>\"Grain\", :colour=>1, :must_mash=>true, :ppg=>1.032},\n :roasted_barley=>{:name=>\"Roasted Barley\", :origin=>\"US\", :type=>\"Grain\", :colour=>300, :must_mash=>false, :ppg=>1.025},\n :rye_malt=>{:name=>\"Rye Malt\", :origin=>\"US\", :type=>\"Grain\", :colour=>5, :must_mash=>true, :ppg=>1.029},\n :rye_flaked=>{:name=>\"Rye, Flaked\", :origin=>\"US\", :type=>\"Grain\", :colour=>2, :must_mash=>true, :ppg=>1.036},\n :smoked_malt=>{:name=>\"Smoked Malt\", :origin=>\"Germany\", :type=>\"Grain\", :colour=>9, :must_mash=>true, :ppg=>1.037},\n :special_b_malt=>{:name=>\"Special B Malt\", :origin=>\"Belgium\", :type=>\"Grain\", :colour=>180, :must_mash=>true, :ppg=>1.03},\n :special_roast=>{:name=>\"Special Roast\", :origin=>\"US\", :type=>\"Grain\", :colour=>50, :must_mash=>true, :ppg=>1.033},\n :toasted_malt=>{:name=>\"Toasted Malt\", :origin=>\"United Kingdom\", :type=>\"Grain\", :colour=>27, :must_mash=>true, :ppg=>1.033},\n :turbinado=>{:name=>\"Turbinado\", :origin=>\"United Kingdom\", :type=>\"Sugar\", :colour=>10, :must_mash=>false, :ppg=>1.044},\n :victory_malt=>{:name=>\"Victory Malt\", :origin=>\"US\", :type=>\"Grain\", :colour=>25, :must_mash=>true, :ppg=>1.034},\n :vienna_malt=>{:name=>\"Vienna Malt\", :origin=>\"Germany\", :type=>\"Grain\", :colour=>4, :must_mash=>true, :ppg=>1.036},\n :wheat_dry_extract=>{:name=>\"Wheat Dry Extract\", :origin=>\"US\", :type=>\"Dry Extract\", :colour=>8, :must_mash=>false, :ppg=>1.044},\n :wheat_liquid_extract=>{:name=>\"Wheat Liquid Extract\", :origin=>\"US\", :type=>\"Extract\", :colour=>8, :must_mash=>false, :ppg=>1.036},\n :wheat_malt=>{:name=>\"Wheat Malt\", :origin=>\"Belgium\", :type=>\"Grain\", :colour=>2, :must_mash=>true, :ppg=>1.037},\n :wheat_malt_dark=>{:name=>\"Wheat Malt, Dark\", :origin=>\"Germany\", :type=>\"Grain\", :colour=>9, :must_mash=>true, :ppg=>1.039},\n :wheat_flaked=>{:name=>\"Wheat, Flaked\", :origin=>\"US\", :type=>\"Grain\", :colour=>2, :must_mash=>true, :ppg=>1.035},\n :wheat_roasted=>{:name=>\"Wheat, Roasted\", :origin=>\"Germany\", :type=>\"Grain\", :colour=>425, :must_mash=>true, :ppg=>1.025},\n :wheat_torrified=>{:name=>\"Wheat, Torrified\", :origin=>\"US\", :type=>\"Grain\", :colour=>2, :must_mash=>true, :ppg=>1.036},\n :white_wheat_malt=>{:name=>\"White Wheat Malt\", :origin=>\"US\", :type=>\"Grain\", :colour=>2, :must_mash=>true, :ppg=>1.04}\n },\n hops: {\n :admiral=>{:name=>\"Admiral\", :origin=>\"UK\", :aa=>14.8, :type=>\"Bittering\"},\n :ahtanum=>{:name=>\"Ahtanum\", :origin=>\"US\", :aa=>6.0, :type=>\"Aroma\"},\n :amarillo_gold=>{:name=>\"Amarillo Gold\", :origin=>\"US\", :aa=>8.5, :type=>\"Aroma\"},\n :aquila=>{:name=>\"Aquila\", :origin=>\"US\", :aa=>6.5, :type=>\"Aroma\"},\n :banner=>{:name=>\"Banner\", :origin=>\"US\", :aa=>10.0, :type=>\"Bittering\"},\n :bramling_cross=>{:name=>\"Bramling Cross\", :origin=>\"UK\", :aa=>6.0, :type=>\"Aroma\"},\n :brewers_gold=>{:name=>\"Brewers Gold\", :origin=>\"UK\", :aa=>8.0, :type=>\"Bittering\"},\n :bullion=>{:name=>\"Bullion\", :origin=>\"UK\", :aa=>8.0, :type=>\"Bittering\"},\n :cascade=>{:name=>\"Cascade\", :origin=>\"US\", :aa=>5.5, :type=>\"Both\"},\n :centennial=>{:name=>\"Centennial\", :origin=>\"US\", :aa=>10.0, :type=>\"Bittering\"},\n :challenger=>{:name=>\"Challenger\", :origin=>\"UK\", :aa=>7.5, :type=>\"Aroma\"},\n :chinook=>{:name=>\"Chinook\", :origin=>\"US\", :aa=>13.0, :type=>\"Bittering\"},\n :cluster=>{:name=>\"Cluster\", :origin=>\"US\", :aa=>7.0, :type=>\"Bittering\"},\n :columbia=>{:name=>\"Columbia\", :origin=>\"UK\", :aa=>5.5, :type=>\"Bittering\"},\n :columbus_tomahawk=>{:name=>\"Columbus (Tomahawk)\", :origin=>\"US\", :aa=>14.0, :type=>\"Bittering\"},\n :comet=>{:name=>\"Comet\", :origin=>\"US\", :aa=>9.5, :type=>\"Bittering\"},\n :crystal=>{:name=>\"Crystal\", :origin=>\"US\", :aa=>3.5, :type=>\"Aroma\"},\n :eroica=>{:name=>\"Eroica\", :origin=>\"US\", :aa=>13.0, :type=>\"Bittering\"},\n :first_gold=>{:name=>\"First Gold\", :origin=>\"UK\", :aa=>7.5, :type=>\"Both\"},\n :fuggles=>{:name=>\"Fuggles\", :origin=>\"UK\", :aa=>4.5, :type=>\"Aroma\"},\n :galena=>{:name=>\"Galena\", :origin=>\"US\", :aa=>13.0, :type=>\"Bittering\"},\n :glacier=>{:name=>\"Glacier\", :origin=>\"US\", :aa=>5.6, :type=>\"Aroma\"},\n :goldings_bc=>{:name=>\"Goldings, Brit. Col.\", :origin=>\"Canada\", :aa=>5.0, :type=>\"Aroma\"},\n :goldings_ek=>{:name=>\"Goldings, EK\", :origin=>\"UK\", :aa=>5.0, :type=>\"Aroma\"},\n :green_bullet=>{:name=>\"Green Bullet\", :origin=>\"New Zealand\", :aa=>13.5, :type=>\"Bittering\"},\n :hallertauer=>{:name=>\"Hallertauer\", :origin=>\"Germany\", :aa=>4.8, :type=>\"Aroma\"},\n :hallertauer_hersbrucker=>{:name=>\"Hallertauer, Hersbrucker\", :origin=>\"Germany\", :aa=>4.0, :type=>\"Aroma\"},\n :hallertauer_mittelfrueh=>{:name=>\"Hallertauer, Mittelfrueh\", :origin=>\"Germany\", :aa=>4.0, :type=>\"Aroma\"},\n :hallertauer_nz=>{:name=>\"Hallertauer, New Zealand\", :origin=>\"New Zealand\", :aa=>8.5, :type=>\"Both\"},\n :herald=>{:name=>\"Herald\", :origin=>\"UK\", :aa=>12.0, :type=>\"Bittering\"},\n :horizon=>{:name=>\"Horizon\", :origin=>\"US\", :aa=>12.0, :type=>\"Bittering\"},\n :liberty=>{:name=>\"Liberty\", :origin=>\"US\", :aa=>4.3, :type=>\"Aroma\"},\n :lublin=>{:name=>\"Lublin\", :origin=>\"Poland\", :aa=>5.0, :type=>\"Bittering\"},\n :magnum=>{:name=>\"Magnum\", :origin=>\"Germany\", :aa=>14.0, :type=>\"Bittering\"},\n :mt_hood=>{:name=>\"Mt. Hood\", :origin=>\"US\", :aa=>6.0, :type=>\"Aroma\"},\n :northdown=>{:name=>\"Northdown\", :origin=>\"UK\", :aa=>8.5, :type=>\"Both\"},\n :northern_brewer=>{:name=>\"Northern Brewer\", :origin=>\"Germany\", :aa=>8.5, :type=>\"Both\"},\n :nugget=>{:name=>\"Nugget\", :origin=>\"US\", :aa=>13.0, :type=>\"Bittering\"},\n :orion=>{:name=>\"Orion\", :origin=>\"Germany\", :aa=>7.3, :type=>\"Both\"},\n :pacific_gem=>{:name=>\"Pacific Gem\", :origin=>\"New Zealand\", :aa=>15.0, :type=>\"Bittering\"},\n :pearle=>{:name=>\"Pearle\", :origin=>\"Germany\", :aa=>8.0, :type=>\"Bittering\"},\n :phoenix=>{:name=>\"Phoenix\", :origin=>\"UK\", :aa=>8.0, :type=>\"Bittering\"},\n :pilgrim=>{:name=>\"Pilgrim\", :origin=>\"UK\", :aa=>11.5, :type=>\"Bittering\"},\n :pioneer=>{:name=>\"Pioneer\", :origin=>\"UK\", :aa=>9.0, :type=>\"Both\"},\n :pride_of_ringwood=>{:name=>\"Pride of Ringwood\", :origin=>\"Australia\", :aa=>9.0, :type=>\"Bittering\"},\n :progress=>{:name=>\"Progress\", :origin=>\"UK\", :aa=>6.3, :type=>\"Aroma\"},\n :saaz=>{:name=>\"Saaz\", :origin=>\"Czech Rep.\", :aa=>4.0, :type=>\"Aroma\"},\n :santiam=>{:name=>\"Santiam\", :origin=>\"US\", :aa=>6.0, :type=>\"Aroma\"},\n :select_spalt=>{:name=>\"Select Spalt\", :origin=>\"Germany\", :aa=>4.8, :type=>\"Aroma\"},\n :southern_cross=>{:name=>\"Southern Cross\", :origin=>\"New Zealand\", :aa=>13.0, :type=>\"Both\"},\n :spalter=>{:name=>\"Spalter\", :origin=>\"Germany\", :aa=>4.5, :type=>\"Aroma\"},\n :sterling=>{:name=>\"Sterling\", :origin=>\"US\", :aa=>7.5, :type=>\"Both\"},\n :sticklebract=>{:name=>\"Sticklebract\", :origin=>\"New Zealand\", :aa=>13.5, :type=>\"Both\"},\n :strisselspalt=>{:name=>\"Strisselspalt\", :origin=>\"France\", :aa=>4.0, :type=>\"Aroma\"},\n :styrian_goldings=>{:name=>\"Styrian Goldings\", :origin=>\"Slovenia\", :aa=>5.4, :type=>\"Aroma\"},\n :sun=>{:name=>\"Sun\", :origin=>\"US\", :aa=>14.0, :type=>\"Bittering\"},\n :super_alpha=>{:name=>\"Super Alpha\", :origin=>\"New Zealand\", :aa=>13.0, :type=>\"Bittering\"},\n :target=>{:name=>\"Target\", :origin=>\"UK\", :aa=>11.0, :type=>\"Bittering\"},\n :tettnang=>{:name=>\"Tettnang\", :origin=>\"Germany\", :aa=>4.5, :type=>\"Aroma\"},\n :tradition=>{:name=>\"Tradition\", :origin=>\"Germany\", :aa=>6.0, :type=>\"Bittering\"},\n :ultra=>{:name=>\"Ultra\", :origin=>\"US\", :aa=>3.0, :type=>\"Aroma\"},\n :vanguard=>{:name=>\"Vanguard\", :origin=>\"US\", :aa=>5.5, :type=>\"Aroma\"},\n :warrior=>{:name=>\"Warrior\", :origin=>\"US\", :aa=>15.0, :type=>\"Both\"},\n :whitbread_gv=>{:name=>\"Whitbread Golding Var\", :origin=>\"UK\", :aa=>6.0, :type=>\"Aroma\"},\n :willamette=>{:name=>\"Willamette\", :origin=>\"US\", :aa=>5.5, :type=>\"Aroma\"},\n :zeus=>{:name=>\"Zeus\", :origin=>\"US\", :aa=>14.0, :type=>\"Bittering\"}\n },\n yeasts: {\n :coopers_ale=>{:name=>\"Coopers Ale\", :lab=>\"Coopers\", :number=>\"\", :type=>\"Ale\", :form=>\"Dry\", :flocculation=>\"Medium\"},\n :doric_ale=>{:name=>\"Doric Ale\", :lab=>\"Doric\", :number=>\"\", :type=>\"Ale\", :form=>\"Dry\", :flocculation=>\"Medium\"},\n :edme_ale=>{:name=>\"Edme Ale Yeast\", :lab=>\"Edme\", :number=>\"\", :type=>\"Ale\", :form=>\"Dry\", :flocculation=>\"Medium\"},\n :danstar_nottingham_ale=>{:name=>\"Nottingham\", :lab=>\"Danstar\", :number=>\"\", :type=>\"Ale\", :form=>\"Dry\", :flocculation=>\"High\"},\n :munton_fison_ale=>{:name=>\"Munton Fison Ale\", :lab=>\"Munton-Fison\", :number=>\"\", :type=>\"Ale\", :form=>\"Dry\", :flocculation=>\"Medium\"},\n :lallemand_windsor_ale=>{:name=>\"Windsor Yeast\", :lab=>\"Lallemand\", :number=>\"\", :type=>\"Ale\", :form=>\"Dry\", :flocculation=>\"Very High\"},\n :red_star_ale=>{:name=>\"Red Star Ale\", :lab=>\"Red Star\", :number=>\"\", :type=>\"Ale\", :form=>\"Dry\", :flocculation=>\"Medium\"},\n :glenbrew_special_ale=>{:name=>\"Special Ale\", :lab=>\"Glenbrew\", :number=>\"\", :type=>\"Ale\", :form=>\"Dry\", :flocculation=>\"Medium\"},\n :wyeast_labs_1007=>{:name=>\"German Ale\", :lab=>\"Wyeast Labs\", :number=>\"1007\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :wyeast_labs_1010=>{:name=>\"American Wheat Ale\", :lab=>\"Wyeast Labs\", :number=>\"1010\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :wyeast_labs_1026=>{:name=>\"British Cask Ale\", :lab=>\"Wyeast Labs\", :number=>\"1026\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_1028=>{:name=>\"London Ale\", :lab=>\"Wyeast Labs\", :number=>\"1028\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_1056=>{:name=>\"American Ale\", :lab=>\"Wyeast Labs\", :number=>\"1056\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_1084=>{:name=>\"Irish Ale\", :lab=>\"Wyeast Labs\", :number=>\"1084\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_1087=>{:name=>\"Wyeast Ale Blend\", :lab=>\"Wyeast Labs\", :number=>\"1087\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_1098=>{:name=>\"British Ale\", :lab=>\"Wyeast Labs\", :number=>\"1098\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_1099=>{:name=>\"Whitbread Ale\", :lab=>\"Wyeast Labs\", :number=>\"1099\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_1187=>{:name=>\"Ringwood Ale\", :lab=>\"Wyeast Labs\", :number=>\"1187\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_1214=>{:name=>\"Belgian Ale\", :lab=>\"Wyeast Labs\", :number=>\"1214\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_1272=>{:name=>\"GF All American Ale\", :lab=>\"Wyeast Labs\", :number=>\"1272\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_1275=>{:name=>\"Thames Valley Ale\", :lab=>\"Wyeast Labs\", :number=>\"1275\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_1318=>{:name=>\"London Ale III\", :lab=>\"Wyeast Labs\", :number=>\"1318\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_1332=>{:name=>\"Northwest Ale\", :lab=>\"Wyeast Labs\", :number=>\"1332\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_1335=>{:name=>\"British Ale II\", :lab=>\"Wyeast Labs\", :number=>\"1335\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_1338=>{:name=>\"European Ale\", :lab=>\"Wyeast Labs\", :number=>\"1338\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_1388=>{:name=>\"Belgian Strong Ale\", :lab=>\"Wyeast Labs\", :number=>\"1388\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :wyeast_labs_1728=>{:name=>\"Scottish Ale\", :lab=>\"Wyeast Labs\", :number=>\"1728\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_1762=>{:name=>\"Belgian Abbey II\", :lab=>\"Wyeast Labs\", :number=>\"1762\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_1968=>{:name=>\"London ESB Ale\", :lab=>\"Wyeast Labs\", :number=>\"1968\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_2000=>{:name=>\"Budvar Lager\", :lab=>\"Wyeast Labs\", :number=>\"2000\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_2001=>{:name=>\"Urquell Lager\", :lab=>\"Wyeast Labs\", :number=>\"2001\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_2007=>{:name=>\"Pilsen Lager\", :lab=>\"Wyeast Labs\", :number=>\"2007\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_2035=>{:name=>\"American Lager\", :lab=>\"Wyeast Labs\", :number=>\"2035\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_2042=>{:name=>\"Danish Lager\", :lab=>\"Wyeast Labs\", :number=>\"2042\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_2112=>{:name=>\"California Lager\", :lab=>\"Wyeast Labs\", :number=>\"2112\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_2124=>{:name=>\"Bohemian Lager\", :lab=>\"Wyeast Labs\", :number=>\"2124\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_2178=>{:name=>\"Wyeast Lager Blend\", :lab=>\"Wyeast Labs\", :number=>\"2178\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_2206=>{:name=>\"Bavarian Lager\", :lab=>\"Wyeast Labs\", :number=>\"2206\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_2247=>{:name=>\"European Lager II\", :lab=>\"Wyeast Labs\", :number=>\"2247\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :wyeast_labs_2272=>{:name=>\"North American Lager\", :lab=>\"Wyeast Labs\", :number=>\"2272\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_2278=>{:name=>\"Czech Pilsner Lager\", :lab=>\"Wyeast Labs\", :number=>\"2278\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_2308=>{:name=>\"Munich Lager\", :lab=>\"Wyeast Labs\", :number=>\"2308\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_2565=>{:name=>\"Kolsch Yeast\", :lab=>\"Wyeast Labs\", :number=>\"2565\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :wyeast_labs_3056=>{:name=>\"Bavarian Wheat Yeast\", :lab=>\"Wyeast Labs\", :number=>\"3056\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_3068=>{:name=>\"Weihenstephan Weizen\", :lab=>\"Wyeast Labs\", :number=>\"3068\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :wyeast_labs_3112=>{:name=>\"Brettanomyces bruxellensis\", :lab=>\"Wyeast Labs\", :number=>\"3112\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_3278=>{:name=>\"Belgian Lambic Blend\", :lab=>\"Wyeast Labs\", :number=>\"3278\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :wyeast_labs_3333=>{:name=>\"German Wheat\", :lab=>\"Wyeast Labs\", :number=>\"3333\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_3463=>{:name=>\"Forbidden Fruit\", :lab=>\"Wyeast Labs\", :number=>\"3463\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :wyeast_labs_3522=>{:name=>\"Belgian Ardennes\", :lab=>\"Wyeast Labs\", :number=>\"3522\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :wyeast_labs_3638=>{:name=>\"Bavarian Wheat\", :lab=>\"Wyeast Labs\", :number=>\"3638\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :wyeast_labs_3724=>{:name=>\"Belgian Saison\", :lab=>\"Wyeast Labs\", :number=>\"3724\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :wyeast_labs_3763=>{:name=>\"Roselare Belgian Blend\", :lab=>\"Wyeast Labs\", :number=>\"3763\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_3787=>{:name=>\"Trappist High Gravity\", :lab=>\"Wyeast Labs\", :number=>\"3787\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_3942=>{:name=>\"Belgian Wheat Yeast\", :lab=>\"Wyeast Labs\", :number=>\"3942\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_3944=>{:name=>\"Belgian Witbier\", :lab=>\"Wyeast Labs\", :number=>\"3944\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_4335=>{:name=>\"Lactobacillus Delbrueckii\", :lab=>\"Wyeast Labs\", :number=>\"4335\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :wyeast_labs_4733=>{:name=>\"Pediococcus Cerevisiae\", :lab=>\"Wyeast Labs\", :number=>\"4733\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0010=>{:name=>\"American Microbrewery Ale #1\", :lab=>\"Brewtek\", :number=>\"CL-0010\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0020=>{:name=>\"American Microbrewery Ale #2\", :lab=>\"Brewtek\", :number=>\"CL-0020\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0060=>{:name=>\"Noth-Eastern Micro Ale\", :lab=>\"Brewtek\", :number=>\"CL-0060\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0110=>{:name=>\"British Microbrewery Ale\", :lab=>\"Brewtek\", :number=>\"CL-0110\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0120=>{:name=>\"British Pale Ale #1\", :lab=>\"Brewtek\", :number=>\"CL-0120\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0130=>{:name=>\"British Pale Ale #2\", :lab=>\"Brewtek\", :number=>\"CL-0130\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0150=>{:name=>\"British Real Ale\", :lab=>\"Brewtek\", :number=>\"CL-0150\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0160=>{:name=>\"British Draft Ale\", :lab=>\"Brewtek\", :number=>\"CL-0160\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0170=>{:name=>\"Classic British Ale\", :lab=>\"Brewtek\", :number=>\"CL-0170\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0240=>{:name=>\"Irish Dry Stout\", :lab=>\"Brewtek\", :number=>\"CL-0240\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0260=>{:name=>\"Canadian Ale\", :lab=>\"Brewtek\", :number=>\"CL-0260\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0300=>{:name=>\"Belgian Ale #1\", :lab=>\"Brewtek\", :number=>\"CL-0300\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0320=>{:name=>\"Belgian Ale #2\", :lab=>\"Brewtek\", :number=>\"CL-0320\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :brewtek_cl_0340=>{:name=>\"Belgian Ale #3\", :lab=>\"Brewtek\", :number=>\"CL-0340\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0380=>{:name=>\"Saison\", :lab=>\"Brewtek\", :number=>\"CL-0380\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0400=>{:name=>\"Old German Ale\", :lab=>\"Brewtek\", :number=>\"CL-0400\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0600=>{:name=>\"Original Pilsner\", :lab=>\"Brewtek\", :number=>\"CL-0600\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0620=>{:name=>\"American Megabrewery\", :lab=>\"Brewtek\", :number=>\"CL-0620\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0630=>{:name=>\"American Microbrewery Lager\", :lab=>\"Brewtek\", :number=>\"CL-0630\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0650=>{:name=>\"Old Bavarian Lager\", :lab=>\"Brewtek\", :number=>\"CL-0650\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0660=>{:name=>\"Northern German Lager\", :lab=>\"Brewtek\", :number=>\"CL-0660\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0680=>{:name=>\"East European Lager\", :lab=>\"Brewtek\", :number=>\"CL-0680\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0690=>{:name=>\"California Esteem\", :lab=>\"Brewtek\", :number=>\"CL-0690\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0900=>{:name=>\"Belgian Wheat\", :lab=>\"Brewtek\", :number=>\"CL-0900\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0920=>{:name=>\"German Wheat\", :lab=>\"Brewtek\", :number=>\"CL-0920\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0930=>{:name=>\"German Weiss\", :lab=>\"Brewtek\", :number=>\"CL-0930\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_0980=>{:name=>\"American White Ale\", :lab=>\"Brewtek\", :number=>\"CL-0980\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :brewtek_cl_5200=>{:name=>\"Brettanomyces lambicus\", :lab=>\"Brewtek\", :number=>\"CL-5200\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :brewtek_cl_5600=>{:name=>\"Pediococcus damnosus\", :lab=>\"Brewtek\", :number=>\"CL-5600\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :lallemand_lalvin_71b_1122=>{:name=>\"Lalvin 71B-1122\", :lab=>\"Lallemand - Lalvin\", :number=>\"71B-1122\", :type=>\"Wine\", :form=>\"Dry\", :flocculation=>\"High\"},\n :lallemand_lalvin_d47=>{:name=>\"Lalvin D-47\", :lab=>\"Lallemand - Lalvin\", :number=>\"D-47\", :type=>\"Wine\", :form=>\"Dry\", :flocculation=>\"High\"},\n :lallemand_lalvin_ec1118=>{:name=>\"Lalvin EC-1118\", :lab=>\"Lallemand - Lalvin\", :number=>\"EC-1118\", :type=>\"Wine\", :form=>\"Dry\", :flocculation=>\"High\"},\n :lallemand_lalvin_k1v1116=>{:name=>\"Lalvin - K1V-1116\", :lab=>\"Lallemand - Lalvin\", :number=>\"K1V-1116\", :type=>\"Wine\", :form=>\"Dry\", :flocculation=>\"Medium\"},\n :lallemand_lalvin_rc212=>{:name=>\"Lalvin RC 212 (Bourgovin)\", :lab=>\"Lallemand - Lalvin\", :number=>\"RC 212\", :type=>\"Wine\", :form=>\"Dry\", :flocculation=>\"Medium\"},\n :dcl_yeast_k97=>{:name=>\"SafAle German Ale\", :lab=>\"DCL Yeast\", :number=>\"K-97\", :type=>\"Ale\", :form=>\"Dry\", :flocculation=>\"Medium\"},\n :dcl_yeast_s04=>{:name=>\"SafAle English Ale\", :lab=>\"DCL Yeast\", :number=>\"S-04\", :type=>\"Ale\", :form=>\"Dry\", :flocculation=>\"Medium\"},\n :dcl_yeast_s189=>{:name=>\"SafLager German Lager\", :lab=>\"DCL Yeast\", :number=>\"S-189\", :type=>\"Lager\", :form=>\"Dry\", :flocculation=>\"High\"},\n :dcl_yeast_s23=>{:name=>\"SafLager West European Lager\", :lab=>\"DCL Yeast\", :number=>\"S-23\", :type=>\"Lager\", :form=>\"Dry\", :flocculation=>\"High\"},\n :dcl_yeast_s33=>{:name=>\"SafBrew Ale\", :lab=>\"DCL Yeast\", :number=>\"S-33\", :type=>\"Ale\", :form=>\"Dry\", :flocculation=>\"Medium\"},\n :dcl_yeast_t58=>{:name=>\"SafBrew Specialty Ale\", :lab=>\"DCL Yeast\", :number=>\"T-58\", :type=>\"Ale\", :form=>\"Dry\", :flocculation=>\"Medium\"},\n :white_labs_wlp001=>{:name=>\"California Ale\", :lab=>\"White Labs\", :number=>\"WLP001\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :white_labs_wlp002=>{:name=>\"English Ale\", :lab=>\"White Labs\", :number=>\"WLP002\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Very High\"},\n :white_labs_wlp003=>{:name=>\"German Ale II\", :lab=>\"White Labs\", :number=>\"WLP003\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp004=>{:name=>\"Irish Ale\", :lab=>\"White Labs\", :number=>\"WLP004\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp005=>{:name=>\"British Ale\", :lab=>\"White Labs\", :number=>\"WLP005\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :white_labs_wlp006=>{:name=>\"Bedford British Ale\", :lab=>\"White Labs\", :number=>\"WLP006\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :white_labs_wlp007=>{:name=>\"Dry English Ale\", :lab=>\"White Labs\", :number=>\"WLP007\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :white_labs_wlp008=>{:name=>\"East Coast Ale\", :lab=>\"White Labs\", :number=>\"WLP008\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :white_labs_wlp009=>{:name=>\"Australian Ale Yeast\", :lab=>\"White Labs\", :number=>\"WLP009\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :white_labs_wlp011=>{:name=>\"European Ale\", :lab=>\"White Labs\", :number=>\"WLP011\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp013=>{:name=>\"London Ale\", :lab=>\"White Labs\", :number=>\"WLP013\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp022=>{:name=>\"Essex Ale Yeast\", :lab=>\"White Labs\", :number=>\"WLP022\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp023=>{:name=>\"Burton Ale\", :lab=>\"White Labs\", :number=>\"WLP023\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp025=>{:name=>\"Southwold Ale\", :lab=>\"White Labs\", :number=>\"WLP025\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp026=>{:name=>\"Premium Bitter Ale\", :lab=>\"White Labs\", :number=>\"WLP026\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp028=>{:name=>\"Edinburgh Ale\", :lab=>\"White Labs\", :number=>\"WLP028\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp029=>{:name=>\"German Ale/Kolsch\", :lab=>\"White Labs\", :number=>\"WLP029\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp033=>{:name=>\"Klassic Ale Yeast\", :lab=>\"White Labs\", :number=>\"WLP033\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp036=>{:name=>\"Dusseldorf Alt Yeast\", :lab=>\"White Labs\", :number=>\"WLP036\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp039=>{:name=>\"Nottingham Ale Yeast\", :lab=>\"White Labs\", :number=>\"WLP039\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp041=>{:name=>\"Pacific Ale\", :lab=>\"White Labs\", :number=>\"WLP041\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :white_labs_wlp051=>{:name=>\"California Ale V\", :lab=>\"White Labs\", :number=>\"WLP051\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :white_labs_wlp099=>{:name=>\"Super High Gravity Ale\", :lab=>\"White Labs\", :number=>\"WLP099\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :white_labs_wlp300=>{:name=>\"Hefeweizen Ale\", :lab=>\"White Labs\", :number=>\"WLP300\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :white_labs_wlp320=>{:name=>\"American Hefeweizen Ale\", :lab=>\"White Labs\", :number=>\"WLP320\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :white_labs_wlp351=>{:name=>\"Bavarian Weizen Yeast\", :lab=>\"White Labs\", :number=>\"WLP351\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :white_labs_wlp380=>{:name=>\"Hefeweizen IV Ale\", :lab=>\"White Labs\", :number=>\"WLP380\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :white_labs_wlp400=>{:name=>\"Belgian Wit Ale\", :lab=>\"White Labs\", :number=>\"WLP400\", :type=>\"Wheat\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :white_labs_wlp410=>{:name=>\"Belgian Wit II\", :lab=>\"White Labs\", :number=>\"WLP410\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp500=>{:name=>\"Trappist Ale\", :lab=>\"White Labs\", :number=>\"WLP500\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp510=>{:name=>\"Bastogne Belgian Ale\", :lab=>\"White Labs\", :number=>\"WLP510\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp530=>{:name=>\"Abbey Ale\", :lab=>\"White Labs\", :number=>\"WLP530\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp550=>{:name=>\"Belgian Ale\", :lab=>\"White Labs\", :number=>\"WLP550\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp565=>{:name=>\"Belgian Saison I Ale\", :lab=>\"White Labs\", :number=>\"WLP565\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp570=>{:name=>\"Belgian Golden Ale\", :lab=>\"White Labs\", :number=>\"WLP570\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :white_labs_wlp575=>{:name=>\"Belgian Style Ale Yeast Blend\", :lab=>\"White Labs\", :number=>\"WLP575\", :type=>\"Ale\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp715=>{:name=>\"Champagne Yeast\", :lab=>\"White Labs\", :number=>\"WLP715\", :type=>\"Champagne\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :white_labs_wlp720=>{:name=>\"Sweet Mead/Wine\", :lab=>\"White Labs\", :number=>\"WLP720\", :type=>\"Wine\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :white_labs_wlp727=>{:name=>\"Sweet Mead/Wine\", :lab=>\"White Labs\", :number=>\"WLP727\", :type=>\"Wine\", :form=>\"Liquid\", :flocculation=>\"Low\"},\n :white_labs_wlp775=>{:name=>\"English Cider Yeast\", :lab=>\"White Labs\", :number=>\"WLP775\", :type=>\"Wine\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp800=>{:name=>\"Pilsner Lager\", :lab=>\"White Labs\", :number=>\"WLP800\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :white_labs_wlp802=>{:name=>\"Czech Budejovice Lager\", :lab=>\"White Labs\", :number=>\"WLP802\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp810=>{:name=>\"San Francisco Lager\", :lab=>\"White Labs\", :number=>\"WLP810\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :white_labs_wlp820=>{:name=>\"Octoberfest/Marzen Lager\", :lab=>\"White Labs\", :number=>\"WLP820\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp830=>{:name=>\"German Lager\", :lab=>\"White Labs\", :number=>\"WLP830\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp833=>{:name=>\"German Bock Lager\", :lab=>\"White Labs\", :number=>\"WLP833\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp838=>{:name=>\"Southern German Lager\", :lab=>\"White Labs\", :number=>\"WLP838\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"High\"},\n :white_labs_wlp840=>{:name=>\"American Lager\", :lab=>\"White Labs\", :number=>\"WLP840\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp862=>{:name=>\"Cry Havoc\", :lab=>\"White Labs\", :number=>\"WLP862\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp885=>{:name=>\"Zurich Lager\", :lab=>\"White Labs\", :number=>\"WLP885\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp920=>{:name=>\"Old Bavarian Lager\", :lab=>\"White Labs\", :number=>\"WLP920\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"},\n :white_labs_wlp940=>{:name=>\"Mexican Lager\", :lab=>\"White Labs\", :number=>\"WLP940\", :type=>\"Lager\", :form=>\"Liquid\", :flocculation=>\"Medium\"}\n }\n }\n end", "def meta_tags_to_array\n self.ingredients.gsub(/(\\[\\\"|\\\"\\])/, '').split('\" \"').split('\", \"')\n end", "def ingredient_definitions\n definition.fetch(:ingredients, [])\n end", "def parse_ingredients(data)\n ingredients = []\n data.gsub!(/(?i)(ingredients)/, '') # Remove \"Ingredients\" ignore case\n if data.include? ','\n data.split(/[,.()]/).each do |s|\n candidate = s.gsub(/\\W+/, ' ').strip\n ingredients.push(candidate) unless candidate.empty?\n end\n else\n # Not yet implemented\n nil\n end\n ingredients\n end", "def ingredients\n (self.recipe_ingredients + self.steps.select{ |i| i.is_recipe_id }.map{|i|\n Recipe.includes(:recipe_ingredients).find(i.is_recipe_id).ingredients\n }.compact).flatten\n end", "def ingredient_names\n self.ingredients.map do |ing|\n ing.name\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /stock_medicas POST /stock_medicas.json
def create @stock_medica = StockMedica.new(stock_medica_params) respond_to do |format| if @stock_medica.save format.html { redirect_to @stock_medica, notice: 'Fue Crado stock' } format.json { render :show, status: :created, location: @stock_medica } else format.html { render :new } format.json { render json: @stock_medica.errors, status: :unprocessable_entity } end end end
[ "def create\n @stock = Stock.create!(stock_params)\n json_response(@stock, :created)\n\n end", "def create\n @stock = Stock.new(stock_params)\n\n if @stock.save\n render json: @stock, status: :created, location: @stock\n else\n render json: @stock.errors, status: :unprocessable_entity\n end\n end", "def create\n @sp500_stock = Sp500Stock.new(params[:sp500_stock])\n\n respond_to do |format|\n if @sp500_stock.save\n format.html { redirect_to @sp500_stock, notice: 'Sp500 stock was successfully created.' }\n format.json { render json: @sp500_stock, status: :created, location: @sp500_stock }\n else\n format.html { render action: \"new\" }\n format.json { render json: @sp500_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @medicament = Medicament.new(medicament_params)\n\n if @medicament.save\n render json: @medicament\n else\n render json: @medicament.errors, status: :unprocessable_entity\n end\n end", "def create\n @medic = Medic.new(params[:medic])\n\n respond_to do |format|\n if @medic.save\n format.html { redirect_to @medic, notice: 'Medic was successfully created.' }\n format.json { render json: @medic, status: :created, location: @medic }\n else\n format.html { render action: \"new\" }\n format.json { render json: @medic.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stock = Stock.new(params[:stock])\n\n respond_to do |format|\n if @stock.save\n format.html { redirect_to @stock, notice: 'Stock was successfully created.' }\n format.json { render json: @stock, status: :created, location: @stock }\n else\n format.html { render action: \"new\" }\n format.json { render json: @stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @medicamento = Medicamento.new(params[:medicamento])\n\n respond_to do |format|\n if @medicamento.save\n format.html { redirect_to @medicamento, notice: 'Medicamento was successfully created.' }\n format.json { render json: @medicamento, status: :created, location: @medicamento }\n else\n format.html { render action: \"new\" }\n format.json { render json: @medicamento.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @medico = Medico.new(params[:medico])\n\n respond_to do |format|\n if @medico.save\n format.html { redirect_to @medico, :notice => 'Medico was successfully created.' }\n format.json { render :json => @medico, :status => :created, :location => @medico }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @medico.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @model_stock = ModelStock.new(model_stock_params)\n\n respond_to do |format|\n if @model_stock.save\n format.html { redirect_to @model_stock, notice: t('common.message.created_success')}\n format.json { render :show, status: :created, location: @model_stock }\n else\n format.html { render :new }\n format.json { render json: @model_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @movie_stock = MovieStock.new(movie_stock_params)\n\n respond_to do |format|\n if @movie_stock.save\n\n format.html { redirect_to [:admin, @movie_stock], notice: \"Movie Stock was successfully created.\" }\n format.json { render :show, status: :created, location: [:admin, @movie_stock] }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: [:admin, @movie_stock].errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stock = Stock.new(params[:stock])\n\n respond_to do |format|\n if @stock.save\n format.html { redirect_to stocks_url, notice: 'Stock was successfully created.' }\n format.json { render json: @stock, status: :created, location: @stock }\n else\n format.html { render action: \"new\" }\n format.json { render json: @stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @detalle_movimiento_stock = DetalleMovimientoStock.new(params[:detalle_movimiento_stock])\n\n respond_to do |format|\n if @detalle_movimiento_stock.save\n format.html { redirect_to @detalle_movimiento_stock, notice: 'Detalle movimiento stock was successfully created.' }\n format.json { render json: @detalle_movimiento_stock, status: :created, location: @detalle_movimiento_stock }\n else\n format.html { render action: \"new\" }\n format.json { render json: @detalle_movimiento_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @mata_matum = MataMatum.new(mata_matum_params)\n\n respond_to do |format|\n if @mata_matum.save\n format.html { redirect_to @mata_matum, notice: 'Mata matum was successfully created.' }\n format.json { render :show, status: :created, location: @mata_matum }\n else\n format.html { render :new }\n format.json { render json: @mata_matum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stock_master = StockMaster.new(stock_master_params)\n\n respond_to do |format|\n if @stock_master.save\n format.html { redirect_to @stock_master, notice: 'Stock master was successfully created.' }\n format.json { render :show, status: :created, location: @stock_master }\n else\n format.html { render :new }\n format.json { render json: @stock_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @stock_medica.update(stock_medica_params)\n format.html { redirect_to @stock_medica, notice: 'Stock medica was successfully updated.' }\n format.json { render :show, status: :ok, location: @stock_medica }\n else\n format.html { render :edit }\n format.json { render json: @stock_medica.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @various_stock = VariousStock.new(various_stock_params)\n\n respond_to do |format|\n if @various_stock.save\n format.html { redirect_to @various_stock, notice: 'Various stock was successfully created.' }\n format.json { render :show, status: :created, location: @various_stock }\n else\n format.html { render :new }\n format.json { render json: @various_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @total_stock = TotalStock.new(params[:total_stock])\n\n respond_to do |format|\n if @total_stock.save\n format.html { redirect_to @total_stock, notice: 'Total stock was successfully created.' }\n format.json { render json: @total_stock, status: :created, location: @total_stock }\n else\n format.html { render action: \"new\" }\n format.json { render json: @total_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @vending_machine_stock = VendingMachineStock.new(vending_machine_stock_params)\n\n respond_to do |format|\n if @vending_machine_stock.save\n format.html { redirect_to @vending_machine_stock, notice: 'Vending machine stock was successfully created.' }\n format.json { render :show, status: :created, location: @vending_machine_stock }\n else\n format.html { render :new }\n format.json { render json: @vending_machine_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @medalha = Medalha.new(medalha_params)\n\n respond_to do |format|\n if @medalha.save\n format.html { redirect_to @medalha, notice: 'Medalha was successfully created.' }\n format.json { render :show, status: :created, location: @medalha }\n else\n format.html { render :new }\n format.json { render json: @medalha.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /stock_medicas/1 PATCH/PUT /stock_medicas/1.json
def update respond_to do |format| if @stock_medica.update(stock_medica_params) format.html { redirect_to @stock_medica, notice: 'Stock medica was successfully updated.' } format.json { render :show, status: :ok, location: @stock_medica } else format.html { render :edit } format.json { render json: @stock_medica.errors, status: :unprocessable_entity } end end end
[ "def update\n respond_to do |format|\n if @mouvement_stock.update(mouvement_stock_params)\n format.html { redirect_to @mouvement_stock, notice: 'Mouvement stock was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @mouvement_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @stock = Stock.find(params[:id])\n\n if @stock.update(stock_params)\n head :no_content\n else\n render json: @stock.errors, status: :unprocessable_entity\n end\n end", "def update\n render json: @stock.errors unless @stock.update(stock_params)\n end", "def update\n @stock = Stock.find(params[:id])\n\n respond_to do |format|\n if @stock.update_attributes(params[:stock])\n format.html { redirect_to @stock, notice: 'Stock was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @stock = Stock.find(params[:id])\n\n respond_to do |format|\n if @stock.update_attributes(params[:stock])\n format.html { redirect_to stocks_url }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @movimiento_stock = MovimientoStock.find(params[:id])\n respond_to do |format|\n if @movimiento_stock.update_attributes(params[:movimiento_stock])\n format.html { redirect_to @movimiento_stock, notice: 'Movimiento stock was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @movimiento_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @model_stock.update(model_stock_params)\n format.html { redirect_to @model_stock, notice: t('common.message.updated_success')}\n format.json { render :show, status: :ok, location: @model_stock }\n else\n format.html { render :edit }\n format.json { render json: @model_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @total_stock = TotalStock.find(params[:id])\n\n respond_to do |format|\n if @total_stock.update_attributes(params[:total_stock])\n format.html { redirect_to @total_stock, notice: 'Total stock was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @total_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @sp500_stock = Sp500Stock.find(params[:id])\n\n respond_to do |format|\n if @sp500_stock.update_attributes(params[:sp500_stock])\n format.html { redirect_to @sp500_stock, notice: 'Sp500 stock was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @sp500_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @stock_master.update(stock_master_params)\n format.html { redirect_to @stock_master, notice: 'Stock master was successfully updated.' }\n format.json { render :show, status: :ok, location: @stock_master }\n else\n format.html { render :edit }\n format.json { render json: @stock_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @various_stock.update(various_stock_params)\n format.html { redirect_to @various_stock, notice: 'Various stock was successfully updated.' }\n format.json { render :show, status: :ok, location: @various_stock }\n else\n format.html { render :edit }\n format.json { render json: @various_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @movie_stock.update(movie_stock_params)\n format.html { redirect_to [:admin, @movie_stock], notice: \"Movie Stock was successfully updated.\" }\n format.json { render :show, status: :ok, location: [:admin, @movie_stock] }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: [:admin, @movie_stock].errors, status: :unprocessable_entity }\n end\n\n end\n end", "def update\n respond_to do |format|\n if @stock_setting.update(stock_setting_params)\n format.html { redirect_to @stock_setting, notice: 'Stock setting was successfully updated.' }\n format.json { render :show, status: :ok, location: @stock_setting }\n else\n format.html { render :edit }\n format.json { render json: @stock_setting.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @invoice_stock.update(invoice_stock_params)\n format.html { redirect_to invoice_stocks_path, notice: 'Invoice stock was successfully updated.' }\n format.json { render :show, status: :ok, location: @invoice_stock }\n else\n format.html { render :edit }\n format.json { render json: @invoice_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @asset_stock.update(asset_stock_params)\n format.html { redirect_to @asset_stock, notice: 'Asset stock was successfully updated.' }\n format.json { render :show, status: :ok, location: @asset_stock }\n else\n format.html { render :edit }\n format.json { render json: @asset_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @vending_machine_stock.update(vending_machine_stock_params)\n format.html { redirect_to @vending_machine_stock, notice: 'Vending machine stock was successfully updated.' }\n format.json { render :show, status: :ok, location: @vending_machine_stock }\n else\n format.html { render :edit }\n format.json { render json: @vending_machine_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @food_stock.update(food_stock_params)\n format.html { redirect_to @food_stock, notice: 'Food stock was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @food_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @sku_stock.update(sku_stock_params)\n format.html { redirect_to @sku_stock, notice: 'Sku stock was successfully updated.' }\n format.json { render :show, status: :ok, location: @sku_stock }\n else\n format.html { render :edit }\n format.json { render json: @sku_stock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @fitment_center_stock = FitmentCenterStock.find(params[:id])\n\n respond_to do |format|\n if @fitment_center_stock.update_attributes(params[:fitment_center_stock])\n format.html { redirect_to @fitment_center_stock, notice: 'Fitment center stock was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fitment_center_stock.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /stock_medicas/1 DELETE /stock_medicas/1.json
def destroy @stock_medica.destroy respond_to do |format| format.html { redirect_to stock_medicas_url, notice: 'Stock medica was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @stock.destroy\n respond_to do |format|\n format.html { redirect_to api_stocks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mouvement_stock.destroy\n respond_to do |format|\n format.html { redirect_to mouvement_stocks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @sp500_stock = Sp500Stock.find(params[:id])\n @sp500_stock.destroy\n\n respond_to do |format|\n format.html { redirect_to sp500_stocks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @total_stock = TotalStock.find(params[:id])\n @total_stock.destroy\n\n respond_to do |format|\n format.html { redirect_to total_stocks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @stock = Stock.find(params[:id])\n @stock.destroy\n\n respond_to do |format|\n format.html { redirect_to stocks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @core_stock.destroy\n respond_to do |format|\n format.html { redirect_to core_stocks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @manual_stock.destroy\n respond_to do |format|\n format.html { redirect_to manual_stocks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @bacterial_stock.destroy\n respond_to do |format|\n format.html { redirect_to @sequence, notice: 'Bacterial stock was successfully deleted.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @food_stock.destroy\n respond_to do |format|\n format.html { redirect_to food_stocks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @stumark = Stumark.find(params[:id])\n @stumark.destroy\n\n respond_to do |format|\n format.html { redirect_to stumarks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_stadium.destroy\n respond_to do |format|\n format.html { redirect_to api_stadia_url }\n format.json { head :no_content }\n end\n end", "def destroy\n # @core_stock_in_bill.destroy\n # respond_to do |format|\n # format.html { redirect_to core_stock_in_bills_url }\n # format.json { head :no_content }\n # end\n end", "def destroy\n @asset_stock.destroy\n respond_to do |format|\n format.html { redirect_to asset_stocks_url, notice: 'Asset stock was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @stock_audit.destroy\n respond_to do |format|\n format.html { redirect_to stock_audits_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @seo_metum = SeoMetum.find(params[:id])\n @seo_metum.destroy\n\n respond_to do |format|\n format.html { redirect_to seo_meta_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @addstock.destroy\n respond_to do |format|\n format.html { redirect_to addstocks_url, notice: 'Addstock was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @stock_item = StockItem.find(params[:id])\n @stock_item.destroy\n\n respond_to do |format|\n format.html { redirect_to stock_items_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @stock_master.destroy\n respond_to do |format|\n format.html { redirect_to stock_masters_url, notice: 'Stock master was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @uniform_stock_received.destroy\n respond_to do |format|\n format.html { redirect_to uniform_stock_receiveds_url, notice: (t 'uniform_stock_receiveds.title')+(t 'actions.removed') }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The number of rotational degrees required to display this image as upright
def required_rotation_for_upright_display required_rotation_orientation_in_degrees = (360 - self.orientation) % 360 return required_rotation_orientation_in_degrees end
[ "def image_rotation\n @rotation\n end", "def total_rotation\n rotation + rotation_offset\n end", "def max_tilt_angle; end", "def rotation\n @rotation ||= 0\n end", "def rotation\n @rotation || -Math::PI/2\n end", "def rotated_height\n case self.rotate_to\n when 90, 270 then self.width\n else self.height\n end\n end", "def rot_y; end", "def orientation_as_rotation orientation\n case orientation\n when 6 then 90\n when 3 then 180\n when 8 then 270\n else 0\n end\n end", "def rotated_width\n case self.rotate_to\n when 90, 270 then self.height\n else self.width\n end\n end", "def rotate(img)\n exif = img.get_exif_by_entry(:Orientation)\n return img if !(exif && exif[0] && exif[0][0] == :Orientation)\n case exif[0][1]\n when '1' # Normal\n img\n when '6' # 90 degree\n img.rotate(90) # 90[deg] to clock direction\n when '8' # 270 degree\n img.rotate(-90) # 90[deg] to reversed-clock direction\n else\n img\n end\n end", "def rotate_180!\n pixels.reverse!\n self\n end", "def rotate_it\n if self.image.stored?\n\t\t case self.orientation\n\t\t when 8..7\n\t\t\t\t image.rotate!(270)\n\t\t\t\t self.orientation = 1\n\t when 3..4\n\t\t\t\t image.rotate!(180)\n\t\t\t\t self.orientation = 1\n\t\t when 5..6\n\t\t\t\t image.rotate!(90)\n\t\t\t\t self.orientation = 1\n\t\t end\n\t end\n end", "def angle\n @angle\n end", "def zrotation\n end", "def degrees\n\t\t@degrees ||= cardinal.keys.sort + [360.0]\n\tend", "def absolute_orientation\n current = self\n orientation = 1\n until current.thesis?\n orientation *= current.multiplicator\n current = current.parent\n end\n orientation\n end", "def get_rotation\n return @rotation\n end", "def rotation_anchor\n [0.7, 0.5]\nend", "def track_angle()\n # Using a default for first version\n # Assuming the aircraft heading is perfectly on the route.\n return 0\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts an UID (room, grouping or app) from an URL/path.
def uid_from_path(url, base_store_url) return [:main, 0] if url.include?(base_store_url) return [:category, url.match(/viewGenre\?id\=(\d+)/)[1]] if url.include?("viewGenre?id=") return [:category, url.match(/viewGrouping\?id\=(\d+)/)[1]] if url.include?("viewGrouping?id=") return [:room, url.match(/viewMultiRoom\?fcId\=(\d+)/)[1]] if url.include?("viewMultiRoom?fcId=") return [:app, url.match(/.+id(\d+)/)[1]] if url =~ /\/id\d+/ [nil, nil] end
[ "def id_from_url(url)\n url.split(\"/\")[-1]\n end", "def extract_pid(uri)\n URI(uri).path.split('/').last\n end", "def find_id(uri)\n Addressable::URI.parse(uri).basename\n end", "def parse_attachment_reference_uuid_from_url(url)\n result = url&.match(ATTACHMENT_ID_REGEX)\n result ? result[1] : nil\n end", "def uid\n Base32::URL.encode(id, split: 4, length: 16)\n end", "def extract_work_id( url )\n /^.*\\/(\\d+-\\d+-.*)$/.match( url )[ 1 ]\nend", "def guid_from_url\n # get the last large number from the url, if there is one\n url.to_s.scan(/[0-9]{6,12}/).last\n end", "def parse_attachment_reference_id_from_url(url)\n # TODO: Attachments from a third party domain with the same path should not be returned.\n result = url.match(ATTACHMENT_ID_REGEX)\n result ? result[1] : nil\n end", "def id_from_uri(uri)\n id = URI.parse(uri)\n # /notes/abc\n if id.path[0,1] == \"/\"\n id.path.split(\"/\")[2]\n else\n id.to_s\n end\n end", "def extract_identity(uri)\n return $1.downcase if uri =~ %r[/user/([a-zA-Z_1-9-]*)] || uri =~ %r[://([a-zA-Z_1-9-]*)?\\.#{AppConfig.host(request.host)}] || uri =~ %r[://(.*?)/?$]\n return nil\n end", "def steam_id_from_url(url)\n url.slice!('https://store.steampowered.com/app/')\n m = url.match(/(\\d+)\\/?/)\n return nil if m.nil?\n m.captures.first.to_i\nend", "def id_from_url(url)\n feed = where(:user_id => User.current_user_id, :url => url).first\n feed.nil? ? 0 : feed.id\n end", "def id(string)\n return if string.blank?\n\n URI(string)\n .path\n .split(\"/\")\n .last\n .to_i\n end", "def trip_id\n url.to_s =~ /information\\/[a-z]+\\/[^\\/]+\\/([^\\/]+)/\n $1\n end", "def extract_user_id(username)\n username[2..-2]\n end", "def extract_id(image_id)\n regex = /500px\\.com\\/photo\\/(\\d+)\\//\n matches = regex.match(image_id)\n return nil if !matches\n match = matches[1]\n return nil if match.empty?\n match\n end", "def get_vimeo_id(uri)\n return uri.sub(\"/users/\", \"\")\n end", "def get_userid(url=USERID_URL)\n get(url)\n end", "def extract_uuid(section_hash)\n section_hash['id'].split('@').first\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
certinfos should be a hashlike where each entry describes a certificate. defaulthostname should be a string that will be inserted into %HOSTNAME% in certificate subject lines.
def initialize(certinfos, defaulthostname, config={}) @config = config @defaulthostname = defaulthostname @parenthostname = defaulthostname.sub(/^[\w-]+\./, '') # remove left-most label @certinfos = certinfos @certificates = {} end
[ "def warning_subjectaltname(cert, warning_messages, required_san_array, service_name)\n cent_san_hash = get_san_hash(cert)\n altnames = cent_san_hash[:altnames] || []\n ip_altnames = cent_san_hash[:ip_altnames] || []\n cert_san_array = altnames + ip_altnames\n missing_hostnames = []\n\n # Convert all IP addresses to canonical form\n required_san_array.each do |i|\n temp_san = case i\n when Resolv::IPv4::Regex\n IPAddr.new(i).to_string\n when Resolv::IPv6::Regex\n # :nocov:\n # We aren't using IPv6 in production so we are skipping tests for this\n IPAddr.new(i).to_string\n # :nocov:\n else\n i\n end\n missing_hostnames << i unless cert_san_array.include?(temp_san)\n end\n\n return if missing_hostnames.empty?\n warning_messages.push(\"Warning, #{service_name} is missing the following hostnames in its \" \\\n \"certificate: #{missing_hostnames.join(\" \")}\")\n end", "def lookup_cert(hostname=nil)\n @@certcache ||= {}\n\n if hostname\n cachekey = \"#{hostname}:#{dest_port}\"\n else\n cachekey = \"#{dest_host}:#{dest_port}\"\n end\n\n unless @@certcache.has_key? cachekey\n logdebug \"lookup_cert: cache miss, looking up and doctoring actual cert\", :dest => cachekey\n @@certcache[cachekey] = doctor_cert(preflight_for_cert(hostname), @ca_chain[0], @key)\n else\n logdebug \"lookup_cert: cache hit\", :dest => cachekey\n end\n logdebug \"lookup_cert: returning\", :subject => @@certcache[cachekey].subject\n @@certcache[cachekey]\n end", "def parse_cert(cert)\n domains_to_add = []\n san_extension = nil\n parsed_cert = OpenSSL::X509::Certificate.new(cert)\n parsed_cert.extensions.each { |extension|\n if (extension.oid == 'subjectAltName') then\n domains_to_add = parse_san_extension(extension)\n end\n }\n {:subject => parsed_cert.subject, :subjectAltName => domains_to_add}\n end", "def change_name_to_certname(hash)\n hash['certname'] = hash.delete('name')\n\n hash\n end", "def main\n certificates = get_certificate_objects\n definitions = get_certificate_definitions\n\n puts %(#{\"NAMESPACE\".ljust(50)} #{\"CERT. SECRETNAME\".ljust(50)})\n (certificates - definitions).map do |s|\n namespace, name = s.split(\":\")\n puts \"#{namespace.ljust(50)} #{name.ljust(50)}\"\n end\nend", "def collect_cert_info\n # Redirect keytool check error to /dev/null\n os_has_keytool = system('keytool 2>/dev/null')\n raise 'keytool dependency not satisfied. Make sure that JAVA keytool utility is installed' unless os_has_keytool\n cert_info = {}\n certificate_raw = `keytool -printcert -rfc -jarfile #{@apk_path.shellescape}`\n certificate_content_regexp = /(-----BEGIN CERTIFICATE-----.*-----END CERTIFICATE-----)/m\n matched_data = certificate_content_regexp.match(certificate_raw)\n if matched_data\n certificate_content = matched_data.captures[0]\n cert_info = {\n issuer_raw: nil,\n cn: nil,\n ou: nil,\n o: nil,\n st: nil,\n l: nil,\n c: nil,\n creation_date: nil,\n expiration_date: nil\n }\n cert_extract_dates(certificate_content, cert_info)\n cert_extract_issuer(certificate_content, cert_info)\n else\n puts 'Failed to find CERT.RSA file in APK'\n end\n cert_info\n end", "def run_fake_pki_ca_on( ca_sut = master, suts = hosts, local_dir = '' )\n puts \"== Fake PKI CA\"\n pki_dir = File.expand_path( \"../../files/pki\", File.dirname(__FILE__))\n host_dir = '/root/pki'\n\n ca_sut.mkdir_p(host_dir)\n Dir[ File.join(pki_dir, '*') ].each{|f| copy_to( ca_sut, f, host_dir)}\n\n # Collect network information from all SUTs\n #\n # We need this so that we don't insert any common IP addresses into certs\n suts_network_info = {}\n\n hosts.each do |host|\n fqdn = fact_on(host, 'fqdn').strip\n\n host_entry = { fqdn => [] }\n\n # Add the short name because containers can't change the hostname\n host_entry[fqdn] << host.name if (host[:hypervisor] == 'docker')\n\n # Ensure that all interfaces are active prior to collecting data\n activate_interfaces(host)\n\n networking_fact = pfact_on(host, 'networking')\n if networking_fact && networking_fact['interfaces']\n networking_fact['interfaces'].each do |iface, data|\n next unless data['ip']\n next if data['ip'].start_with?('127.')\n\n host_entry[fqdn] << data['ip'].strip\n end\n else\n # Gather the IP Addresses for the host to embed in the cert\n interfaces = fact_on(host, 'interfaces').strip.split(',')\n interfaces.each do |interface|\n ipaddress = fact_on(host, \"ipaddress_#{interface}\")\n\n next if ipaddress.nil? || ipaddress.empty? || ipaddress.start_with?('127.')\n\n host_entry[fqdn] << ipaddress.strip\n end\n end\n\n unless host_entry[fqdn].empty?\n suts_network_info[fqdn] = host_entry[fqdn].sort.uniq\n end\n end\n\n # Get all of the repeated SUT IP addresses:\n # 1. Create a hash of elements that have a key that is the value and\n # elements that are the same value\n # 2. Grab all elements that have more than one value (therefore, were\n # repeated)\n # 3. Pull out an Array of all of the common element keys for future\n # comparison\n common_ip_addresses = suts_network_info\n .values.flatten\n .group_by{ |x| x }\n .select{|k,v| v.size > 1}\n .keys\n\n # generate PKI certs for each SUT\n Dir.mktmpdir do |dir|\n pki_hosts_file = File.join(dir, 'pki.hosts')\n\n File.open(pki_hosts_file, 'w') do |fh|\n suts_network_info.each do |fqdn, ipaddresses|\n fh.puts ([fqdn] + (ipaddresses - common_ip_addresses)) .join(',')\n end\n end\n\n copy_to(ca_sut, pki_hosts_file, host_dir)\n\n # generate certs\n on(ca_sut, \"cd #{host_dir}; cat #{host_dir}/pki.hosts | xargs bash make.sh\")\n end\n\n # if a local_dir was provided, copy everything down to it\n unless local_dir.empty?\n FileUtils.mkdir_p local_dir\n scp_from( ca_sut, host_dir, local_dir )\n end\n end", "def epoc_cert_info cert, plat\n this_dir = File.dirname(File.expand_path(__FILE__))\n caps = case plat\n when /_3[01]_/\n SELF30_CAPS\n else\n SELF32_CAPS\n end\n args = [File.join(this_dir, \"selfsigned.key\"),\n File.join(this_dir, \"selfsigned.cer\"),\n nil,\n caps]\n EpocLocalRb::CertInfo.new(*args)\nend", "def facts_for_node(certnames)\n return {} if certnames.empty? || certnames.nil?\n\n certnames.uniq!\n name_query = certnames.map { |c| [\"=\", \"certname\", c] }\n name_query.insert(0, \"or\")\n\n @logger.debug(\"Querying certnames\")\n result = make_query(name_query, 'inventory')\n\n result&.each_with_object({}) do |node, coll|\n coll[node['certname']] = node['facts']\n end\n end", "def configure(cert)\n cert.version = 2\n cert.serial = serial\n cert.subject = OpenSSL::X509::Name.parse(name)\n cert.issuer = cert.subject\n cert.public_key = key.public_key\n cert.not_before = days_ago(2)\n cert.not_after = days_from_now(2)\n end", "def parse_file(doc)\n address = doc[0]['ip'] + ':' + doc[0]['port']\n @host_results[address] = Hash.new\n \n\n\n #testSSL JSON files are an array of elements, it's nicer for this to be able to key off a hash of the id\n results = Hash.new\n doc.each {|element| results[element['id']] = element}\n\n #Get a list of the valid hostnames for the Certificat\n sans = results['san']['finding']\n sans.slice!('subjectAltName (SAN) : ')\n host_names = Array.new\n host_names << sans.split(' ')\n host_names << address.split('/')[0]\n\n @host_results[address]['port'] = results['service']['port']\n\n #Self Signed Certificate Checks\n if results['chain_of_trust']['finding'].downcase =~ /self signed/\n @host_results[address]['self_signed'] = true\n else\n @host_results[address]['self_signed'] = false\n end\n\n #Untrusted Issuer\n if results['chain_of_trust']['finding'].downcase =~ /all certificate trust checks failed/\n @host_results[address]['untrusted_issuer'] = true\n else\n @host_results[address]['untrusted_issuer'] = false\n end\n\n #Hostname Mismatch\n #if results['cn']['finding'].downcase =~ /(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\\.?/\n # hostname = results['cn']['finding'].slice(/(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\\.?/)\n # unless host_names.eql?(hostname)\n # @host_results[address]['hostname_mismatch'] = true\n # else\n # @host_results[address]['hostname_mismatch'] = false\n # end\n #end\n\n @host_results[address]['hostname_mismatch'] = \"Manual check needed\"\n @host_results[address]['cert_no_www'] = \"Manual check needed\"\n #Cert No WWW\n #if results['trust']['finding'].downcase =~ //\n # @host_results[address]['cert_no_www'] = true\n #else\n # @host_results[address]['cert_no_www'] = false\n #end\n\n #Expiration\n if results['expiration']['severity'] != \"OK\"\n @host_results[address]['expired_cert'] = true\n else\n @host_results[address]['expired_cert'] = false\n end\n\n #About to expire \n if results['expiration']['severity'] != \"OK\"\n @host_results[address]['cert_expiring_soon'] = true\n else\n @host_results[address]['cert_expiring_soon'] = false\n end\n\n #Wildcard Cert\n if results['cn']['finding'].downcase =~ /wildcard/\n @host_results[address]['wildcard_cert'] = true\n else\n @host_results[address]['wildcard_cert'] = false\n end\n\n\n #Public Key Size INFO is passed for 2048 bit key\n if results['key_size']['severity'] == \"INFO\" \n @host_results[address]['public_key_size'] = false\n else\n @host_results[address]['public_key_size'] = true\n end\n\n #SHA-1 Signed\n if results['algorithm']['finding'].downcase =~ /sha1/\n @host_results[address]['sha1_signed'] = true\n else\n @host_results[address]['sha1_signed'] = false\n end\n\n #Anonymous Ciphers\n if results['std_aNULL']['severity'] == \"OK\" && \n results['std_ADH']['severity'] == \"OK\"\n @host_results[address]['anonymous_ciphers'] = false\n else\n @host_results[address]['anonymous_ciphers'] = true\n end\n\n #Weak Ciphers\n if results['std_LOW']['severity'] == \"OK\" &&\n results['std_DES']['severity'] == \"OK\" && \n results['std_MEDIUM']['severity'] == \"OK\" && \n results['std_3DES']['severity'] == \"OK\"\n @host_results[address]['weak_ciphers'] = false\n else\n @host_results[address]['weak_ciphers'] = true\n end\n\n #RC4 Ciphers\n if results['rc4']['severity'] == \"OK\"\n @host_results[address]['rc4_ciphers'] = false\n else\n @host_results[address]['rc4_ciphers'] = true\n end\n\n #Weak Diffie Hellman\n if results['logjam']['severity'] == \"OK\"\n @host_results[address]['weak_dh'] = false\n else\n @host_results[address]['weak_dh'] = true\n end\n\n #Weak RSA\n if results['freak']['severity'] == \"OK\"\n @host_results[address]['weak_rsa'] = false\n else\n @host_results[address]['weak_rsa'] = true\n end\n\n #No PFS\n if results['pfs']['severity'] == \"OK\"\n @host_results[address]['no_pfs'] = false\n else\n @host_results[address]['no_pfs'] = true\n end\n\n #SSLv2\n if results['sslv2']['severity'] == \"OK\"\n @host_results[address]['sslv2_supported'] = false\n else\n @host_results[address]['sslv2_supported'] = true\n end\n\n #SSLv3\n if results['sslv3']['severity'] == \"OK\"\n @host_results[address]['sslv3_supported'] = false\n else\n @host_results[address]['sslv3_supported'] = true\n end\n\n #TLSv1 (there should be a better way to check this)\n if results['tls1']['severity'] == \"INFO\" &&\n (results['tls1_1']['severity'] != \"INFO\" &&\n results['tls1_2']['severity'] !=\"OK\")\n @host_results[address]['no_tls_v1_1_2'] = true\n else\n @host_results[address]['no_tls_v1_1_2'] = false\n end\n\n #Client Renegotation\n if results['sec_client_renego']['severity'] == \"OK\"\n @host_results[address]['client_renegotiation'] = false\n else\n @host_results[address]['client_renegotiation'] = true\n end\n\n if results['secure_renego']['severity'] == \"OK\"\n @host_results[address]['insecure_renegotiation'] = false\n else\n @host_results[address]['insecure_renegotiation'] = true\n end\n\n #Need to wrap this as not all output has this issue present in the file.\n begin\n if results['breach']['severity'] == \"OK\"\n @host_results[address]['compression'] = false\n else\n @host_results[address]['compression'] = true\n end\n rescue NoMethodError\n @host_results[address]['compression'] = false\n end\n\n if results['ccs']['severity'] == \"OK\"\n @host_results[address]['ccs_vuln'] = false\n else\n @host_results[address]['ccs_vuln'] = true\n end\n\n if results['beast']['severity'] == \"OK\"\n @host_results[address]['beast'] = false\n else\n @host_results[address]['beast'] = true\n end\n\n end", "def certificate_path\n\t\t\tFile.join(@root, \"#{@hostname}.crt\")\n\t\tend", "def set_certificate_entry(aliaz, certificate)\n\n end", "def make_certs(config, verbose=false)\n FileUtils.mkdir_p config['certmaker']['outdir'], :verbose => verbose\n\n certs = CertificateSuiteGenerator.new(config['certs'], config['hostname'], config['certmaker']).certificates\n\n certs.each do |calias, ck|\n File.open(File.join(config['certmaker']['outdir'],calias+\"cert.pem\"),\"wb\") { |f| f.write ck[:cert] }\n File.open(File.join(config['certmaker']['outdir'],calias+\"key.pem\"),\"wb\") { |f| f.write ck[:key] }\n end\n\n end", "def certification_name=(value)\n @certification_name = value\n end", "def autosign certname\n FileUtils.touch(autosign_file) unless File.exist?(autosign_file)\n\n autosign = File.open(autosign_file, File::RDWR)\n # Check that we don't have that host already\n found = autosign.readlines.find { |line| line.chomp == certname }\n autosign.puts certname unless found\n autosign.close\n logger.info \"Added #{certname} to autosign\"\n end", "def tls_hostname; end", "def cert=(cert); end", "def servernames_from_csr(csr)\n server_names = []\n\n # get common name\n cn = csr.subject.to_a.find{ |key,val,type| key=='CN' }\n server_names << cn[1] \n\n # try finding SubjectAltName\n extreq = csr.attributes.find { |attr| attr.oid == 'extReq' }\n return server_names unless extreq\n\n asnext = extreq.value\n return server_names unless asnext.value.is_a?(Array)\n\n asnext.value.each do |asnseq1|\n next unless asnseq1.is_a?(OpenSSL::ASN1::Sequence)\n next unless asnseq1.value.is_a?(Array)\n\n asnseq1.value.each do |asnseq2|\n next unless asnseq2.is_a?(OpenSSL::ASN1::Sequence)\n next unless asnseq2.value.is_a?(Array)\n\n ary = asnseq2.value.map{ |asn|\n asn.value if asn.is_a?(OpenSSL::ASN1::Primitive)\n }\n ext = nil\n case ary.size\n when 2\n # extension oid , extension value\n ext = OpenSSL::X509::Extension.new(ary[0], ary[1])\n when 3\n # extension oid , critical, extension value\n ext = OpenSSL::X509::Extension.new(ary[0], ary[2], ary[1])\n end\n\n if ext && ext.oid == 'subjectAltName' then\n # subjectAltName extension found\n ext.value.split(',').each do |san|\n # san = \"DNS:host.example.com\" etc.\n san.strip!\n type,host = san.split(':')\n if type == 'DNS' then\n server_names << host.strip\n end\n end\n end\n end\n end\n server_names.uniq\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTIONS a_anno 0:chr 1:pos 3:oldBase 4:newBase 5:quality 10:gene 11:/+ 12:exon/intron/promotor a_gen 1:gene 2:chr 3:+/ 4:start 5:stop 6:start_coding 7:end_coding 8:ofExons 9:ExonStarts 10:exonEnds
def mutations_effect(a_anno, a_gen) if $locus[a_anno[10]] && a_anno[3].length == a_anno[4].length $cdna.pos = $locus[a_anno[10]] transcript = original() exon_starts = a_gen[9].split(',') exon_ends = a_gen[10].split(',') mutation_position,exon_num = position_on_transcript(a_anno[1],a_gen[3],exon_starts,exon_ends,a_gen[6],a_gen[7]) a_anno[12] = "exon#{exon_num}" start_triplet = (mutation_position/3 * 3) - 1 if start_triplet >= 0 code = transcript[start_triplet..start_triplet+2] pos_in_triplet = mutation_position%3 original_aa = $codes[code] code[pos_in_triplet] = a_anno[4] mutated_aa = $codes[code[0..2]] if original_aa != mutated_aa a_anno[13] = pos_in_triplet + 1 a_anno[14] = original_aa[:name] a_anno[15] = mutated_aa[:name] puts a_anno.join("\t") else a_anno[13] = "same_AA" STDERR.puts a_anno.join("\t") end end else if $locus_non_coding[a_anno[10]] a_anno[13] = "ncrna" STDERR.puts a_anno.join("\t") else if (a_anno[3].length > a_anno[4].length || a_anno[3].length < a_anno[4].length) a_anno[13] = "indel" puts a_anno.join("\t") else a_anno[13] = "?" STDERR.puts a_anno.join("\t") end end end end
[ "def write_fasta_annotation (file_list)\n file_list.each do |f|\n abort(\"Couldn't open the file #{f}\") unless File.exists?(f)\n f_basename = File.basename(f, \".gbk\")\n outfile = File.open(\"fasta_with_annotations/\" + f_basename + \".fasta\", 'w')\n bio_gbk = Bio::GenBank.open(f)\n count = 0\n print \"#{f_basename} writing fasta with annotation...\"\n bio_gbk.each do |e|\n e.features.drop(1).each do |gene|\n na_seq = Bio::Sequence::NA.new(e.naseq.splicing(gene.position))\n begin\n next if gene.feature == \"source\" || gene.feature == \"gene\"\n count += 1\n outfile.write(na_seq.to_fasta(f_basename + \"_\" + count.to_s + \" product='\\\"\" +gene.assoc['product'] + \"'\\\" \" + \"loc=\"+ gene.position))\n rescue\n puts \"could not write #{f_basename}\"\n puts \"gene number \" + count.to_s \n puts gene.assoc['product'] unless gene.assoc['product'].nil? #or gene.assoc['product'].exists?\n end\n end \n end\n puts \"#{f_basename} wrote #{count} CDS\"\n end\nend", "def get_annotations_xml(xmlfile)\n annos = Hash.new {|h,k| h[k] = Hash.new {|h,k| h[k] ={} } }\n @doc = Nokogiri::XML(File.open(xmlfile))\n geneid = (@doc.xpath(\"//xmlns:xref\"))[0]['id']\n\n (@doc.xpath(\"//xmlns:go-xref\")).each do |p|\n ## Descriptions might have [\"] characters that would results unexpected comma separation, so replace with [']\n info = p['category'] + '\",\"' + (p['name']).gsub(/\\\"/, \"'\")\n annos[geneid][p['db']][p['id']] = info\n end\n\n (@doc.xpath(\"//xmlns:signature\")).each do |p|\n library = \"\"\n p.children.each do |k|\n k.to_s =~ /signature-library-release.*library=\"(.*)\"/\n test = $1\n\t\t if test =~ /\\w/\n library = test\n end\n end\n info = \"\"\n next unless p['name'] =~ /\\w/\n if p['desc'] !~ /\\w/\n info = (p['name']).gsub(/\\\"/, \"'\")\n else\n info = (p['name']).gsub(/\\\"/, \"'\") + '\",\"' + (p['desc']).gsub(/\\\"/, \"'\")\n end\n annos[geneid][library][p['ac']] = info\n end\n \n annos\nend", "def match_exon (seq) #object to take the target in given exon\r\n\r\n len_seq = seq.length()\r\n exon_positions = Hash.new\r\n\r\n # #we take all the positions inside of the seq that match with cttctt\r\n positions_direct_match = seq.gsub(/#{$match}/).map{Regexp.last_match.begin(0)}\r\n positions_reverse_match = seq.reverse_complement.gsub(/#{$match}/).map{Regexp.last_match.begin(0)}\r\n\r\n #Look for the features for the seq: exon id, position and strand\r\n seq.features.each do |feature|\r\n\r\n if feature.feature =~ /exon/ #first filter --> has to be exon\r\n\r\n position = feature.position\r\n\r\n exon_id = feature.qualifiers[0].value.gsub('exon_id=', '')\r\n\r\n\r\n if position =~ /complement/ # If that happens --> the strand is reverse -\r\n #coordinates for exons\r\n position = feature.position.match(/[0-9]+\\.\\.[0-9]+/).to_s.split(\"..\")\r\n positions_exon = []\r\n\r\n position.each do |pos|\r\n #We transform the coordinates\r\n positions_exon.insert(0, len_seq - pos.to_i)\r\n end\r\n\r\n strand = '-'\r\n positions_reverse_match.each do |match_init|\r\n\r\n match_end = match_init + $match.length() - 1\r\n\r\n if (match_init >= positions_exon[0].to_i) && (match_init <= positions_exon[1].to_i) && (match_end >= positions_exon[0].to_i) && (match_end <= positions_exon[1].to_i)\r\n\r\n m_end = len_seq - match_end\r\n m_init = len_seq - match_init\r\n exon_positions[[m_end, m_init]] = [exon_id, strand]\r\n\r\n end\r\n\r\n end\r\n\r\n ####################################################################################################################33\r\n else #the exon is +\r\n\r\n position_exon = position.split(\"..\")\r\n\r\n strand = '+'\r\n positions_direct_match.each do |match_begin|\r\n\r\n match_end = match_begin + $match.length() - 1\r\n\r\n if (match_begin >= position_exon[0].to_i) && (match_begin <= position_exon[1].to_i) && (match_end >= position_exon[0].to_i) && (match_end <= position_exon[1].to_i)\r\n #The target have to be inside of the exon\r\n exon_positions[[match_begin, match_end]] = [exon_id, strand]\r\n\r\n end\r\n\r\n end\r\n\r\n end #if complement === reverse\r\n\r\n\r\n end #end exon\r\n end #end features\r\n\r\n return exon_positions\r\n\r\n\r\nend", "def setup_gene_from_first_line(gene_line)\n gene = PositionedGeneWithOntology.new\n gene.start = gene_line.start\n gene.strand = gene_line.strand\n aliai = gene_line.attributes['Alias']\n if aliai\n aliai.chomp!\n gene.alternate_ids = aliai.split ','\n end\n \n # make description proper\n description = gene_line.attributes['description']\n gene.description = CGI::unescape(description) # yey for useful functions I didn't write\n \n # name - remove the 'apidb|' bit\n match = gene_line.attributes['ID'].match('apidb\\|(.*)')\n if !match or !match[1] or match[1] === ''\n raise Exception, \"Badly parsed gene name: #{gene_line}.attributes['ID']}.\"\n end\n gene.name = match[1]\n gene.seqname = gene_line.seqname\n \n return gene\n end", "def extract_genes file_prefix\n\n if ! File.exists? file_prefix+\".cds.fasta\"\n\n puts \" ..extracting genes from #{file_prefix}\"\n\n fasta_f = file_prefix + \".fasta\"\n gbk_f = file_prefix + \".gb\"\n gbk_parser = GenbankParser.new(gbk_f)\n cds = gbk_parser.getFtsProtSequences(\"#{File.basename(file_prefix)}\", true)\n\n File.open(file_prefix+\".cds.fasta\",\"w\") do |fout|\n fout.write(cds)\n end\n\n fts_f = file_prefix + \".gb.fts.tsv\"\n fasta_parser = FastaParser.new(fasta_f)\n trna_output = \"\"\n rrna_output = \"\"\n\n File.open(fts_f, \"r\").drop(1).each do |f|\n lA = f.chomp!.split(\"\\t\")\n next if lA[5] == \"1\" # skip partial gene\n basename = File.basename(fasta_f).gsub('.fasta','')\n header = \"#{basename}|#{lA[1]}|#{lA[6]}|#{lA[7]}|#{lA[8]}|#{lA[9]}\"\n if lA[0] == \"tRNA\"\n trna_output += fasta_parser.getSeqLoc(lA[1], \"#{lA[2]}..#{lA[3]}\", \"#{lA[4]}\", 0, header)\n elsif lA[0] == \"rRNA\"\n rrna_output += fasta_parser.getSeqLoc(lA[1], \"#{lA[2]}..#{lA[3]}\", \"#{lA[4]}\", 0, header)\n end\n end\n\n # write output\n File.open(file_prefix+\".trna.fasta\", \"w\") do |f_out|\n f_out.write(trna_output)\n end\n\n File.open(file_prefix+\".rrna.fasta\", \"w\") do |f_out|\n f_out.write(rrna_output)\n end\n\n end\n\nend", "def annotate\n kegg_features = []\n go_features = []\n kegg = fetch('http://togows.org/entry/kegg-genes/ath:'+ self.gene_id)\n if kegg\n pathways = kegg.body.match(Regexp.new(/PATHWAY(.*)BRITE/m))\n if pathways.singleton_class != NilClass\n pathways = pathways.captures[0].split(\"\\n\")\n for pathway in pathways\n pathway = pathway.split(\" \")\n pathway_id = pathway[0]\n pathway_name = pathway[1]\n kegg_features << [pathway_id, pathway_name]\n end\n end\n end\n go = fetch('http://togows.org/entry/ebi-uniprot/'+ self.gene_id)\n if go\n go_ids = go.body.scan(Regexp.new(/DR\\s*GO;\\s(GO:\\d{7});\\sP:.*;/))\n go_names = go.body.scan(Regexp.new(/DR\\s*GO;\\sGO:\\d{7};\\sP:(.*);/))\n for i in 0..go_ids.length-1\n go_id = go_ids[i][0]\n go_name = go_names[i][0]\n go_features << [go_id, go_name]\n end \n end\n self.kegg_annotations = kegg_features\n self.go_annotations = go_features\n end", "def load_gff_file(gff_path)\n gen_annots = {}\n chr = \"\"\n File.open(gff_path).each do |line|\n if !( line.start_with?(\"#\") )\n fields = line.chomp.split(\"\\t\")\n if fields[2] == \"region\"\n metadata = fields[8].split(\";\")\n n = (( metadata[3] ).split(\"=\")[1])\n chr = \"chr#{n}\"\n elsif fields[2] == \"gene\"\n metadata = fields[8].split(\";\")\n id = (metadata.shift.split(\"=\"))[1]\n gen_annots[id] = {}\n gen_annots[id][\"pseudo\"] = metadata.include?(\"pseudo=true\") ? \"true\" : \"false\"\n gen_annots[id][\"chr\"] = chr\n gen_annots[id][\"start\"] = fields[3]\n gen_annots[id][\"stop\"] = fields[4]\n\n metadata.each do |item|\n key = item.split(\"=\")[0]\n value = item.split(\"=\")[1]\n gen_annots[id][key] = value\n end\n end\n end\n end\n return gen_annots\nend", "def target_def; genomic.definition; end", "def chromosome\n \n #a method for returning chromosome sequence as if it were a read to trick annoj into showing a reference sequence...\n if request.get?\n ##sort out the params from annoj's get\n annoj_params = {}\n request.url.split(/&/).each do |pair|\n k,v = pair.split(/=/)\n annoj_params[k] = v\n end#CGI.parse(URI.parse(request.url).query)\n annoj_params.each_pair {|k,v| annoj_params[k] = v.to_s}\n case annoj_params['action']\n when \"syndicate\"\n @response = syndicate(params[:id])\n when \"describe\"\n @response = [] ##to be done... \n end\n render :json => @response, :layout => false\n elsif request.post?\n annoj_params = {}\n request.raw_post.split(/&/).each do |pair|\n k,v = pair.split(/=/)\n annoj_params[k] = v\n end\n annoj_params.each_pair {|k,v| annoj_params[k] = v.to_s}\n #now do the specific stuff based on the annoj action... \n if annoj_params['action'] == 'range'\n #remember params[:id] is genome id and annoj_params['assembly'] is the chromosome\n sequence = Reference.find(:first, :conditions => {:genome_id => params[:id], :name => annoj_params['assembly']}).sequence.sequence\n subseq = sequence[annoj_params['left'].to_i - 3..annoj_params['right'].to_i - 3]\n f = LightFeature.new(\n :group => '.',\n :feature => 'chromosome',\n :source => '.',\n :start => annoj_params['left'].to_i,\n :end => annoj_params['right'].to_i, \n :strand => '+',\n :phase => '.',\n :seqid => annoj_params['assembly'],\n :score => '.',\n :experiment_id => nil,\n :gff_id => nil,\n :sequence => \"#{subseq}\",\n :quality => nil,\n :reference_id => nil\n )\n zoom_factor = annoj_params['bases'].to_i / annoj_params['pixels'].to_i\n response = new_response\n features = [f]\n #@response = #range(annoj_params['assembly'], annoj_params['left'], annoj_params['right'], params[:id], annoj_params['bases'], annoj_params['pixels'])\n if zoom_factor >= 10\n hist_data = get_histogram(features)\n response[:data] = {}\n response[:data][:read] = hist_data \n\n elsif zoom_factor < 10 and zoom_factor > 0.1\n box_data = get_boxes(features)\n box_data[:watson][0][0] = f.seqid\n response[:data] = {}\n response[:data][:read] = box_data\n else\n read_data = get_reads(features)\n read_data[:watson][0][0] = f.seqid\n response[:data] = {}\n response[:data][:read] = read_data\n end\n @response = response\n\n elsif annoj_params[\"action\"] == \"lookup\"\n @response = [] #to be done also #lookup(annoj_params[\"query\"], params[:id])\n end\n render :json => @response, :layout => false\n end\n end", "def load_gff_file(gff_path)\n gen_annots = {}\n chr = \"\"\n File.open(gff_path).each do |line|\n if !( line.start_with?(\"#\") )\n fields = line.chomp.split(\"\\t\")\n if fields[2] == \"region\"\n metadata = fields[8].split(\";\")\n n = (( metadata[3] ).split(\"=\")[1])\n chr = \"chr#{n}\"\n elsif fields[2] == \"gene\"\n metadata = fields[8].split(\";\")\n id = (metadata.shift.split(\"=\"))[1]\n gen_annots[id] = {}\n gen_annots[id][\"pseudo\"] = \"false\"\n gen_annots[id][\"chr\"] = chr\n gen_annots[id][\"start\"] = fields[3]\n gen_annots[id][\"stop\"] = fields[4]\n\n metadata.each do |item|\n key = item.split(\"=\")[0]\n value = item.split(\"=\")[1]\n gen_annots[id][key] = value\n end\n end\n end\n end\n return gen_annots\nend", "def pubannos(data)\n result = JSON.parse(data)\n \n if result.has_key? 'Error'\n raise BioInterchange::Exceptions::InputFormatError, 'Error parsing the JSON input file: #{result[\"Error\"]}'\n end\n \n text = result['text']\n #doc_uri = \"http://pubannotation.dbcls.jp/pmdocs/\" + result['pmid'].to_s\n doc_uri = result['docurl']\n \n doc = Document.new(doc_uri)\n docContent = Content.new(0, text.length, Content::DOCUMENT, @process)\n docContent.setContext(doc)\n doc.add(docContent)\n \n #so our document requires content of type document or abstract\n #should it hold the content string?\n\n #hash to remember annotation in case they are needed for building upon based on ids later\n contents = {}\n\n if result['catanns']\n result['catanns'].each do |annot| \n start_offset = 0\n end_offset = 0\n if annot['span']\n start_offset = annot['span']['begin']\n end_offset = annot['span']['end']\n elsif annot['begin'] and annot['end']\n start_offset = annot['begin']\n end_offset = annot['end']\n end\n length = end_offset - start_offset\n\n category = annot['category']\n id = annot['id']\n \n entity = text.slice(start_offset..end_offset)\n \n #phrase = type for NE\n con = Content.new(start_offset, length, Content::PHRASE, @process)\n con.setContext(doc)\n doc.add(con)\n\n contents[id] = con \n \n #set process.date = updated_time?\n end\n end\n \n if result['insanns']\n result['insanns'].each do |annot|\n \n #unsure what to do about this (con1), 'E1' is the ID of something not created yet.\n #it is perhaps a case of making a new content, but with what params...?\n #need to conform what this is refering to with JDK\n con1 = nil \n con2 = contents[annot['object']]\n \n #get annotation type\n type = ContentConnection::UNSPECIFIED\n case annot['type']\n when 'subClassOf'\n type = ContentConnection::SUBCLASS\n end\n connection = ContentConnection.new(con1, con2, type, @process)\n connection.setContext(doc)\n doc.add(connection)\n\n contents[annot['id']] = connection\n\n end\n end\n \n if result['relanns']\n result['relanns'].each do |annot|\n con1 = contents[annot['subject']] \n con2 = contents[annot['object']]\n \n #get annotation type\n type = ContentConnection::UNSPECIFIED\n case annot['type']\n when 'equivalentTo'\n type = ContentConnection::EQUIVALENCE\n when 'themeOf'\n type = ContentConnection::THEME\n end\n connection = ContentConnection.new(con1, con2, type, @process)\n connection.setContext(doc)\n doc.add(connection)\n\n contents[annot['id']] = connection\n\n end\n end\n \n if result['modanns']\n result['modanns'].each do |annot|\n \n #in this case, it is a modification of an already existing content object (speculation/negation). \n con = contents[annot['object']]\n \n #get annotation type\n type = ContentConnection::UNSPECIFIED\n case annot['type']\n when 'Speculation'\n type = ContentConnection::SPECULATION\n when 'Negation'\n type = ContentConnection::NEGATION\n end\n connection = ContentConnection.new(con, nil, type, @process)\n connection.setContext(doc)\n doc.add(connection)\n\n contents[annot['id']] = connection\n\n end\n end\n \n doc\n end", "def pubannos(data)\n \n result = JSON.parse(data)\n \n if result.has_key? 'Error'\n raise BioInterchange::Exceptions::InputFormatError, 'Error parsing the JSON input file: #{result[\"Error\"]}'\n end\n \n \n text = result['text']\n #doc_uri = \"http://pubannotation.dbcls.jp/pmdocs/\" + result['pmid'].to_s\n doc_uri = result['docurl']\n \n doc = Document.new(doc_uri)\n docContent = Content.new(0, text.length, Content::DOCUMENT, @process)\n docContent.setContext(doc)\n doc.add(docContent)\n \n #so our document requires content of type document or abstract\n #should it hold the content string?\n\n #hash to remember annotation in case they are needed for building upon based on ids later\n contents = {}\n\n if result['catanns']\n result['catanns'].each do |annot| \n start_offset = 0\n end_offset = 0\n if annot['span']\n start_offset = annot['span']['begin']\n end_offset = annot['span']['end']\n elsif annot['begin'] and annot['end']\n start_offset = annot['begin']\n end_offset = annot['end']\n end\n length = end_offset - start_offset\n\n category = annot['category']\n id = annot['id']\n \n entity = text.slice(start_offset..end_offset)\n \n #phrase = type for NE\n con = Content.new(start_offset, length, Content::PHRASE, @process)\n con.setContext(doc)\n doc.add(con)\n\n contents[id] = con \n \n #set process.date = updated_time?\n end\n end\n \n if result['insanns']\n result['insanns'].each do |annot|\n \n #unsure what to do about this (con1), 'E1' is the ID of something not created yet.\n #it is perhaps a case of making a new content, but with what params...?\n #need to conform what this is refering to with JDK\n con1 = nil \n con2 = contents[annot['object']]\n \n #get annotation type\n type = ContentConnection::UNSPECIFIED\n case annot['type']\n when 'subClassOf'\n type = ContentConnection::SUBCLASS\n end\n connection = ContentConnection.new(con1, con2, type, @process)\n connection.setContext(doc)\n doc.add(connection)\n\n contents[annot['id']] = connection\n\n end\n end\n \n if result['relanns']\n result['relanns'].each do |annot|\n con1 = contents[annot['subject']] \n con2 = contents[annot['object']]\n \n #get annotation type\n type = ContentConnection::UNSPECIFIED\n case annot['type']\n when 'equivalentTo'\n type = ContentConnection::EQUIVALENCE\n when 'themeOf'\n type = ContentConnection::THEME\n end\n connection = ContentConnection.new(con1, con2, type, @process)\n connection.setContext(doc)\n doc.add(connection)\n\n contents[annot['id']] = connection\n\n end\n end\n \n if result['modanns']\n result['modanns'].each do |annot|\n \n #in this case, it is a modification of an already existing content object (speculation/negation). \n con = contents[annot['object']]\n \n #get annotation type\n type = ContentConnection::UNSPECIFIED\n case annot['type']\n when 'Speculation'\n type = ContentConnection::SPECULATION\n when 'Negation'\n type = ContentConnection::NEGATION\n end\n connection = ContentConnection.new(con, nil, type, @process)\n connection.setContext(doc)\n doc.add(connection)\n\n contents[annot['id']] = connection\n\n end\n end\n \n doc\n end", "def process_alignment\n # init vars\n @names = []\n @seqs = []\n \n @alignment = \"-B #{@basename}.aln\"\n\n # import alignment file\n @content = IO.readlines(@infile).map {|line| line.chomp}\n \n #check alignment for gap-only columns\n remove_inserts\n \n #write query-file\n File.open(@infile, \"w\") do |file|\n file.write(\">#{@names[0]}\\n\")\n file.write(\"#{@seqs[0]}\\n\")\n end\n \n #write aln-file\n File.open(@basename + \".aln\", \"w\") do |file|\n @names.each_index do |num|\n file.write(\"Sequence#{num} \")\n file.write(\" \") if (num < 10)\n file.write(\" \") if (num < 100)\n file.write(\"#{@seqs[num]}\\n\")\n end\n end\n end", "def add_features(biosequence, gene_id, plus_target_positions, minus_target_positions)\n chr_num = biosequence.definition.match(/chromosome\\s(\\d)/)[1]\n chr_init_pos = biosequence.definition.match(/(\\d+)\\.\\.\\d+/)[1].to_i \n for target in plus_target_positions\n feature = Bio::Feature.new(\"targeting_vector\",\"#{target[0]}..#{target[1]}\")\n feature.append(Bio::Feature::Qualifier.new(\"seqid\", gene_id))\n feature.append(Bio::Feature::Qualifier.new(\"strand\", \"+\"))\n feature.append(Bio::Feature::Qualifier.new(\"chromosome\", chr_num))\n feature.append(Bio::Feature::Qualifier.new(\"chromosome_position\", chr_init_pos))\n biosequence.features << feature\n end\n for target in minus_target_positions\n feature = Bio::Feature.new(\"targeting_vector\",\"complement(#{target[0]}..#{target[1]})\")\n feature.append(Bio::Feature::Qualifier.new(\"seqid\", gene_id))\n feature.append(Bio::Feature::Qualifier.new(\"strand\", \"-\"))\n feature.append(Bio::Feature::Qualifier.new(\"chromosome\", chr_num))\n feature.append(Bio::Feature::Qualifier.new(\"chromosome_position\", chr_init_pos))\n biosequence.features << feature\n end \n return biosequence\nend", "def get_annotation_and_dna(record)\n mo = record.match(/^(LOCUS.*ORIGIN\\s*\\n)(.*)\\/\\/\\n/m)\n if mo\n annotation = mo[1]\n dna = mo[2]\n else\n STDERR.puts \"Cannot separate annotation from sequence info\"\n exit 1\n end\n dna.gsub!(/[\\s0-9]/,\"\") # clean the sequence of any whitespace or digits\n return annotation, dna\nend", "def annotation; @_sequence.annotation end", "def aon; end", "def annotate_GO(ids,db=\"uniprot\",field=\"dr\") #annotate with GO from uniprot cross refferences\n annotations=[]\n ids.each do |id|\n resp = InteractionNetwork.fetch(\"http://togows.org/entry/#{db}/#{id}/#{field}.json\")\n \n if resp\n res=JSON.parse(resp.body)[0]\n res[\"GO\"].each do |term| #dr format is hashes --> list of lists GO lists have three elements: GO-id,GOterm(class:definition)\n if term[1]=~/P:/ #P=biological processes class\n goid=term[0]\n goterm=term[1].match(/:(.+)/)[1]\n annotations << [goid,goterm]\n end\n end\n return annotations.uniq # some GO terms are repeated in this database\n end\n end \n end", "def write_polyA_chars(polyA,biosequence)\n \n polyA = polyA.split(\"\\t\")\n polyA_chr_pos = polyA[3].to_i\n polyA_strand = polyA[6]\n polyA_conditions = polyA[8].match(/conditions=(.+)/)[1]\n begin; chr_start = biosequence.definition.match(/(\\d+)\\.\\.\\d+/)[1].to_i; polyA_gene_pos = polyA_chr_pos - chr_start + 1; rescue; end\n \n for feature in biosequence.features\n if feature.feature == \"gene\" and feature.assoc[\"gene\"] == self.id\n begin gene = feature.position.scan(/(\\d+\\.\\.\\d+)/).map!{|x| x[0].split(\"..\")}[0].map(&:to_i); rescue; end\n end\n if feature.feature == \"mRNA\" and feature.assoc[\"gene\"] == self.id\n begin mrna = feature.position.scan(/(\\d+..\\d+)/).map!{|x| x[0].split(\"..\").map(&:to_i)}; min_mrna,max_mrna = mrna.flatten.minmax; rescue; end\n end\n if feature.feature == \"CDS\" and feature.assoc[\"gene\"] == self.id\n begin cds = feature.position.scan(/(\\d+..\\d+)/).map!{|x| x[0].split(\"..\").map(&:to_i)}; min_cds,max_cds = cds.flatten.minmax; rescue; end;\n end\n if feature.feature == \"misc_RNA\" and feature.assoc[\"gene\"] == self.id\n begin misc_rna = feature.position.scan(/(\\d+..\\d+)/).map!{|x| x[0].split(\"..\").map(&:to_i)}; rescue; end\n end\n end\n \n begin\n polyA_type = \"Intronic\"\n if polyA_gene_pos.between?(gene[0],gene[1]) == false\n polyA_type = \"Incorrectly annotated (the polyA site belongs to other gene than indicated in the GFF file)\"\n elsif polyA_gene_pos.between?(min_mrna,min_cds-1)\n polyA_type = \"5'UTR\" if polyA_strand == \"+\"\n polyA_type = \"3'UTR\" if polyA_strand == \"-\"\n elsif polyA_gene_pos.between?(max_cds+1,max_mrna)\n polyA_type = \"3'UTR\" if polyA_strand == \"+\"\n polyA_type = \"5'UTR\" if polyA_strand == \"-\"\n elsif\n for cd in cds\n if polyA_gene_pos.between?(cd[0],cd[1])\n polyA_type = \"Exonic\"\n end\n end\n elsif polyA_gene_pos.between?(misc_rna[0],misc_rna[1])\n for misc in misc_rna\n if polyA_gene_pos.between?(mis[0],misc[1])\n polyA_type = \"Exonic\"\n end\n end\n end\n rescue;polyA_type = \"Undefined\";end\n\n dict = {\"polyA_chr_pos\"=>polyA_chr_pos,\"polyA_gene_pos\"=>polyA_gene_pos,\"polyA_strand\"=>polyA_strand,\n \"polyA_type\"=>polyA_type,\"polyA_conditions\"=>polyA_conditions}\n self.polyA_info.append(dict)\n \n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /slow_things GET /slow_things.json
def index @slow_things = SlowThing.all respond_with @slow_things if stale? @slow_things, public: true end
[ "def find\n @thing = Thing.where(:thing, url[:thing]).where(:tid, url[:id]).last\n render json: @thing.object\n end", "def index\n @things = Thing.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @things }\n end\n end", "def show\n respond_with @slow_thing if stale? @slow_thing, public: true\n end", "def show\n @things_to_see = ThingsToSee.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @things_to_see }\n end\n end", "def api_get url_suffix\n url = URI::encode \"#{@@oauth_info[:api_url]}/gems/#{url_suffix}\"\n data = {:client_id => @@oauth_info[:client_id]}\n headers = {:Authorization => \"Bearer #{@access_token}\"}\n\n conn = get_conn url\n #Try request 3 times\n for i in 1..3\n res = conn.get(url, data, headers)\n if res.status == 200 then return JSON.parse(res.body) end\n sleep 1\n end\n raise OAuthSessionError, \"GET Failed. Status: #{res.status}. Body: #{res.body}\"\n end", "def show\n @thingy = Thingy.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @thingy }\n end\n end", "def index\n @slowlogexts = Slowlogext.get_all(params[:page])\n end", "def benchmark_rest_api\n @operation = '/api/rest/products'\n b_api = Benchmark.measure do\n (1..NUM_ITERATIONS).each do\n access_token = Marshal.load(session[:access_token])\n access_token.get(@operation).body\n end\n end\n @iterations = NUM_ITERATIONS\n @time = b_api.real\n end", "def index\n @more_power_ups_requests = MorePowerUpsRequest.pending\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @more_power_ups_requests }\n end\n end", "def show\n @thing = Thing.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @thing }\n end\n end", "def top_stories\n get('/topstories.json')\n end", "def get_difficulty\n # /wow/?a=get_difficulty\n Faraday.get(\"#{BASE_URL}&a=get_difficulty\").body\n end", "def index\n @gets = Get.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @gets }\n end\n end", "def index\n @totem_things = TotemThing.all\n end", "def create\n @slow_thing = SlowThing.new(slow_thing_params)\n\n respond_to do |format|\n if @slow_thing.save\n\n domain = URI(root_url)\n Net::HTTP.start(domain.host, domain.port) do |http|\n Rails.logger.debug \"purging #{domain}\"\n http.request( Purge.new(domain) )\n\n Rails.logger.debug \"purging #{slow_things_url}\"\n http.request( Purge.new(URI(slow_things_url)) )\n end\n\n format.html { redirect_to @slow_thing, notice: 'Slow thing was successfully created.' }\n format.json { render :show, status: :created, location: @slow_thing }\n else\n format.html { render :new }\n format.json { render json: @slow_thing.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @slow_jobs = SlowJob.all\n end", "def index\n @used_bikes = UsedBike.all\n\n render json: @used_bikes, each_serializer: Web::V1::UsedBikeSerializer\n end", "def get_client_throughput_time_series_data(args = {}) \n get(\"/clients.json/stats/throughput\", args)\nend", "def get_model_years_fast\n start = Time.now\n\n # open the json file of all cars and models\n json = JSON.parse(File.read(@all_cars_file))\n\n if json.nil?\n puts \"ERROR - could not find json file\"\n exit\n end\n\n # get all of the car ids with model ids\n # model_ids = json.map{|key, value| value['models'].keys}.flatten\n car_model_ids = json.map{|key, value| [key, value['models'].keys]}\n\n if car_model_ids.nil? || car_model_ids.length == 0\n puts \"ERROR - could not find model ids\"\n exit\n end\n\n puts \"- found #{car_model_ids.length} cars with a total of #{car_model_ids.map{|x| x[1]}.flatten.length} models\"\n\n hydra = Typhoeus::Hydra.new(max_concurrency: @max_concurrency)\n request = nil\n total_left_to_process = car_model_ids.length\n\n car_model_ids.each_with_index do |car, index|\n puts \"-------------------\"\n puts \"#{index} cars download so far in #{((Time.now-start)/60).round(2)} minutes\\n\\n\"\n\n car[1].each do |model_id|\n puts \"- car #{car[0]}, model #{model_id}\"\n request = Typhoeus::Request.new(\"#{@model_years_url}#{model_id}\",\n :headers=>{\"User-Agent\" => @user_agent}, followlocation: true, ssl_verifypeer: false, ssl_verifyhost: 0)\n\n request.on_complete do |response|\n # save years\n json[car[0]]['models'][model_id]['years'] = JSON.parse(response.response_body)\n\n # decrease counter of items to process\n total_left_to_process -= 1\n if total_left_to_process == 0\n puts \"TOTAL TIME TO DOWNLOAD = #{((Time.now-start)/60).round(2)} minutes\"\n\n elsif total_left_to_process % 10 == 0\n puts \"\\n\\n- #{total_left_to_process} files remain to download; time so far = #{((Time.now-start)/60).round(2)} minutes\\n\\n\"\n end\n end\n hydra.queue(request)\n end\n end\n\n hydra.run\n\n\n puts \"FINISHED DOWNLOAD DATA!!\"\n\n # save to file\n File.open(@all_cars_file_with_years, 'wb') { |file| file.write(JSON.generate(json)) }\n\n puts \"TOTAL TIME TO DOWNLOAD AND WRITE TO FILE = #{((Time.now-start)/60).round(2)} minutes\"\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /slow_things/1 GET /slow_things/1.json
def show respond_with @slow_thing if stale? @slow_thing, public: true end
[ "def index\n @slow_things = SlowThing.all\n respond_with @slow_things if stale? @slow_things, public: true\n end", "def find\n @thing = Thing.where(:thing, url[:thing]).where(:tid, url[:id]).last\n render json: @thing.object\n end", "def index\n @things = Thing.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @things }\n end\n end", "def show\n @things_to_see = ThingsToSee.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @things_to_see }\n end\n end", "def show\n @thing = Thing.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @thing }\n end\n end", "def show\n @thingy = Thingy.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @thingy }\n end\n end", "def api_get url_suffix\n url = URI::encode \"#{@@oauth_info[:api_url]}/gems/#{url_suffix}\"\n data = {:client_id => @@oauth_info[:client_id]}\n headers = {:Authorization => \"Bearer #{@access_token}\"}\n\n conn = get_conn url\n #Try request 3 times\n for i in 1..3\n res = conn.get(url, data, headers)\n if res.status == 200 then return JSON.parse(res.body) end\n sleep 1\n end\n raise OAuthSessionError, \"GET Failed. Status: #{res.status}. Body: #{res.body}\"\n end", "def show\n @tooth = Tooth.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tooth }\n end\n end", "def create\n @slow_thing = SlowThing.new(slow_thing_params)\n\n respond_to do |format|\n if @slow_thing.save\n\n domain = URI(root_url)\n Net::HTTP.start(domain.host, domain.port) do |http|\n Rails.logger.debug \"purging #{domain}\"\n http.request( Purge.new(domain) )\n\n Rails.logger.debug \"purging #{slow_things_url}\"\n http.request( Purge.new(URI(slow_things_url)) )\n end\n\n format.html { redirect_to @slow_thing, notice: 'Slow thing was successfully created.' }\n format.json { render :show, status: :created, location: @slow_thing }\n else\n format.html { render :new }\n format.json { render json: @slow_thing.errors, status: :unprocessable_entity }\n end\n end\n end", "def show\n @thot = Thot.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @thot }\n end\n end", "def index\n @gets = Get.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @gets }\n end\n end", "def show\n @fake_thing = FakeThing.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @fake_thing }\n end\n end", "def get_client_throughput_time_series_data(args = {}) \n get(\"/clients.json/stats/throughput\", args)\nend", "def show\n @things_to_do = ThingsToDo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @things_to_do }\n end\n end", "def show\n @microtask = Microtask.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @microtask }\n end\n end", "def get_random_pokemon(number)\n uri = URI(\"https://pokeapi.co/api/v2/pokemon/#{number}\")\n res = Net::HTTP.get_response(uri)\n JSON.parse(res.body)\nend", "def index\n @thingies = Thingie.all\n respond_to do |format|\n format.html\n format.json { render json: @thingies}\n format.xml { render xml: @thingies}\n end\n end", "def index\n @textures = Texture.find(:all, :limit => 20, :order=> 'created_at desc')\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @textures }\n end\n end", "def show\n @thing = current_user.things.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @thing }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /slow_things POST /slow_things.json
def create @slow_thing = SlowThing.new(slow_thing_params) respond_to do |format| if @slow_thing.save domain = URI(root_url) Net::HTTP.start(domain.host, domain.port) do |http| Rails.logger.debug "purging #{domain}" http.request( Purge.new(domain) ) Rails.logger.debug "purging #{slow_things_url}" http.request( Purge.new(URI(slow_things_url)) ) end format.html { redirect_to @slow_thing, notice: 'Slow thing was successfully created.' } format.json { render :show, status: :created, location: @slow_thing } else format.html { render :new } format.json { render json: @slow_thing.errors, status: :unprocessable_entity } end end end
[ "def long_slow_post(host, rate_limit, keep_alive) \r\n\trequest = \"POST /\" + (Digest::MD5.hexdigest(srand.to_s)) + \" HTTP/1.1\\r\\n\";\r\n request += \"Host: #{$host}\\r\\n\"\r\n request += \"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0\\r\\n\"\r\n request += \"Keep-Alive: #{keep_alive}\\r\\n\"\r\n request += \"Content-Length: 1000000000\\r\\n\";\r\n request += \"Content-Type: application/x-www-form-urlencoded\\r\\n\";\r\n request += \"Accept: *.*\\r\\n\";\r\n TCPSocket.open(host, 80) do |socket|\r\n\t\tsocket.write request\r\n\t\tloop {\r\n\t\t\tbegin \t\t\t\r\n\t\t\t\t# Writing one character to socket\r\n\t\t\t\tsocket.write \".\"\r\n\t\t\t\t# Printing request indicator to console\t\t\t\r\n\t\t\t\tprint '.'\r\n\t\t\t\t# Suspending this thread for 1 second to rate limit data sent to target\r\n\t\t\t\tsleep rate_limit\r\n\t\t\trescue\r\n\t\t\t\tbreak\r\n\t\t\tend\r\n\t\t}\t\r\n\tend\t\r\n\tsocket.close\r\nend", "def index\n @slow_things = SlowThing.all\n respond_with @slow_things if stale? @slow_things, public: true\n end", "def post(secret, batch)\n\n status, error = nil, nil\n remaining_retries = @retries\n backoff = @backoff\n\n begin\n res = @conn.post do |req|\n req.options[:timeout] = 8\n req.options[:open_timeout] = 3\n req.url(@path)\n req.body = AnalyticsRuby::JSON::dump :secret => secret, :batch => batch\n end\n status = res.status\n error = res.body[\"error\"]\n\n rescue Exception => err\n status = -1\n error = \"Connection error: #{err}\"\n unless (remaining_retries -=1).zero?\n sleep(backoff)\n retry\n end\n end\n\n AnalyticsRuby::Response.new status, error\n end", "def create\n @slow_job = SlowJob.new(slow_job_params)\n\n respond_to do |format|\n if @slow_job.save\n format.html { redirect_to @slow_job, notice: 'Slow job was successfully created.' }\n format.json { render :show, status: :created, location: @slow_job }\n else\n format.html { render :new }\n format.json { render json: @slow_job.errors, status: :unprocessable_entity }\n end\n end\n end", "def postReadings(info, state)\r\n params = {\r\n :device_id => info.deviceId,\r\n :sensor_data => [\r\n {\r\n :type => \"Temperature\",\r\n :value => state.temperature,\r\n :time => Time.now.to_i\r\n },\r\n {\r\n :type => \"Humidity\",\r\n :value => state.humidity,\r\n :time => Time.now.to_i\r\n }\r\n ]\r\n }\r\n res = apiPostJson(\"readings\", params)\r\n if res.status != 201\r\n $LOG.warn(\"Failed to post readings to backend! Status: #{res.status}, Response: #{res.body}\")\r\n end\r\n end", "def test_perf_post_hero()\n time = Benchmark.realtime do |bm|\n @heroes.post_hero(@dummy_record)\n end\n assert_operator time, :<=, @max_api_time\n end", "def post(rectype,attribs,http)\r\n endpoint=\"#{URL_PREFIX}/t#{rectype}s.json\"\r\n req = Net::HTTP::Post.new(endpoint,initheader = {'Content-Type' =>'application/json'})\r\n req.body = attribs.to_json\r\n http.request(req)\r\nend", "def better\n faraday = Faraday.new do\n # options\n _1.headers['User-Agent'] = 'HTTPDisk'\n _1.params.update(hello: 'world')\n _1.options.timeout = 10\n\n # middleware\n _1.use :cookie_jar\n _1.request :url_encoded\n _1.response :json\n _1.response :follow_redirects # must come before httpdisk\n\n # httpdisk\n _1.use :httpdisk\n\n # retries (must come after httpdisk)\n retry_options = {\n methods: %w[delete get head options patch post put trace],\n retry_statuses: (400..600).to_a,\n retry_if: ->(_env, _err) { true },\n }.freeze\n _1.request :retry, retry_options\n end\n\n # get w/ params\n 3.times { puts }\n response = faraday.get('http://httpbingo.org/get', { q: 'query' })\n puts response.env.url\n puts JSON.pretty_generate(response.body)\n\n # post w/ encoded form body\n 3.times { puts }\n response = faraday.post('http://httpbingo.org/post', 'a=1&b=2')\n puts response.env.url\n puts JSON.pretty_generate(response.body)\n\n # post w/ auto-encoded form hash\n 3.times { puts }\n response = faraday.post('http://httpbingo.org/post', { input: 'body' })\n puts response.env.url\n puts JSON.pretty_generate(response.body)\n end", "def test_no_request_retry_post\n response = Typhoeus.get(\"http://127.0.0.1:9442/backend_call_count?id=#{unique_test_id}\")\n assert_response_code(200, response)\n assert_equal(\"0\", response.body)\n\n response = Typhoeus.post(\"http://127.0.0.1:9080/api/delay-sec/20?backend_counter_id=#{unique_test_id}\", http_options)\n assert_response_code(504, response)\n\n # Ensure that the backend has only been called once.\n response = Typhoeus.get(\"http://127.0.0.1:9442/backend_call_count?id=#{unique_test_id}\")\n assert_response_code(200, response)\n assert_equal(\"1\", response.body)\n\n # Wait 5 seconds for any possible retry attempts that might be pending, and\n # then ensure the backend has still only been called once.\n sleep 5\n response = Typhoeus.get(\"http://127.0.0.1:9442/backend_call_count?id=#{unique_test_id}\")\n assert_response_code(200, response)\n assert_equal(\"1\", response.body)\n end", "def test_no_request_retry_post\n response = Typhoeus.get(\"http://127.0.0.1:9442/backend_call_count?id=#{unique_test_id}\")\n assert_response_code(200, response)\n assert_equal(\"0\", response.body)\n\n response = Typhoeus.post(\"http://127.0.0.1:9080/api/delay-sec/20?backend_counter_id=#{unique_test_id}\", http_options)\n assert_response_code(504, response)\n assert_match(\"Inactivity Timeout\", response.body)\n\n # Ensure that the backend has only been called once.\n response = Typhoeus.get(\"http://127.0.0.1:9442/backend_call_count?id=#{unique_test_id}\")\n assert_response_code(200, response)\n assert_equal(\"1\", response.body)\n\n # Wait 5 seconds for any possible retry attempts that might be pending, and\n # then ensure the backend has still only been called once.\n sleep 5\n response = Typhoeus.get(\"http://127.0.0.1:9442/backend_call_count?id=#{unique_test_id}\")\n assert_response_code(200, response)\n assert_equal(\"1\", response.body)\n end", "def post_spoonacular\n # %encode ingredients to url\n encoded_ingr = URI.escape(@translated_recipe[:ingredients_list])\n # post call block :\n url = URI(\"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/parseIngredients?includeNutrition=true\")\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Post.new(url)\n request[\"content-type\"] = \"application/x-www-form-urlencoded\"\n request[\"x-rapidapi-key\"] = ENV[\"X_RAPIDAPI_KEY\"]\n request[\"x-rapidapi-host\"] = \"spoonacular-recipe-food-nutrition-v1.p.rapidapi.com\"\n # body of the call with ingredients and servings\n request.body = \"ingredientList=#{encoded_ingr}&#{@recipe_hash[:servings]}\"\n # response\n response = http.request(request)\n end", "def create\n @heart = Heart.new heart_params_with_datetime\n split_heart_by_minute(@heart).each(&:save!)\n render :json => { :hello => \"world\" }.to_json\n rescue Exception => e\n render :json => { :error => e.message }.to_json\n end", "def create\n @slowlogext = Slowlogext.new(slowlogext_params)\n\n respond_to do |format|\n if @slowlogext.save\n format.html { redirect_to @slowlogext, notice: 'Slowlogext was successfully created.' }\n format.json { render :show, status: :created, location: @slowlogext }\n else\n format.html { render :new }\n format.json { render json: @slowlogext.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n \n #timestamp={{FellAsleepAt}}&total_sleep={{TotalTimeSleptInSeconds}}&deep={{TimeInDeepSleepSeconds}}&light={{TimeInLightSleepSeconds}}&awake={{TimeAwakeSeconds}}\n \n json_hash = Hash.new\n \n description = params[:description]\n \n timestamp = params[:timestamp]\n total_sleep_seconds = params[:total_sleep]\n deep_sleep_seconds = params[:deep]\n light_sleep_seconds = params[:light]\n awake_seconds = params[:awake]\n \n if timestamp.nil? || total_sleep_seconds.nil?\n \n puts 'timestamp is nil or total_sleep_seconds is nil :('\n \n else\n \n total_sleep = total_sleep_seconds / 60.0\n deep = deep_sleep_seconds / 60.0\n light = light_sleep_seconds / 60.0\n awake = awake_seconds / 60.0\n \n post_to_twitter = false\n post_to_facebook = false\n \n # FellAsleepAt is formatted: August 23, 2013 at 11:01PM\n # Convert to Runkeeper's preferred format: Sat, 1 Jan 2011 00:00:00\n timestamp_datetime = DateTime.parse(timestamp)\n formatted_timestamp = timestamp_datetime.strftime(\"%a, %d %b %Y %H:%M:%S\")\n \n json_hash['timestamp'] = formatted_timestamp\n json_hash['total_sleep'] = deep\n json_hash['deep'] = deep\n json_hash['light'] = light\n json_hash['awake'] = awake\n json_hash['post_to_twitter'] = post_to_twitter\n json_hash['post_to_facebook'] = post_to_facebook\n \n url = 'https://api.runkeeper.com/sleep'\n \n uri = URI.parse(url)\n \n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n request = Net::HTTP::Post.new(uri.request_uri)\n request[\"Authorization\"] = \"Bearer \" + RUNKEEPER_ACCESS_TOKEN\n request[\"Content-Type\"] = \"application/vnd.com.runkeeper.NewSleep+json\"\n request.body = json_hash.to_json\n \n response = http.request(request)\n \n puts response.body\n \n end\n \n @sleep = json_hash\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sleep }\n end\n \n end", "def create\n @thing = Thing.new(params[:thing])\n\n respond_to do |format|\n if @thing.save\n format.html { redirect_to @thing, :notice => 'Thing was successfully created.' }\n format.json { render :json => @thing, :status => :created, :location => @thing }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @thing.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create \n render json: Tuning.create(tuning_params)\n end", "def create\n @totem_thing = TotemThing.new(totem_thing_params)\n\n respond_to do |format|\n if @totem_thing.save\n format.html { redirect_to @totem_thing, notice: 'Totem thing was successfully created.' }\n format.json { render action: 'show', status: :created, location: @totem_thing }\n else\n format.html { render action: 'new' }\n format.json { render json: @totem_thing.errors, status: :unprocessable_entity }\n end\n end\n end", "def post *args\n make_request :post, *args\n end", "def perform_optimization_actions_on_arrays(args = {}) \n post(\"/arrays.json/actions/optimize\", args)\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /slow_things/1 PATCH/PUT /slow_things/1.json
def update respond_to do |format| if @slow_thing.update(slow_thing_params) domain = URI(root_url) Net::HTTP.start(domain.host, domain.port) do |http| Rails.logger.debug "purging #{domain}" http.request( Purge.new(domain) ) Rails.logger.debug "purging #{slow_things_url}" http.request( Purge.new(URI(slow_things_url)) ) Rails.logger.debug "purging #{slow_thing_url(@slow_thing)}" http.request( Purge.new(URI(slow_thing_url(@slow_thing))) ) end format.html { redirect_to @slow_thing, notice: 'Slow thing was successfully updated.' } format.json { render :show, status: :ok, location: @slow_thing } else format.html { render :edit } format.json { render json: @slow_thing.errors, status: :unprocessable_entity } end end end
[ "def patch *args\n make_request :patch, *args\n end", "def update\n @thing = Thing.find(params[:id])\n\n respond_to do |format|\n if @thing.update_attributes(params[:thing])\n format.html { redirect_to things_path, notice: 'Your thing was successfully updated!' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @thing.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @fake_thing = FakeThing.find(params[:id])\n\n respond_to do |format|\n if @fake_thing.update_attributes(params[:fake_thing])\n format.html { redirect_to @fake_thing, notice: 'Fake thing was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fake_thing.errors, status: :unprocessable_entity }\n end\n end\n end", "def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end", "def update\n spice = Spice.find_by(id: params[:id])\n spice.update(spice_params)\n render json: spice\nend", "def update\n @thingy = Thingy.find(params[:id])\n\n respond_to do |format|\n if @thingy.update_attributes(params[:thingy])\n format.html { redirect_to @thingy, notice: 'Thingy was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @thingy.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(path, params: {}, headers: {})\n request_json :patch, path, params, headers\n end", "def put(id, json)\n with_endpoint do |endpoint|\n url = [endpoint, @resource_name, id].compact.join('/')\n url += \"/\" \n return HTTParty.put(url, :body => json, :timeout => 4, :headers => { 'Content-Type' => 'application/json' })\n end\n end", "def update\n respond_to do |format|\n if @fictional_thing.update(fictional_thing_params)\n format.html { redirect_to @fictional_thing, notice: 'Fictional thing was successfully updated.' }\n format.json { render :show, status: :ok, location: @fictional_thing }\n else\n format.html { render :edit }\n format.json { render json: @fictional_thing.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(path, options = {}, &block)\n perform_request Net::HTTP::Patch, path, options, &block\n end", "def patch(data, options={})\n raise NotImplementedError, \"We only patchs to singular resources.\" if count > 1\n first.patch(data, options)\n end", "def update\n respond_to do |format|\n if @totem_thing.update(totem_thing_params)\n format.html { redirect_to @totem_thing, notice: 'Totem thing was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @totem_thing.errors, status: :unprocessable_entity }\n end\n end\n end", "def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\n end", "def update\n @stuff = Stuff.find(params[:id])\n\n respond_to do |format|\n if @stuff.update_attributes(params[:stuff])\n format.html { redirect_to @stuff, :notice => 'Stuff was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @stuff.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def _update_item(http, headers, path, body, name)\n resp = retry_request(http, \"PATCH\", path, body, headers)\n if resp.is_a?(Net::HTTPOK)\n Chef::Log.info(\"Updated keystone item '#{name}'\")\n else\n _raise_error(resp, \"Unable to update item '#{name}'\", \"_update_item\")\n end\nend", "def update\n respond_to do |format|\n if @happy_thing.update(happy_thing_params)\n format.html { redirect_to @happy_thing, notice: 'Happy thing was successfully updated.' }\n format.json { render :show, status: :ok, location: @happy_thing }\n else\n format.html { render :edit }\n format.json { render json: @happy_thing.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @things_to_do = ThingsToDo.find(params[:id])\n\n respond_to do |format|\n if @things_to_do.update_attributes(params[:things_to_do])\n format.html { redirect_to @things_to_do, notice: 'Things to do was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @things_to_do.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @thing_to_do.update(thing_to_do_params)\n format.html { redirect_to @thing_to_do, notice: 'Thing to do was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @thing_to_do.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /slow_things/1 DELETE /slow_things/1.json
def destroy @slow_thing.destroy respond_to do |format| format.html { redirect_to slow_things_url, notice: 'Slow thing was successfully destroyed.' } format.json { head :no_content } end end
[ "def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end", "def destroy\n # delete a specific thing\n end", "def destroy\n @thing = Thing.find(params[:id])\n @thing.destroy\n\n respond_to do |format|\n format.html { redirect_to things_url }\n format.json { head :ok }\n end\n end", "def destroy\n @thing = Thing.find(params[:id])\n @thing.destroy\n\n respond_to do |format|\n format.html { redirect_to things_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @fake_thing = FakeThing.find(params[:id])\n @fake_thing.destroy\n\n respond_to do |format|\n format.html { redirect_to fake_things_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @json.destroy\n\n head :no_content\n end", "def destroy\n @thingy = Thingy.find(params[:id])\n @thingy.destroy\n\n respond_to do |format|\n format.html { redirect_to thingies_url }\n format.json { head :no_content }\n end\n end", "def test_trying_to_delete_non_item\n r = delete \"/groceries\", name: \"not a thing\"\n assert_equal 404, r.status\n end", "def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def destroy\n @totem_thing.destroy\n respond_to do |format|\n format.html { redirect_to totem_things_url }\n format.json { head :no_content }\n end\n end", "def delete_floor_plan(args = {}) \n delete(\"/files.json/floorplan/images\", args)\nend", "def delete endpoint\n do_request :delete, endpoint\n end", "def delete(path, params={}); make_request(:delete, host, port, path, params); end", "def test_delete_not_exist_metric\n not_exist_id = '10000'\n output = `curl -X DELETE http://localhost:8080/metrics/metrics/#{not_exist_id}`\n assert_match \"<html>\", output, \"TEST 5: delete not existing metric - FAILED\"\n end", "def destroy\n @tiny = Tiny.find(params[:id])\n @tiny.destroy\n\n respond_to do |format|\n format.html { redirect_to tinies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @thot = Thot.find(params[:id])\n @thot.destroy\n\n respond_to do |format|\n format.html { redirect_to thots_url }\n format.json { head :no_content }\n end\n end", "def cmd_delete argv\n setup argv\n uuid = @hash['uuid']\n response = @api.delete(uuid)\n msg response\n return response\n end", "def destroy\n @stuff = Stuff.find(params[:id])\n @stuff.destroy\n\n respond_to do |format|\n format.html { redirect_to stuffs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tiny = Tiny.find(params[:id])\n @tiny.destroy\n respond_to do |format|\n format.html { redirect_to tinies_url }\n format.json { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an array of strings, each representing a line Draws a box around the lines, and returns a new array padding may be provided
def box_it(array_of_lines, padding = 1, _box_colour = :bc_cyan) max_length = max_box_line_length(array_of_lines) pad_string = "\s" * padding box_lines = [ # Set the top box line "#{BOX_TOP_LEFT}#{BOX_HORIZONTAL_LINE * (max_length + (padding + 1))}#{BOX_TOP_RIGHT}" ] array_of_lines.each do |line| line_length = line.sanitize.length box_lines << "#{BOX_SIDE}#{pad_string}" + line.to_s + "#{"\s" * (max_length - line_length)}#{pad_string}#{BOX_SIDE}" end # Set the bottom box line box_lines << "#{BOX_BOTTOM_LEFT}#{BOX_HORIZONTAL_LINE * (max_length + (padding + 1))}#{BOX_BOTTOM_RIGHT}" box_lines end
[ "def pad_line(text)\n return text if text.empty? || padding.empty?\n\n padding_left = ' ' * padding[3].to_i\n padding_right = ' ' * padding[1].to_i\n text.map! do |part|\n part.insert(0, padding_left).insert(-1, padding_right)\n end\n end", "def pad_multi_line(text)\n text.split(\"\\n\", -1).map { |part| pad_around(part) }.join(\"\\n\")\n end", "def pad_two_dimensionnal_array(array)\n column_count = array[0].length\n longests = Array.new(column_count, 0)\n array.each do |line|\n line.each_with_index do |cell, column|\n cell = '' if cell.nil?\n length = cell.size\n longest = longests[column]\n longests[column] = length if length > longest\n end\n end\n\n padded_array = array.map do |line|\n line.map.with_index do |cell, index|\n cell = '' if cell.nil?\n cell.ljust(longests[index])\n end\n end\n padded_array\n end", "def break_text_with_image(width, textarray, draw)\n tokens = textarray.flat_map{ |x| x.respond_to?(:split) ? x.split(/ /) : x }\n tokens = tokens.flat_map{ |x| x.respond_to?(:split) ? x.split(/(?<=\\n)/) : x }\n\n result = []\n line = []\n linelength = 0\n\n tokens.each_with_index do |item, i|\n itemlength = item.class == Image ?\n item.columns : draw.get_type_metrics(item + ' ').width\n\n if (line.empty?)\n line << item\n else\n if (width != 0 && itemlength + linelength > width)\n result << line\n line = [item]\n linelength = 0\n else\n t = line.pop\n\n if (t.class != Image)\n t += ' '\n elsif (item.class != Image)\n item = ' ' + item\n end\n\n if (t.class == Image or item.class == Image)\n line << t << item\n else\n line << t + item\n end\n end\n end\n\n if (item.class != Image and item.include?(\"\\n\"))\n line[0].sub!(\"\\n\", '')\n result << line\n line = []\n linelength = 0\n next\n end\n\n linelength += itemlength\n end\n\n unless (line.empty?)\n result << line\n end\n\n return result\n end", "def block_trim_padding( lines ) # :doc:\n pad = nil\n lines\n .reject { |l| l =~ /^\\s*$/ } #blank lines\n .map do |line|\n line = line.dup\n unless pad && line.gsub!(/^(\\s{,#{pad}})/, '')\n prior = line.length\n line.gsub!(/^(\\s*)/, '')\n pad = prior - line.length\n end\n line.rstrip!\n line\n end\n end", "def format_content(lines, width)\n return [] if lines.empty?\n\n formatted = lines.each_with_object([]) do |line, acc|\n wrapped = Strings::Wrap.wrap(line, width, separator: @sep)\n acc << Strings::Align.align(wrapped, width,\n direction: @align,\n separator: @sep)\n end.join(@sep)\n\n Strings::Pad.pad(formatted, @padding, separator: @sep).split(@sep)\n end", "def lPad(thePad = '')\n theCopy = TextRect.new(@theLines)\n theCopy.lPad!(thePad)\n end", "def print_in_box(text)\n line = '-'\n lines = []\n text.size.times { lines << line }\n space = ' '\n spaces = []\n text.size.times { spaces << space }\n puts \"+#{lines.join}+\"\n puts \"|#{spaces.join}|\"\n puts \"|#{text}|\"\n puts \"|#{spaces.join}|\"\n puts \"+#{lines.join}+\"\nend", "def box msgs, box_char=@box_char, box_size=@box_size\n self.liner box_char, box_size\n [msgs].flatten.each do |text|\n text.each_line do |line|\n self.<< '# ' + box_char + ' ' + line.chomp + \"\\n\"\n end\n end\n self.liner box_char, box_size\n end", "def adjust_spacing(line)\n joined_line = line.join(' ')\n\n unless joined_line.length == @line_width\n # Find number of spaces needed\n spaces = (@line_width - joined_line.length)\n\n # Take the last word from the array as we don't want to have spaces following it\n last_word = line.pop\n\n # Add spaces to the random words from the array\n spaces.times do\n random_word = line.sample\n line.map! do |word|\n if word == random_word\n word << ' '\n break\n else\n word\n end\n end\n end\n\n # Add the last word to the concatenated list and the return the text line\n joined_line = line.push(last_word).join(' ')\n end\n joined_line\n end", "def align(rows)\n cols = rows.first.length\n lengths = [0] * cols\n\n cols.times do |i|\n rows.each do |r|\n lengths[i] = r[i].length if r[i] && r[i].length > lengths[i]\n end\n end\n\n rows.map do |r|\n \"# #{r.zip(lengths).map{|c, l| c.to_s.ljust(l).gsub(\"\\n\", \"\\n# \")}.join(' | ')}\".strip\n end\n end", "def split_into_lines(rect) \n\t\tbottom_right = Point.new(rect.location.x + rect.width, rect.location.y)\n\t\ttop_right = Point.new(rect.location.x + rect.width, rect.location.y + rect.height)\n\t\ttop_left = Point.new(rect.location.x, rect.location.y + rect.height)\n\n\t\treturn [[rect.location, top_left],\n\t\t\t\t[rect.location, bottom_right],\n\t\t\t\t[top_left, top_right],\n\t\t\t\t[bottom_right, top_right]]\n\tend", "def wrap(line,pad_length=0,line_length=nil)\n line ||= ''\n if line_length.nil?\n line_length = Terminal.instance.size[0]\n end\n line_padding = sprintf(\"%#{pad_length}s\",'')\n paragraphs = line.split(\"\\n\\n\").map { |l| l.chomp }.reject { |l| l.empty? }\n wrapped = paragraphs.map do |para|\n paragraph_lines(para, line_length - pad_length).join(\"\\n#{line_padding}\")\n end\n wrapped.join(\"\\n\\n#{line_padding}\")\n end", "def split_multiline(rect, text, multiline_mode=0)\n return [] if text == nil\n\n case multiline_mode\n when 0\n # Draw first line normally\n x_adjustment = 0\n when 1\n # Draw first line with a specific x and restart to 0 after\n x_adjustment = rect.x\n when 2\n # Draw first line with a specific height and restart to text height after\n x_adjustment = 0\n when 3\n # Mixes mode 1 and 2\n x_adjustment = rect.x\n else\n # Does nothing\n end\n \n textblocks = text.split(CORE_CONFIG::END_LINE_CHARACTER)\n \n lines = []\n for block in textblocks\n length = get_text_width(block)\n \n if (length >= (rect.width-x_adjustment))\n multilineText = format_multiline(rect, block, x_adjustment)\n lines.concat(multilineText.split(CORE_CONFIG::END_LINE_CHARACTER))\n else\n lines.push(block)\n end\n end\n \n return lines\n end", "def paddings(number_size)\n left_padding = internal_padding = right_padding = ''\n if padded?\n left_padding_size, internal_padding_size, right_padding_size = padding.padding_sizes(number_size)\n right_padding_size = right_padding_size/fill.size\n right_padding = fill*right_padding_size\n d = right_padding_size - right_padding.size\n left_padding_size = (left_padding_size + d)/fill.size\n left_padding = fill*left_padding_size\n internal_padding_size = internal_padding_size/fill.size\n internal_padding = fill*internal_padding_size\n end\n [left_padding, internal_padding, right_padding ]\n end", "def justify(array, max_length=16)\n words_per_line = 0\n character_count = 0\n per_line = []\n\n array.each_with_index do |word, index|\n if (character_count + word.length) > max_length\n per_line << words_per_line\n character_count = 0\n words_per_line = 0\n end\n character_count += word.length + 1\n words_per_line += 1\n end\n\n per_line << array.size - per_line.inject(:+) if (array.size - per_line.inject(:+)) != 1\n\n result = []\n number_of_lines = per_line.size\n\n 0.upto(number_of_lines - 1) do |i|\n line = array.first(per_line[i])\n array = array.drop(per_line[i])\n\n num_of_chars = line.join(\" \").size\n num_of_chars_to_fill = max_length - num_of_chars\n num_of_words = per_line[i]\n num_of_words == 1 ? num_of_spaces = 1 : num_of_spaces = (num_of_words - 1)\n\n if num_of_chars_to_fill % num_of_spaces == 0\n 0.upto(num_of_spaces-1) do |space|\n line[space] << \" \" * (num_of_chars_to_fill/num_of_spaces)\n ##will only occur when number of chars to fill is less than the num of spaces.\n if num_of_chars_to_fill > 0 && num_of_chars_to_fill/num_of_spaces == 0\n ## Add the num_of_chars_to_fill to the most lefterly spaces.\n count = 0\n until count == num_of_chars_to_fill\n line[count] << \" \"\n count += 1\n end\n end\n end\n elsif num_of_chars_to_fill % num_of_spaces != 0\n if num_of_chars_to_fill == 1\n line[0] << \" \"\n elsif num_of_chars_to_fill > 1\n 0.upto(num_of_spaces-1) do |space|\n line[space] << \" \" * (num_of_chars_to_fill/num_of_spaces)\n line[0] << \" \"\n if num_of_chars_to_fill > 0 && num_of_chars_to_fill/num_of_spaces == 0\n ## Add the num_of_chars_to_fill to the most lefterly spaces.\n ## Count == as we have already placed one.\n count = 1\n until count == num_of_chars_to_fill\n line[count] << \" \"\n count += 1\n end\n end\n end\n end\n end\n line = line.join(\" \")\n result << line\n end\n\n unless array.empty?\n last_line = array[0] + (\" \" * (max_length - array[0].size))\n result << last_line\n end\n\n puts result\nend", "def wrap array\n return super unless array[0][:linenum] # sanity check\n initialize_wrap array\n @line_wrap.extend SourceLineWrap\n highlight_line = stop = nil\n unconsumed = @arranger.unconsumed\n until stop\n if (first_fragment = unconsumed[0])[:linenum]\n linenum_text = first_fragment[:text]\n linenum_spacer ||= { text: (NoBreakSpace.encode linenum_text.encoding) + (' ' * (linenum_text.length - 1)), linenum: :spacer }\n highlight_line = (second_fragment = unconsumed[1])[:highlight] ? second_fragment.merge : nil\n else # wrapped line\n first_fragment[:text] = first_fragment[:text].lstrip\n @arranger.unconsumed.unshift highlight_line if highlight_line\n @arranger.unconsumed.unshift linenum_spacer.merge\n end\n @line_wrap.wrap_line \\\n document: @document,\n kerning: @kerning,\n width: @width,\n arranger: @arranger,\n disable_wrap_by_char: @disable_wrap_by_char\n if enough_height_for_this_line?\n move_baseline_down\n print_line\n stop = @arranger.finished?\n else\n stop = true\n end\n end\n @text = @printed_lines.join ?\\n\n @everything_printed = @arranger.finished?\n @arranger.unconsumed\n end", "def indent_lines(lines, indent: 6)\n lines.map { |line| (' ' * indent) + line }.join(\"\\n\")\n end", "def rPad!(thePad = '')\n len = @theLines.length\n padArray = Array.new(len, thePad)\n padTR = TextRect.new(padArray)\n self.join!(padTR)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MUST BE CALLED BY User.deliver_inactive_notification!
def inactive_notification(user) setup_email(user) @subject += subject_from_sym :inactive_notification @body[:name] = user.full_name || 'Eternos user' @body[:link] = account_setup_url(:id => user.perishable_token) add_category_header "Inactive Account Notice" end
[ "def inactive\n\t\t# Pick a random user and temporary set his status to 'inactive'\n\t\tuser = User.first\n\t\tuser.status = 'inactive'\n\t\tUserStatusMailer.set_mail(user)\n\tend", "def atest_ID_25861_suspended_user_notification()\n # Need suspended account\n end", "def inactive_message\n self.status == USER_STATUS_DELETED ? :user_deleted : super\n end", "def deliver_signup_notification\n if !self.email.blank?\n Mailers::User.deliver_signup_notification(self) if self.recently_activated?\n end\n end", "def inactive_message\n login_email = multi_email.login_email_record\n\n if login_email && !login_email.primary? && !login_email.confirmed?\n :unconfirmed\n else\n super\n end\n end", "def inactive_message\n deactivated_at.present? ? 'Account has been deactivated' : super\n end", "def inactive_message\n isActive ? super : :inative_account\n end", "def deliver_activation\n if self.state != \"active\" && !self.email.blank?\n Mailers::User.deliver_activation(self) unless !!skip_activation\n end\n end", "def remove_upcoming_registrations_if_inactive\n remove_upcoming_registrations if !self.active \n end", "def users_to_notify\n super\n end", "def inactive_message\n !disabled ? super : :account_has_been_disabled\n end", "def notify_unlocked\n ::Notification.create!(\n from: user,\n user_id: user_id,\n seen: false,\n target: self,\n kind: :ACHIEVEMENT_UNLOCKED\n )\n end", "def inactive_message\n\t\t\"Sorry, this account not active by admin. Will Contact you soon.\"\n\tend", "def resend_activation_emails\n User.where.not(person: nil).where.not(activation_code: nil).each do |user|\n if user.person\n logs = user.person.activation_email_logs\n if logs.count < MAX_ACTIVATION_EMAILS && (logs.empty? || logs.last.created_at < RESEND_ACTIVATION_EMAIL_DELAY.ago)\n Mailer.activation_request(user).deliver_later\n MessageLog.log_activation_email(user.person)\n end\n else\n Rails.logger.info(\"User with invalid person - #{user.id}\")\n end \n end\n end", "def skip_email_changed_notification!; end", "def skip_confirmation_notification!; end", "def inactive_message\n 'Account is disabled'\n end", "def disable_all_notifications\r\n @user = current_user\r\n\r\n return if show_session_user_on_get\r\n\r\n if @params['disable'] == \"on\"\r\n @user.set_att(UserAttribute::ATT_REMIND_BY_EMAIL, 0)\r\n end\r\n end", "def send_devise_pending_notifications\n devise_pending_notifications.each do |pair|\n DeviseBackgrounder.send(pair[0], self, pair[1]).deliver\n end\n @devise_pending_notifications = []\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MUST BE CALLED BY User.deliver_account_setup_reminder!
def account_setup_reminder(user) setup_email(user) @subject = subject_from_sym :account_setup_reminder @body[:name] = user.full_name @body[:setup_url] = account_setup_url(:id => user.perishable_token, :ref => 'asr1') add_category_header "Account Setup Reminder" end
[ "def handle_password_reminder_setup\n Users::Reminders.password_expiration(self) if @set_reminder && is_a?(User)\n end", "def deliver_signup_notification\n if !self.email.blank?\n Mailers::User.deliver_signup_notification(self) if self.recently_activated?\n end\n end", "def send_signup_notification\n deliver_activation_email(:signup, :subject => (MaSA[:activation_subject] || \"Please Activate Your Account\") )\n end", "def setup_email_account\n email_accounts.create!(email: email, primary: true, confirmed: !confirmed_at.blank?)\n end", "def post_creation_setup!(model:, **)\n model.bookings.build paymentplan: Paymentplan.premium,\n type: 'TrialBooking',\n valid_until: 1.month.from_now,\n is_current: true\n vats_from_germany = VatCountry.find_by(country: 'DE')\n model.vat_countries << vats_from_germany\n model.default_vat = Vat.find_by(vat_country: vats_from_germany, key: 'regular_vat')\n model.default_currency_iso_code = 'EUR'\n model.subdomain = model.accountnumber.to_s\n # copy user's email\n model.email = model.creator.email\n model.save\n end", "def send_signup_notification\n deliver_email(:signup, :subject => (MaSM[:activation_subject] || \"Please Activate Your Account\") )\n end", "def setup_email\n self.email = self.user.email if self.user\n end", "def jumpstart_stalled_account\n if user.last_email_at && user.last_email_at < 24.hours.ago\n update_user(:last_uid => nil)\n end\n end", "def send_on_create_confirmation_instructions; end", "def send_primary_reminder_email\n UserMailer.primary_reminder_email(self).deliver_now\n end", "def send_mail_user_make_booking #DZF this always send a mail to supplier\n \tSupplierMailer.user_make_booking_email(self).deliver unless self.user_account.blank?\n end", "def account_setup_action\n return [:complete] if account_setup?\n return [:checkins, :first]\n end", "def send_post_registration_email\n IdealsMailer.account_registered(self).deliver_now\n end", "def resend_activation_email!\n self.send_activation_needed_email!\n end", "def check_if_needs_approval\r\n self.suspended_at = Time.now if Setting.user_signup == :needs_approval && !self.admin\r\n end", "def maybe_ready_for_reminder_email\n ama_maybe_ready + legacy_maybe_ready\n end", "def send_activation_email\n DoctorMailer.account_activation(self).deliver_now\n end", "def save_with_activation\n self.make_activation_code\n @needs_signup_email = true\n self.save\n end", "def force_setup_complete!\n self.setup = [:profile, :invite_team_members, :intro_video]\n self.active = true\n self.save\n c = 0\n self.team_members.each do |u|\n u.setup_complete!\n c += 1\n end\n true\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current status of the state. This includes: Player status Room description Room's treasure Room's monster
def status output = StringIO.new output << @game.player.to_s output << "\n" output << "#{@game.current_room_model.description}\n" treasure = @game.current_room_model.treasure output << "\nThere is treasure here worth $#{treasure}.\n" if treasure && treasure > 0 monster = @game.current_room_model.monster if monster output << "\nDANGER... THERE IS A MONSTER HERE....\n\n" output << "#{@game.current_room_model.monster}\n\n" end if @game.current_room_model.name != "Exit" output << "\nWhat do you want to do? " end output.string end
[ "def status\n monster = @game.current_room_model.monster\n return unless monster\n\n weapons = @game.player.weapons\n output = \"With a ferocious sight the Wild #{monster.name} wants to fight! \\n\"\n output << \"Be careful it's ferocity level is #{monster.ferocity}\\n\"\n weapons.each_with_index do |weapon, i|\n output << \"#{i + 1} - #{weapon}\\n\"\n end\n\n output\n end", "def status\n\t\tif @status_ == :victory\n\t\t\treturn \"You Win!\"\n\t\telsif @status_ == :loss\n\t\t\treturn \"You Loose\"\n\t\telsif @status_ == :in_progress\n\t\t\treturn \"Still playing\"\n\t\tend\n\tend", "def status\n has_torch = @game.player.has_torch?\n return \"You can't see anything, you must purchase a torch\\n\" unless has_torch\n\n output = StringIO.new\n output << @game.player.to_s\n output << \"\\n\"\n\n output << \"#{@game.current_room_model.description}\\n\"\n\n treasure = @game.current_room_model.treasure\n output << \"\\nThere is treasure here worth $#{treasure}.\\n\" if treasure && treasure > 0\n\n monster = @game.current_room_model.monster\n if monster\n output << \"\\nDANGER... THERE IS A MONSTER HERE....\\n\\n\"\n output << \"#{@game.current_room_model.monster}\\n\\n\"\n end\n\n if @game.current_room_model.name != \"Exit\"\n output << \"\\nWhat do you want to do? \"\n end\n\n output.string\n end", "def current_status\n case status\n when NOT_STARTED\n return 'Game not started yet'.freeze\n when RUNNING\n return 'Game is running'.freeze\n when WIN\n return 'Game is won'.freeze\n when DRAWN\n return 'Game is drawn'.freeze\n when ABANDONED\n return 'Game is abandoned'.freeze\n end\n end", "def status\n @status.state\n end", "def get_status\n print \"Here is the door's status...\n Open: #{self.is_open}\n Unlocked: #{self.is_unlocked}\n Inscription: #{self.inscription}\"\n end", "def equipment_status\n\t\n\t\tstat = Status.where(:name => \"Working\").first\n\t\t\n\t\tequipment.each do |equipment|\n\t\t\tif( equipment.status.name == \"Broken\")\n\t\t\t\treturn equipment.status\n\t\t\telsif (equipment.status.name == \"Needs Attention\")\n\t\t\t\tstat = equipment.status\n\t\t\tend\n\t\tend\n\t\treturn stat\n end", "def status\n {\n 'device' => :ok,\n 'no device' => :dead,\n 'offline' => :offline\n }[@state]\n end", "def status\n {\n 'device' => :ok,\n 'no device' => :dead,\n 'offline' => :offline\n }[@state]\n end", "def status\n return :winner if winner?\n return :tie if tie?\n 'Game in Progress'\n end", "def status\r\n return status_from_registry if @use_registry_for_status\r\n\r\n first_line = Advfirewall.call(\"show currentprofile state\", read: true).first_line\r\n\r\n if first_line =~ /ON\\z/\r\n :on\r\n elsif first_line =~ /OFF\\z/\r\n :off\r\n else\r\n @use_registry_for_status = true\r\n status_from_registry\r\n end\r\n end", "def status\n short_state_str=SHORT_VM_STATES[state_str]\n\n if short_state_str=='actv'\n short_state_str=SHORT_LCM_STATES[lcm_state_str]\n end\n\n short_state_str\n end", "def status\n short_state_str=SHORT_VM_STATES[state_str]\n\n if short_state_str==\"actv\"\n short_state_str=SHORT_LCM_STATES[lcm_state_str]\n end\n\n short_state_str\n end", "def show_status\r\n puts \"Status for room #{id}:\"\r\n if @contents.empty?\r\n puts \" The room is empty.\"\r\n else\r\n puts \" Contents: #{sorted_contents.join(', ')}\"\r\n end\r\n if @exits.empty?\r\n puts \" No exits.\"\r\n else\r\n doors = []\r\n doors << 'north' if @exits[:north]\r\n doors << 'south' if @exits[:south]\r\n doors << 'east' if @exits[:east]\r\n doors << 'west' if @exits[:west]\r\n puts \" There are exits to the #{doors.join(', ')}.\"\r\n end\r\n end", "def get_Status()\n \t return @outputs[\"Status\"]\n \tend", "def player_state\n @ole.PlayerState\n end", "def get_status\n case snmp_get('1.3.6.1.2.1.25.3.5.1.1.1')\n when 1\n return 'Other'\n when 3\n return 'Idle'\n when 4\n return 'Printing'\n when 5\n return 'Warmup'\n else\n return 'Unknown'\n end\n end", "def status\n\t\t\tcase @status\n\t\t\twhen :available\n\t\t\t\t\"This book is availbale for check_out\"\n\t\t\twhen :checked_out\n\t\t\t\t\"This book is checked out by #{@check_out_to}on #{@out_time} until #{@due}\"\n\t\t\twhen :overdue\n\t\t\t\t\"<user> checked out this book on <out_time and it was due on #{@due} but they kept it for themselves.\"\n\t\t\twhen :lost\n\t\t\t\t\"Some idiot lost this book\"\n\t\t\tend\n\tend", "def status\n short_state_str=SHORT_VM_STATES[state_str]\n\n if short_state_str==\"actv\"\n short_state_str=SHORT_LCM_STATES[lcm_state_str]\n end\n\n short_state_str\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles a command for this state. +command+ must be a symbol Possible commands: :north : Moves you to north :south : Moves you to south :east : Moves you to east :west : Moves you to west :up : Moves you to up :down : Moves you to down :tally : Shows you the current score and number of monsters killed :run : Tries to run from the current room :magic : Uses the player's Amulet to randomly move to another room :pick_up : Picks the room's treasure if there is any :fight : Fights with the monster in the room :consume : Eats food to gain strength
def handle(command) puts "Doing #{command}..." method = command case command when :north then method = :move when :south then method = :move when :east then method = :move when :west then method = :move when :up then method = :move when :down then method = :move end output = "" if method == :move output << self.send(method, command) else output << self.send(method) end output << "\n" output << self.status output end
[ "def handle(command)\n\n output = \"\"\n if @eating_food\n food_quantities = {:zero => 0, :one => 1, :two => 2, :three => 3, :four => 4, :five => 5, :six => 6,\n :seven => 7, :eight => 8, :nine => 9, :ten => 10}\n units_of_food = food_quantities[command]\n food = @game.player.food\n if units_of_food > food\n output << \"\\n*** You do not have enough food, try again ***\\n\"\n else\n @game.player.strength += 5*units_of_food\n @game.player.food -= units_of_food\n output << \"You have consumed #{units_of_food} number of foods\\n\"\n end\n @eating_food = false\n output << self.status\n else\n method = command\n case command\n when :north then method = :move\n when :south then method = :move\n when :east then method = :move\n when :west then method = :move\n when :up then method = :move\n when :down then method = :move\n end\n\n output = \"\"\n if method == :move\n output << self.send(method, command)\n output << self.status\n @is_moving = false\n else\n if @is_moving\n output << \"Don't waste time on that! You must run!!! \\n\"\n output << @game.current_room_model.description\n else\n output << self.send(method)\n end\n\n end\n\n end\n output << \"\\n\"\n output\n end", "def handle_command(command)\n # TODO: add new param -> after state to specify a transition to go to - can't use last state because it's aready used... - maybe its not needed anymore\n log.debug \"got #{registered_as_type} command: #{command}\"\n current_state = params[:state]\n params.merge!(command)\n if command[:state]\n fire_state_event(command[:state].to_sym) if command[:state] != current_state\n end\n end", "def command(command, value = nil)\n value ||= 7 # long enough to turn the launcher completely in one direction\n command.downcase!\n case command\n when 'right', 'left', 'down', 'up'\n motion = Launcher.const_get(command.upcase)\n send_move(motion, value)\n when 'zero', 'park', 'reset'\n # Move to bottom-left reference point\n send_move(DOWN, 2)\n send_move(LEFT, 7)\n when 'pause', 'sleep'\n sleep(value)\n when 'barrage', 'salvo', 'volley', 'broadside', 'bombard', 'shell', 'shower', 'suppress', 'fusillade'\n send_fire(4)\n when 'fire', 'shoot', 'launch', 'blast'\n # If no value, or value too high, fire 1 missile\n value = 1 unless value && (1..4).include?(value)\n send_fire(value)\n else\n raise(\"Unknown command: #{command}\")\n end\n end", "def proccess_command(command)\n # branch based on command type\n case command[0]\n when COMScript # script [code]\n # evaluate script\n result = eval(command[1])\n when COMWait # wait [int]\n # decrease wait counter by 1\n command[1] -= 1\n # proceed if wait time is up\n return command[1] <= 0\n when COMMove # move [int, int]\n # add to move commands\n @moves.push(command)\n when COMTurn # turn [int]\n # add to move commands\n @moves.push(command)\n when COMJump # jump [int, int]\n # add to move commands\n @moves.push(command)\n when COMAttack # attack\n # use attack\n @ch.use_attack\n when COMSkill # skill [int]\n # use skill\n @ch.use_skill($data_skills[command[1]])\n when COMItem # item [int]\n # use item\n @ch.use_item($data_items[command[1]])\n when COMDefend # defend [int]\n # decrease time\n time = command[1] - 1\n # use defend\n @ch.use_defend\n # set penalty\n @ch.set_action(1)\n # if not done with command\n if time > 0\n # update the command counter\n command[1] = time\n # do not proceed\n return false\n end\n when COMCharacter # character [CH, value]\n # handle based on sub-command\n case command[1]\n when CHSpeed # move speed\n # set movement speed\n @ch.move_speed = command[2]\n when CHFrequency # move frequency\n # set movement frequency\n @ch.move_frequency = command[2]\n when CHSprite # change sprite\n # set sprite\n @ch.character_name = command[2]\n when CHAnimation # play animation\n # set animation\n @ch.animation_id = command[2]\n when CHFix # direction fix\n # set direction fix flag\n @ch.direction_fix = command[2]\n when CHThrough # through\n # set through flag\n @ch.through = command[2]\n when CHOnTop # always on top\n # set always on top flag\n @ch.always_on_top = command[2]\n when CHOpacity # opacity\n # set opacity\n @ch.opacity = command[2] \n end\n when COMInput # create input window [int, [keys], IN, int]\n # create new input window\n @inputs[command[1]] = [command[2], command[3], command[4], false]\n when COMVariable # variable [VAR, value1, '=', VAR, value2]\n val1 = get_variable(command[1], command[2])\n val2 = get_variable(command[4], command[5])\n # branch handling based on operator type\n case command[3]\n when '+=' then val2 = val1 + val2 # add\n when '-=' then val2 = val1 - val2 # subtract\n when '*=' then val2 = val1 * val2 # multiply\n when '/=' then val2 = val1 / val2 # divide\n when '%=' then val2 = val1 % val2 # modulo\n end\n # set the variable\n set_variable(command[1], command[2], val2)\n when COMCondition # condition [VAR, value1, '==', VAR, value2]\n # initialize result\n result = false\n # initialize values\n val1 = get_variable(command[1], command[2])\n val2 = get_variable(command[4], command[5])\n # branch handling based on operator type\n case command[3]\n when '==' # equal to\n # result is value 1 equal to value 2\n result = val1 == val2\n when '!=' # not equal to\n # result is value 1 not equal to value 2\n result = val1 != val2\n when '>' # greater than\n # result is value 1 equal to value 2\n result = val1 > val2\n when '>=' # greater than or equal to\n # result is value 1 not equal to value 2\n result = val1 >= val2\n when '<=' # less than\n # result is value 1 equal to value 2\n result = val1 < val2\n when '<=' # less than or equal to\n # result is value 1 not equal to value 2\n result = val1 <= val2\n end \n # if input or script\n if command[1] == VARInput || command[1] == VARScript\n # value 1 contains the result\n result = val1\n # do not proceed if waiting on an input window\n if command[1] == VARInput && @inputs[command[2]][2] > 0 && !result\n return false\n end\n end\n # skip next command if exists and condition not met\n @commands.delete_at(1) if !result && @commands.size > 1\n when COMFreeze # freeze input [bool]\n # set freeze input flag\n @freeze_character = command[1]\n when COMCompletion # wait for move completion\n # proceed if no more moves and character no longer moving\n return @moves.size == 0 && !@ch.moving?\n when COMGoTo # go to action [int]\n raise 'ERROR: Invalid action' if !is_valid_action?(command[1])\n # setup the action\n setup_action(command[1])\n # do not proceed - new set of commands\n return false\n when COMAbort # abort\n # set ended flag\n @ended = true\n end\n return true\n end", "def processCommand(command)\n # Check if the command is nil\n unless command.nil?\n # Convert command to all uppercase\n command = command.upcase\n # Find out the type of command, PLACE, LEFT, RIGHT, MOVE or REPORT\n commandConst = Command.validate(command)\n # Only process non-PLACE command when robot is placed\n unless commandConst.nil? || (commandConst != Command::P && !@robot.placed)\n case commandConst\n when Command::P\n # Get x and y \n position = command.scan(/\\d+/)\n x = position[0].to_i\n y = position[1].to_i\n face = command.scan(/#{Direction::N}|#{Direction::E}|#{Direction::S}|#{Direction::W}$/)[0]\n @robot.update(x, y, face)\n when Command::L\n @robot.turnLeft\n when Command::R\n @robot.turnRight\n when Command::M\n @robot.move\n when Command::RP \n @view.displayOutput(@robot.x, @robot.y, @robot.face)\n end\n return true\n end\n end\n # Invalid command\n return false\n end", "def instruction (command)\n\t\t\t@actor.tell @actor.state.prompt + command\n\t\t\t@actor.perform command\n\t\tend", "def handle_commands(player_inputs)\n filter_commands(player_inputs)\n case @player_move\n when 'PLACE'\n @new_commands.valid_placement(@position_x, @position_y, @direction)\n when 'MOVE'\n @new_commands.move_robot\n when 'LEFT'\n @new_commands.turn_left\n when 'RIGHT'\n @new_commands.turn_right\n when 'OBSTACLE'\n @new_commands.create_obstacle(@obs_postion_x, @obs_postion_y)\n @new_commands.check_obstacles(@obs_postion_x, @obs_postion_y)\n when 'PATH'\n @new_commands.find_path(@path_position_x, @path_position_y)\n when 'REPORT'\n @new_commands.report_position\n else\n puts 'INVALID COMMAND -- Plase select a valid command:'\n end\n end", "def execute_player_command\n\t\tif state == 'pregame'\n\t\t\tif text_two.get.casecmp('start') == 0\n\t\t\t\tstart\n\t\t\telsif text_two.get.casecmp('help') == 0\n\t\t\telse\n\t\t\t\tinsert_text(\"To start the game, type 'start'\")\n\t\t\tend\n\n\t\telsif state == 'normal'\n\t\t\tif text_two.get.casecmp('fight') == 0\n\t\t\t\tfight\n\t\t\telsif /\\Aequip ([a-zA-Z])+(\\s|[a-zA-Z])*$/ === text_two.get\n\t\t\t\tarray = text_two.get.split(' ')\n\t\t\t\tarray.shift\n\t\t\t\tstring = array.join(' ')\n\t\t\t\t@player.equip(string, self)\n\t\t\telsif /\\Aequip (\\d)+$/ === text_two.get\n\t\t\t\tarray = text_two.get.split(' ')\n\t\t\t\tarray.shift\n\t\t\t\tinteger = array.join(' ').to_i\n\t\t\t\t@player.equip(integer, self)\n\t\t\telsif (text_two.get.casecmp('move e') == 0) || \n\t\t\t\t(text_two.get.casecmp('move w') == 0)||\n\t\t\t\t(text_two.get.casecmp('move s') == 0) ||\n\t\t\t\t(text_two.get.casecmp('move n') == 0)\n\t\t\t\tarray = text_two.get.split(' ')\n\t\t\t\tarray.shift\n\t\t\t\tdirection = array.join(' ')\n\t\t\t\tmove(direction)\n\t\t\telsif text_two.get.casecmp('equipment') == 0\n\t\t\t\tinsert_text(@player.equipment_to_s)\n\t\t\telsif text_two.get.casecmp('survey') == 0\n\t\t\t\tinsert_text(@game_map.get_tile_info)\n\t\t\telsif text_two.get.casecmp('gold') == 0\n\t\t\t\tinsert_text(\"You have #{@player.gold} gold pieces.\")\n\t\t\telsif text_two.get.casecmp('show equippables') == 0\n\t\t\t\tshow_equippables\n\t\t\telsif /\\Aunequip ([a-zA-Z])+(\\s|[a-zA-Z])*$/ === text_two.get\n\t\t\t\tarray = text_two.get.split(' ')\n\t\t\t\tarray.shift\n\t\t\t\tstring = array.join(' ')\n\t\t\t\t@player.unequip(string, self)\n\t\t\telsif text_two.get.casecmp('show inventory') == 0\n\t\t\t\tshow_inventory\n\t\t\telsif text_two.get.casecmp('equip') == 0\n\t\t\t\tinsert_text(\"You must specify the item you want to equip. and the item must be in your inventory.\")\n\t\t\t\tinsert_text(\"You can either use the name of the item, or the slot in your inventory where item is stored.\")\n\t\t\t\tinsert_text(\"For example, you could type 'equip Longsword'.\")\n\t\t\t\tinsert_text(\"Or, if the item is in inventory slot 1, you could type 'equip 1'.\")\n\t\t\t\tinsert_text(\"To see all equippable items you currently posess, type 'show equippables'.\\n\")\t\n\t\t\telsif text_two.get.casecmp('start') == 0\n\t\t\t\tinsert_text(\"Game already started.\")\n\t\t\telsif (text_two.get == '') || (/\\s/ === text_two.get)\n\t\t\t\t# do nothing\n\t\t\telsif text_two.get.casecmp('test') == 0\n\t\t\t\ttest\n\t\t\telsif text_two.get.casecmp('help') == 0\n\t\t\t\thelp\n\t\t\telse\n\t\t\t\tinsert_text(\"Unknown command.\\n\")\n\t\t\tend\n\n\t\telsif state == 'combat'\n\t\t\tif text_two.get == 'attack'\n\t\t\t\t@encounter.attack_monster\n\t\t\telsif text_two.get == 'status'\n\t\t\t\t# print player status\t\t\n\t\t\telse\n\t\t\t\t# do stuff\n\t\t\tend\n\t\telse\n\t\t\t# do stuff\n\t\tend\n\n\t text_two.delete(0, 'end')\n\tend", "def do_command(command, e)\n case command\n when \"DONGME\" then send_dong(e.channel, e.msg.user.hash + e.msg.host.hash)\n when \"UPVOTE\" then vote(1)\n when \"DOWNVOTE\" then vote(-1)\n when \"SCORE\" then score(e.channel)\n when \"HELP\" then @irc.msg(e.channel, \"I HAVE COMMANDS AND THEY ARE !DONGME !UPVOTE !DOWNVOTE !SCORE AND !HELP\")\n end\n\n # Here we're saying that we don't want any other handling run - no filters, no handler. For\n # commands, I put this here because I know I don't want any other handlers having to deal with\n # strings beginning with a bang.\n e.handled!\nend", "def command(command)\n output = \"\"\n\n # LETTER: equivalent to +LETTER\n if (command.match(\"^([A-Z])$\")) then\n command = \"+#{$1}\"\n end\n\n # +WORD : add words to table\n if (command.match(\"^\\\\+([A-Z ]+)$\"))\n new_words = $1.split(\" \").delete_if{|word|word.empty?}\n @words += new_words\n output += \"Added #{new_words.inspect} to table.\\n\"\n output += format_words\n\n # -WORD : remove words from table\n elsif (command.match(\"^-([A-Z ]+)$\"))\n remove_words = $1.split(\" \").delete_if{|word|word.empty?}\n words_copy = @words.dup\n valid = true\n remove_words.each do |word|\n index = words_copy.index(word)\n if index then\n words_copy.delete_at(index)\n else\n output += \"Invalid removal: Not enough #{word.inspect}s on the table.\\n\"\n valid = false\n end\n end\n if valid then\n @words = words_copy\n output += \"Removed #{remove_words.inspect} from table.\\n\"\n end\n output += format_words\n\n elsif ([\"@\",\"/WORDS\"].include?(command))\n output += format_words\n\n # # : number of moves\n elsif ([\"#\",\"/num\"].include?(command))\n output += \"Number of possible moves: #{moves.size}\"\n\n # ? : what moves can we make\n elsif ([\"?\",\"/moves\"].include?(command))\n output += \"Possible moves:\\n\"+@dictionary.format_moves(moves)\n\n # number : make that move\n elsif (command.match(\"^([0-9]+)$\"))\n move = moves[$1.to_i]\n if (move) then\n result = move(move)\n if result==true then\n output += \"Made move: #{dictionary.format_move(move)}\\n\"+format_words\n else\n output += result\n end\n else\n output += \"Unrecognized move #{$1.inspect}. Enter '?' for a list of valid moves.\" \n end\n\n else\n output += \"Unrecognized command #{command.inspect}\"\n end\n\n return output\n end", "def send_command_to_robot(command)\n case command.type\n when 'PLACE'\n @robot.place(command.value[0].to_i, command.value[1].to_i, command.value[2])\n when 'MOVE', 'RIGHT', 'LEFT', 'REPORT'\n @robot.send(command.type.downcase)\n end\n rescue ToyRobot::RobotIsNotPlaced, Surface::TableOutOfBound => e\n command.status = 'ignored'\n command.error = e.to_s\n end", "def handle_command(c)\n\tcase c\n\twhen \"p\"\n\t\tprint_table\n\twhen \"q\"\n\t\texit\n\twhen \"g\"\n\t\tread_table\n\twhen \"c\"\n\t\tinit_table\n\twhen \"?s\"\n\t\tputs $score\n\twhen \"?n\"\n\t\tputs $cleared_lines\n\twhen \"s\"\n\t\tupdate_table\n\twhen *Tetromino.types\n\t\t$active_tetromino = Tetromino.new(c)\n\twhen \"t\"\n\t\tputs $active_tetromino.to_s\n\tend\nend", "def act_on_command(first_word, client_hash, client)\n\t\tcase first_word\n\t\twhen 'groupjoin'\n\t\t\thandle_join(client, client_hash[\"groupId\"])\n\t\twhen 'groups'\n\t\t\thandle_groups(client)\n\t\twhen 'grouppost'\n\t\t\thandle_post(client,\n\t\t\t\t\t\t\t\t\tclient_hash[\"message\"],\n\t\t\t\t\t\t\t\t\tclient_hash[\"subject\"],\n\t\t\t\t\t\t\t\t\tclient_hash[\"groupId\"])\n\t\twhen 'groupusers'\n\t\t\thandle_users(client, client_hash[\"groupId\"])\n\t\twhen 'groupleave'\n\t\t\thandle_leave(client, client_hash[\"groupId\"])\n\t\twhen 'groupmessage'\n\t\t\thandle_open(client, client_hash[\"groupId\"], client_hash[\"messageId\"])\n\t\telse\n\t\t\tclient.send(\"Server\", [\"I don't know the command #{first_word}\"])\n\t\tend\n\tend", "def phase_command\n # Determine action based on what ranges are currently being viewed\n case @range_type\n when 1 # Move\n # Update drawing the arrow path\n update_player_route if cursor.moved?\n # Do not process input if the cursor is still moving\n unless cursor.moving?\n if Input.trigger?(Input::C)\n # If unit belongs to the player and within unit's move range\n if @unit.army == @player and !@positions[cursor.x][cursor.y].nil?\n # Setup a new command\n @command = Unit_Command.new\n # Store location for command\n @command.move = [cursor.x, cursor.y]\n commands = determine_unit_commands\n # If commands exist\n if commands != []\n Config.play_se(\"decide\")\n width = 0\n temp_bitmap = Bitmap.new(32, 32)\n commands.each{|c|\n size = temp_bitmap.text_size(c).width\n width = size if size > width\n }\n # Draw unit command window\n @active_window = Unit_Command_Window.new(width + 50, commands, true, @unit)\n cursor.disable_input = true\n @phase = 3\n else\n # Invalid spot to move to\n $game_system.se_play($data_system.buzzer_se)\n end\n else # Invalid move, buzzer sound\n $game_system.se_play($data_system.buzzer_se)\n end\n elsif Input.trigger?(Input::B)\n $game_system.se_play($data_system.cancel_se)\n @unit.selected = false\n @unit = nil\n @phase = 1\n remove_ranges\n dispose_arrows\n end\n end\n\n when 2 # Attack\n if !Input.press?(Input::B)\n @unit.selected = false\n @unit = nil\n @phase = 1\n remove_ranges\n end\n \n end\n\n \n end", "def interpret_move(command)\n ensure_placed\n @robot.move_forward\n end", "def neighborhoodLoop(command, home)\n\t\tcase command.getCommand()\n\t\twhen 'left'\n\t\t\tif(@player.location % 3 != 1)\n\t\t\t\t@player.location = @player.location - 1;\n\t\t\t\tputs \"You have moved west to another house.\"\n\t\t\telse\n\t\t\t\tputs \"You are at the edge of your neighborhood and cannot go further west.\"\n\t\t\tend\n\t\twhen 'right'\n\t\t\tif(@player.location % 3 != 0)\n\t\t\t\t@player.location = @player.location + 1;\n\t\t\t\tputs \"You have moved east to another house.\"\n\t\t\telse\n\t\t\t\tputs \"You are at the edge of your neighborhood and cannot go further east.\"\n\t\t\tend\n\t\twhen 'up'\n\t\t\tif(@player.location + 3 < 10)\n\t\t\t\t@player.location = @player.location + 3;\n\t\t\t\tputs \"You have moved north to another house.\"\n\t\t\telse\n\t\t\t\tputs \"You are at the edge of your neighborhood and cannot go further north.\"\n\t\t\tend\n\t\twhen 'down'\n\t\t\tif(@player.location - 3 > 0)\n\t\t\t\t@player.location = @player.location - 3;\n\t\t\t\tputs \"You have moved south to another house.\"\n\t\t\telse\n\t\t\t\tputs \"You are at the edge of your neighborhood and cannot go further south.\"\n\t\t\tend\n\t\twhen 'si'\n\t\t\tputs \"Weapon Name\\t-\\tUses\"\n\t\t\t@player.inventory.each do |weapon|\n\t\t\t\tif(weapon.uses < 0)\n\t\t\t\t\tputs \"#{weapon.name}\\t-\\tUnlimited uses\";\n\t\t\t\telse\n\t\t\t\t\tputs \"#{weapon.name}\\t-\\t#{weapon.uses} uses\";\n\t\t\t\tend\n\t\t\tend\n\t\twhen 'sm'\n\t\t\tputs \"You lost the map and connot use it anymore\";\n\t\t\t# print map of houses and monster count info\n\t\t\t# TODO: print map of neighborhood\n\t\twhen 'eh'\n\t\t\tputs \"You entered house number #{@player.location}\";\n\t\t\thome = @neighborhood.homes[@player.location - 1];\n\t\twhen 'ns'\n\t\t\t@neighborhood.stats();\n\t\telse\n\t\t\tputs \"That is not a command.\";\n\t\tend\n\t\t\n\t\treturn home\n\tend", "def take_action(action)\n case action\n when :look\n @print_status\n when :north\n if @current_room.doors[:n]\n @world.move_entity_north(@player)\n else\n @player.hurt(1)\n puts \"You run into a wall. Ouch! You have #{@player.hit_points} HP remaining.\"\n end\n when :east\n if @current_room.doors[:e]\n @world.move_entity_east(@player)\n else\n @player.hurt(1)\n puts \"You run into a wall. Ouch! You have #{@player.hit_points} HP remaining.\"\n end\n when :south\n if @current_room.doors[:s]\n @world.move_entity_south(@player)\n else\n @player.hurt(1)\n puts \"You run into a wall. Ouch! You have #{@player.hit_points} HP remaining.\"\n end\n when :west\n if @current_room.doors[:w]\n @world.move_entity_west(@player)\n else\n @player.hurt(1)\n puts \"You run into a wall. Ouch! You have #{@player.hit_points} HP remaining.\"\n end\n when :fight, :take\n @current_room.interact(@player)\n when :status\n @player.print_status\n end\n end", "def execute(command)\n return 'Not Placed' unless place_command?(command) || @robot.placed\n command, args = command.split(' ')\n command = command.to_s.downcase.to_sym\n args = args ? args.split(',') : []\n\n result = @robot.send(command, *args) if VALID_COMMANDS.include?(command)\n result if report_command?(command)\n end", "def command room, device, state\n # @todo get the device name in here...\n # Command structure is <transaction number>,<Command>|<Action>|<State><cr>\n if room and device and !device.empty? and state\n '666,!' + room['id'] + room['device'][device] + state + '|Turn ' + room['name'] + ' ' + device + '|' + state + ' via @pauly'\n else\n '666,!' + room['id'] + state + '|Turn ' + room['name'] + '|' + state + ' via @pauly'\n end \n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pickup the treasure in the room if there is any
def pick_up treasure = @game.current_room_model.treasure has_torch = @game.player.has_torch? return "There is no treasure to pick up\n" unless treasure && treasure > 0 return "You cannot see where it is\n" unless has_torch @game.player.wealth += treasure return "You picked-up gems worth $#{treasure}\n" # TODO: update room status end
[ "def pickup_treasure\n contents = get_room_items\n if contents == 0\n puts \"THERE IS NO TREASURE TO PICK UP\"\n else\n @wealth += contents\n puts \"PICKED UP $#{contents}!\"\n set_to_room(@room, 0)\n end\n \n end", "def pick_up(item)\n if (item.is_a?Weapon)\n self.equipped_weapon = item\n else\n self.equipped_weapon =nil \n if item.is_a?(BoxOfBolts) && health <= 80 \n self.equipped_weapon =nil \n item.feed(self)\n elsif item.is_a?(Battery) && shield <= 30\n item.recharge(self)\n elsif items_weight + item.weight <= MAX_WEIGHT\n @items << item\n @items_weight += item.weight\n end\n end\n end", "def dropoff_treasure(reference)\n # find the treasure and room\n treasure = @treasures.detect {|tr| tr.reference == reference}\n\n # drop off by changing location to current location\n treasure.location = @player.location\n # find room where it's dropped off\n room = @rooms.detect {|rm| rm.reference == treasure.location}\n\n # remove treasure from satchel array\n @satchel.delete(reference)\n\n puts \"You dropped off \" + treasure.name + \" \" + room.description\n end", "def pick_up(item)\n if items_weight + item.weight <= CAPACITY \n if item.is_a?(Weapon)\n @equipped_weapon = item \n elsif item.is_a?(BoxOfBolts) && health <= 80\n item.feed(self) \n else items << item\n end\n end\n end", "def pick_up(station)\n current_bike = (station.bikes).pop\n fail \"this bike is working\" if current_bike.working? == true\n @bike = current_bike\n end", "def pick_up(item)\n return false if items_weight + item.weight > MAX_WEIGHT\n\n @equipped_weapon = item if item.is_a?(Weapon)\n @items << item\n end", "def pick_up_object(object, direction)\n if @boat.count == 1\n puts \"I just picked up the #{object}.\"\n @boat[1] = object\n return direction == 'left' ? @right_side_of_river.delete(object) : @left_side_of_river.delete(object)\n else\n puts \"Uh oh! My boat is full!\"\n end\n end", "def nextTreasure\n if @unusedTreasures.empty?\n @unusedTreasures = @usedTreasures\n @usedTreasures = []\n @unusedTreasures.shuffle!\n end\n @unusedTreasures.pop\n end", "def pick_weapon; end", "def found_treasure(treasure)\n\t \tdamaged_treasure = Treasure.new(treasure.name, treasure.points/2.0)\n\t \tsuper(damaged_treasure)\n\t end", "def steal\n\t\t# Get the first thing in the character's pocket that has a non-zero quantity\n\t\t_thing = _qty = nil\n\t\t@pocket.each do |thing,qty|\n\t\t\tif qty > 0\n\t\t\t\t_thing = thing\n\t\t\t\t_qty = qty\n\n\t\t\t\t# Zero out the qty.\n\t\t\t\t@pocket[thing] = 0\n\n\t\t\t\tbreak\n\t\t\tend\n\t\tend\n\n\t\t# TODO for you - handle _thing being nil\n\t\treturn if _thing.nil?\n\n\t\t# Move that qty. to the ghost pocket\n\t\tif @ghost_pocket.has_key?(_thing)\n\t\t\t@ghost_pocket[_thing] += _qty\n\t\telse\n\t\t\t@ghost_pocket[_thing] = _qty\n\t\tend\n\tend", "def treasure_chance\n chance = roll.d100(1)\n if chance <= 100\n @treasure = Treasure.new\n end\n end", "def loot_treasure(treasure)\n treasure.open\n loot = treasure.get_reward_for(self)\n case loot[:type]\n when 'money'\n puts \"Congratulations! You have found #{loot[:reward]} gold\"\n @money += loot[:reward]\n when 'item'\n puts \"Congratulations! You have found the #{ loot[:reward].class.to_s }, #{ loot[:reward].name }\"\n add_to_inventory(loot[:reward])\n else invalid\n end\n end", "def treasure_chance\n chance = roll.d100(1)\n if chance <= 70\n @treasure = Treasure.new\n end\n end", "def collect_treasure\n @gold_coins += 1\n if @gold_coins % 10 == 0\n level_up\n end\n end", "def treasure_chance\n chance = roll.d100(1)\n if chance <= 50\n @treasure = Treasure.new\n end\n end", "def collect_treasure\n @gold_coins = @gold_coins + 1\n if gold_coins % 10 == 0 \n return level_up\n end\n end", "def check_treasure\n if (treasure?)\n show_found_treasure\n else puts \"No treasure in this room.\"\n end\n end", "def pickup(object)\n\t\t\tif object.parent == current_room\n\t\t\t\ttake(object)\n\t\t\t\tself.reload\n\t\t\telse\n\t\t\t\traise GreyGoo::Error, \"Can't take that object\"\n\t\t\tend\n\t\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transitions to the buying state
def inventory @game.state = BuyingState.new @game @game.state.handle end
[ "def next_state (delivery)\n\t\tif self.state == \"Box it\" && delivery then self.state = \"Delivery\" end\n\t\tif self.state == \"Box it\" && !delivery then self.state = \"Dispatched\" end\n\t\tif self.state == \"Cut it\" then self.state = \"Box it\" end\n\t\tif self.state == \"Bake it\" then self.state = \"Cut it\" end\n\t\tif self.state == \"In preparation\" then self.state = \"Bake it\" end\n\t\tself.save\n\tend", "def change_state\n @auction = Auction.find(params[:auction])\n @auction.state = params[:state].to_i\n @auction.end_time = params[:end_time]\n @auction.save\n @auction.delay.close_auction(@auction.id)\n redirect_to(:action => 'show', :controller => 'items', :id => @auction.item_id)\n end", "def buy\n @product = @machine.products.find(params[:product_id])\n # get old inventory count and new inventory count\n old, new = @product.current_inventory_count, (@product.current_inventory_count - 1)\n # update product\n @product.update(current_inventory_count: new)\n # update tracker\n @product.update_tracker\n \n render :layout => false\n end", "def settle(delivery, state = nil)\n delivery.update(state) unless state.nil?\n delivery.settle\n end", "def change_state\n @auction = Auction.find(params[:id])\n #@auction.state = params[:state].to_i\n\n if @auction.update_attributes(params[:auction])\n @auction.delay.close_auction(@auction.id)\n redirect_to(:action => 'show', :controller => 'items', :id => @auction.item_id)\n\n else\n @search = Item.search(params[:search])\n\n render action: \"seller_edit\"\n # redirect_to(:action => 'seller_edit', :id => @auction.id)\n end\n end", "def handle_purchase\n if saved_change_to_state == %w(draft purchased)\n seller.increase_balance(payment.amount)\n end\n end", "def transition(to)\n @state = to\n end", "def prepare\r\n # if buyer bought all items\r\n if self.item.quantity == self.quantity\r\n self.seller.release_item(self.item)\r\n else\r\n self.seller.release_quantity_of_item(self.item, self.quantity)\r\n self.item = self.item.clone\r\n self.item.id = Item.next_id!\r\n self.item.owner = nil\r\n self.item.quantity = self.quantity\r\n self.item.save\r\n end\r\n self.item.price = self.price unless self.price == nil\r\n self.item.state = :pending\r\n\r\n self.item.notify_change\r\n self.buyer.add_to_pending(self)\r\n self.buyer.credits -= self.item.price * self.quantity\r\n\r\n self.save\r\n end", "def transition_or_maintain!(new_state)\n return if in_state?(new_state)\n\n transition! new_state\n end", "def change_state\n # transition_to(another_state)\n end", "def toggle_picked_up\n @order = Order.find(params[:id]).toggle_pickup!\n redirect_back fallback_location: '/order_seasons/' + params[:id] + \"/orders\"\n end", "def update_transaction_stage\n if @item.under_sale?\n @item.purchased!\n @information_type = 'be_purchased'\n create_information\n @todo_stage = 'ship_it'\n manage_todo\n elsif @item.purchased?\n @item.shipping!\n @information_type = 'be_shiped'\n create_information\n @todo_stage = 'review_if_buyer_received'\n manage_todo\n elsif @item.shipping?\n @item.evaluated!\n @information_type = 'be_evaluated'\n create_information\n @todo_stage = 'review_and_receive_money'\n manage_todo\n elsif @item.evaluated?\n @item.transaction_completed!\n @information_type = 'transaction_has_been_finished'\n create_information\n manage_todo\n end\n end", "def update_buy_selection\n @status_window.item = @buy_window.item\n if Input.trigger?(Input::B)\n Sound.play_cancel\n @command_window.active = true\n @buy_dummy_window.visible = true\n @buy_window.active = false\n @buy_window.visible = false\n @status_window.visible = false\n @status_window.item = nil\n @help_window.set_text(\"\")\n return\n end\n if Input.trigger?(Input::C)\n @item = @buy_window.item\n number = $game_party.item_number(@item)\n item_lim = IEX::SCENE_SHOP::MAX_BUY_ITEMS\n if @item == nil or @item.price > $game_party.gold or number == item_lim\n Sound.play_buzzer\n else\n Sound.play_decision\n max = @item.price == 0 ? item_lim : $game_party.gold / @item.price\n max = [max, item_lim - number].min\n @buy_window.active = false\n @buy_window.visible = false\n @number_window.set(@item, max, @item.price)\n @number_window.active = true\n @number_window.visible = true\n end\n end\n end", "def soak\n self.state = \"soaked\"\n end", "def set_sellable_item_state(state_result)\n if !state_result[:inventory_item].nil?\n if (state_result[:inventory_item].quantity > state_result[:inventory_item].item.quantity_threshold)\n state_result[:inventory_item].update(id: state_result[:inventory_item].id, inventory_item_state: InventoryItemState.find_by(name: \"Available\"))\n elsif (state_result[:inventory_item].quantity == 0)\n state_result[:inventory_item].update(id: state_result[:inventory_item].id, inventory_item_state: InventoryItemState.find_by(name: \"Out_of_Stock\"), inventory_item_condition: InventoryItemCondition.find_by(name: \"Not_Sellable\"))\n else\n state_result[:inventory_item].update(id: state_result[:inventory_item].id, inventory_item_state: InventoryItemState.find_by(name: \"CriticaL_Level\"))\n end\n end\n end", "def trade_ban_state; end", "def update_shop_ui_after_buying(index)\n # Adjust the bag info\n reload_item_list\n unless @force_close \n @index = index.clamp(0, @last_index)\n @item_list.index = @index\n # Reload the graphics\n update_item_button_list\n update_scrollbar\n update_item_desc\n update_money_text\n end\n end", "def buy(item)\n raise_no_money! if item.price > pending_amount\n change = calc_change(pending_amount - item.price)\n transfer_pending_to_money\n remove_from_money change\n change\n end", "def buy\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts +sexp+ into a Compiler::Node.
def sexp_to_node(sexp) return nil if sexp.nil? if node_class = Node::Mapping[sexp.first] node_class.create(self, sexp) else raise Error, "Unable to resolve '#{sexp.first.inspect}'" end end
[ "def sexp_to_ast(sexp)\n eval sexp\n end", "def process(sexp, level = :expr)\n return fragment('', scope) if sexp.nil?\n\n if handler = handlers[sexp.type]\n return handler.new(sexp, level, self).compile_to_fragments\n else\n error \"Unsupported sexp: #{sexp.type}\"\n end\n end", "def transform_sexp(sexp)\n return sexp unless sexp.body\n\n sexp.body.sexp_type = :NUKE # negate top level body\n sexp = s(:NUKE, sexp) # wrap with extra node to force full process\n\n sexp\n end", "def to_sexp(exp)\n if array?(exp)\n Sexp.from_array(exp)\n elsif exp.is_a?(String)\n parse(exp)\n end\n end", "def get_sexp ast, only_structure\n sexp = ''\n if ast.call? and not only_structure\n sexp = '( ' + ast.method_name.source + LINE_DELIMITER + ast.line.to_s + ' '\n ast.children.each do |child|\n sexp += get_sexp(child, only_structure)\n end\n sexp += ') '\n elsif ast.loop?\n sexp = '( iter' + LINE_DELIMITER + ast.line.to_s + ' '\n ast.children.each do |child|\n sexp += get_sexp(child, only_structure)\n end\n sexp += ') '\n elsif ast.condition?\n sexp = '( cond' + LINE_DELIMITER + ast.line.to_s + ' '\n ast.children.each do |child|\n sexp += get_sexp(child, only_structure)\n end\n sexp += ') '\n else\n ast.children.each do |child|\n sexp += get_sexp(child, only_structure)\n end\n end\n sexp\nend", "def compile_node(node); end", "def translate_generic_sexp(sexp)\n # Notify that the sexp it to be translated.\n event = \"#{sexp[0]}_encountered\".to_sym\n @event_manager.fire_event(event, EventStruct.new(event, self, sexp, nil))\n\n # Is there a public or a private method translating such a sexp?\n if respond_to? (method_name = \"translate_#{sexp[0]}\".to_sym), true\n translated_sexp = send(method_name, sexp)\n else\n line = sexp.line - StdlibLineNumber\n die \"Input contains unsupported Ruby instruction in line #{line}. Aborting.\"\n end\n @translated_sexp_dict.add_entry(sexp, translated_sexp)\n\n # Notify that the sexp was translated.\n event = \"#{sexp[0]}_translated\".to_sym\n @event_manager.fire_event(event, EventStruct.new(event, self, sexp, translated_sexp))\n translated_sexp\n end", "def to_sxp\n require 'sxp' unless defined?(SXP)\n # Output rules as a formatted S-Expression\n SXP::Generator.string(@ast.map(&:for_sxp))\n end", "def parse_sexp\n token = next_token\n\n case token\n when \"(\" then\n parse_list\n when \"[\" then\n parse_cmd\n when \"nil\" then\n nil\n when /^\\d+$/ then\n token.to_i\n when \"___\" then\n Sexp.___\n when \"_\" then\n Sexp._\n when %r%^/(.*)/$% then\n re = $1\n raise SyntaxError, \"Not allowed: /%p/\" % [re] unless\n re =~ /\\A([\\w()|.*+^$]+)\\z/\n Regexp.new re\n when /^\"(.*)\"$/ then\n $1\n when /^([A-Z]\\w*)$/ then\n Object.const_get $1\n when /^:?([\\w?!=~-]+)$/ then\n $1.to_sym\n else\n raise SyntaxError, \"unhandled token: %p\" % [token]\n end\n end", "def compile(code)\n parser = RubyParser.new\n sexp = parser.parse(code)\n # pp sexp\n \n visitor = Visitor.new(@generator, self)\n visitor.visit(sexp)\n \n @generator.program\n end", "def compile(node)\n get_compiler.compile(node).get_source\n end", "def decompose_sexp(sexp)\n raise \"invalid rsxml: #{rsxml.inspect}\" if sexp.length<1\n if sexp[0].is_a?(Array)\n element_name = sexp[0]\n else\n element_name = sexp[0].to_s\n end\n if sexp[1].is_a?(Hash)\n attrs = sexp[1]\n children = sexp[2..-1]\n else\n attrs = {}\n children = sexp[1..-1]\n end\n [element_name, attrs, children]\n end", "def extract(sexp)\n trigger_pattern_callbacks(sexp)\n RubySource.new(@source_lines.join(\"\\n\"), @source_map)\n end", "def compile(source)\n ast = transformer.apply(parser.parse(source))\n ast.compile\n end", "def parse_sexp\n token = next_token\n\n case token\n when \"(\" then\n parse_list\n when \"[\" then\n parse_cmd\n when \"nil\" then\n nil\n when /^\\d+$/ then\n token.to_i\n when \"___\" then\n Sexp.___\n when \"_\" then\n Sexp._\n when %r%^/(.*)/$% then\n re = $1\n raise SyntaxError, \"Not allowed: /%p/\" % [re] unless\n re =~ /\\A([\\w()|.*+^$]+)\\z/\n Regexp.new re\n when /^\"(.*)\"$/ then\n $1\n when /^\\w+$/ then\n token.to_sym\n else\n raise SyntaxError, \"unhandled token: %p\" % [token]\n end\n end", "def sexp\n lambda {|sio|\n res = lparen.call sio\n return res if res.empty?\n \n res = operator.call sio\n oper = nil\n unless res.empty?\n oper = res.head.value\n else\n return res\n end\n space.call sio\n num = many(cor(digit,sexp)).call sio\n total = total_for oper, num\n rpres = rparen.call sio\n unless rpres\n num = many(cor(digit,sexp)).call sio\n total1 = total_for oper, num\n total = total1.send(oper, total1)\n end\n list(ParseResult.new(sio, total))\n }\n end", "def _cedent(sexp)\n iter = self.eval(sexp)\n [iter.length + 1] + iter\n end", "def compile_node(node)\n case node\n when AryPtn\n compile_aryptn(node)\n when Binary\n compile_binary(node)\n when Const\n compile_const(node)\n when ConstPathRef\n compile_const_path_ref(node)\n when DynaSymbol\n compile_dyna_symbol(node)\n when HshPtn\n compile_hshptn(node)\n when RegexpLiteral\n compile_regexp_literal(node)\n when StringLiteral\n compile_string_literal(node)\n when SymbolLiteral\n compile_symbol_literal(node)\n when VarRef\n compile_var_ref(node)\n else\n compile_error(node)\n end\n end", "def compile\n @output = @ast.compile_to_ruby\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Everything should have the same album tag
def all_same_album?(tags) all_same_tag?(tags, :album) end
[ "def fix_album_tags\n file_list = []\n file_list = select_files(\"#{@library_root}/**/D[0-9][0-9]_*.mp3\")\n\n album_name = \"\"\n temp_hash = {}\n\n # create album_name from file name \n # \"D09_0855_GS_10d.mp3\" gets album \"D09_10d\"\n file_list.each do |name|\n w = (File.basename(name)).split(\"_\")\n album_name = [ w[0], w[-1].chomp(\".mp3\")].join(\"_\")\n temp_hash[name] = album_name\n end\n\n if !@dry_run then\n puts \"New album data prepared, now hold on while I write it into the #{file_list.count} mp3 files.\"\n temp_hash.each do |file_name, album_tag|\n ok = TagLib::FileRef.open(file_name) do |f|\n tag = f.tag\n tag.album = album_tag\n f.save\n end\n if ok == false then\n puts \"uh-oh. There was a problem saving / openning #{file_name}\"\n end\n end\n else #@dry_run == true\n puts \"You are in dry run mode.\\nIf you weren't in dry run mode the following changes would be made:\"\n pp temp_hash.sort\n end\n puts \"finished the global album name fix.\"\n end", "def fix_album_tags\n file_list = []\n file_list = select_files(\"#{@library_root}/**/D[0-9][0-9]_*.mp3\")\n\n album_name = \"\"\n temp_hash = {}\n\n\n file_list.each do |name|\n album_name = (File.basename(name)).chomp(\".mp3\")\n temp_hash[name] = album_name\n end\n\n if !@dry_run then\n puts \"New title data prepared, now hold on while I write it into the #{file_list.count} mp3 files.\"\n temp_hash.each do |file_name, title_tag|\n set_metadata(file_name, title:title_tag)\n # create album_name from file name \n # \"D09_0855_GS_10d.mp3\" gets album \"D09_10d\"\n # \"D09_0855_GS_STP.mp3\" gets album \"D09_STP\"\n w = title_tag.split(\"_\")\n album_name = [ w[0], w[-1]].join(\"_\")\n set_metadata(file_name, album:album_name)\n end\n else #@dry_run == true\n puts \"You are in dry run mode.\\nIf you weren't in dry run mode the following changes would be made:\"\n temp_hash.sort\n temp_hash.each do |file_name, title_tag|\n w = title_tag.split(\"_\")\n album_name = [ w[0], w[-1]].join(\"_\")\n print(\"file: #{file_name}, album: #{album_name}, title: #{title_tag}\\n\")\n end\n end\n\n puts \"finished the global album name fix.\"\n end", "def test_check_album_library\n assert_valid_library(make_album_library)\n\n assert_basic_library_checks { make_album_library }\n\n assert_group_library_checks { make_album_library }\n\n lib = make_album_library.apply(1, %w{1 3}) { |l| l.set_tag(\"ALBUMARTIST\", \"Foo\") }\n assert_raises_metadata_error(lib, \"The ALBUMARTIST is not required since all tracks have the same and unique ARTIST.\")\n end", "def albums\n @albums ||= response.albums.uniq(&:name)\n end", "def album=(v)\n if @album != v\n @needs_commit = true\n @album = v\n end\n end", "def set_mix_or_album\n self.is_mix = self.tracks.any?{ |track| track.asset.user.id.to_s != self.user.id.to_s}\n true\n end", "def detect_album_or_song\n if self.link =~ /(album)/\n \"<iframe src='https://open.spotify.com/embed/album/#{album_code}' width='300' height='auto' frameborder='0' allowtransparency='true' allow='encrypted-media'></iframe>\"\n else\n \"<iframe src='https://open.spotify.com/embed/track/#{track_code}' width='300' height='auto' frameborder='0' allowtransparency='true' allow='encrypted-media'></iframe>\"\n end\n end", "def set_id3_tags\r\n z = TagLib::FileRef.open(self.song.path) do |fileref|\r\n tag = fileref.tag\r\n tag.title\r\n end\r\n y = TagLib::FileRef.open(self.song.path) do |fileref|\r\n tag = fileref.tag\r\n tag.artist\r\n end\r\n x = TagLib::FileRef.open(self.song.path) do |fileref|\r\n tag = fileref.tag\r\n tag.album\r\n end\r\n w = TagLib::FileRef.open(self.song.path) do |fileref|\r\n properties = fileref.audio_properties\r\n properties.length\r\n end\r\n if title.nil?\r\n self.update_attributes(:title => z)\r\n elsif artist.nil?\r\n self.update_attributes(:artist => y)\r\n elsif album.nil?\r\n self.update_attributes(:album => x) \r\n elsif length.nil?\r\n self.update_attributes(:length => w)\r\n else \r\n end\r\n end", "def album_unique?(album_object, artist_object)\n\n albums = self.albums.select{|album| album.artist.present?}\n non_nil_albums = albums.select{|album| album.artist.name == artist_object.name} << album_object.name\n non_nil_albums.length == non_nil_albums.uniq.length\n end", "def add_missing_albums(p_same_artist)\n\t\t\n\t\t\t# Only try to add if it's really the same artist\n\t\t\treturn if self != p_same_artist\n\t\t\t\n\t\t\t# Iterate through albums, see if the 'other' artist's albums are new\n\t\t\tp_same_artist.albums.each do |other_album|\n\n\t\t\t\t# Search for candidate album within own albums\n\t\t\t\tidx = @albums.index(other_album)\n\t\t\t\n\t\t\t\t# If the album wasn't found in own collection, add it\n\t\t\t\tif idx.nil?\n @albums << other_album\n else\n\n # TODO: Refactor to Album\n\n\t\t\t\t\t# Store matched album and its path\n\t\t\t\t\tcurrent_album = @albums[idx]\n\t\t\t\t\tcurrent_path_folder = current_album.path_folder\n other_album_path_folder = other_album.path_folder\n\n\t\t\t\t\t# If there is a match, check if the album is multi-disc, update path if so\n\t\t\t\t\tif FileSystemUtils::same_parent_folder(current_path_folder, other_album_path_folder)\n\t\t\t\t\t\tcurrent_album.path = current_path_folder\n log.debug \"[#{self.name}] Consolidated multi-disc album path #{other_album}\"\n else\n\n if current_album.is_unknown? && other_album.is_unknown?\n\n log.debug \"[#{self.name}] Matched multiple locations for unknown/non-album tracks \"\n log.debug \"[#{self.name}] Moving from '#{other_album_path_folder}' to '#{current_path_folder}'\"\n ModelUtils::move_mp3s_to({\n :source => other_album_path_folder,\n :dest => current_path_folder\n })\n\n end\n end\n\t\t\t\t\t\n\t\t\t\tend # if\n\t\t\t\t\n\t\t\tend # each\n\t\tend", "def test_photo_extras\n assert_nothing_raised(Exception) do\n album = @smug.albums( :nick_name => 'kleinpeter' ).first\n photo = album.photos.first\n \n assert_not_nil( photo.details )\n assert_not_nil( photo.info )\n assert_not_nil( photo.urls )\n end\n end", "def album_name\n album.name\n end", "def album_name\n album ? album.name : ''\n end", "def update_albumart!(illegal_albumart_id= nil)\n all= discs.map{|d| d.tracks.map{|t| t.audio_file.audio_tags.map(&:albumart)}}.flatten\n all.delete nil\n all.delete illegal_albumart_id if illegal_albumart_id\n all= all.inject({}){|h,a| h[a]||=0; h[a]+= 1; h}\n max= all.values.max\n img= all.select{|img,score| score == max}.map{|e| e[0]}.first\n update_attributes! :albumart => img\n self.albumart= img\n end", "def album=(value)\n @album = value\n end", "def album_title\n if album\n album.title\n end\n end", "def getInfo(song)\n # BEGIN TAG DETECTION FOR TITLE, ARTIST, ETC. - NO ARTWORK #\n TagLib::FileRef.open('public' + song.file_url) do |fileref|\n unless fileref.null?\n tag = fileref.tag\n song.title = (tag.title if !tag.title.nil?) || \"Unknown Title\"\n song.artist = (tag.artist if !tag.artist.nil?) || \"Unknown Artist\"\n song.album = (tag.album if !tag.album.nil?) || \"Unknown Album\"\n song.genre = (tag.genre if !tag.genre.nil?) || \"\"\n song.track_number = (tag.track if !tag.track.nil?) || 0\n song.save\n end\n end\n\n # Check if the album already exists, if so, use same artwork\n q = Song.where(:directory => current_user.user_directory)\n q = q.where(:artist => song.artist)\n q = q.where(:album => song.album)\n q = q.where.not(:cover_art => \"defaultImg.png\")\n\n q.each do |i|\n puts i\n end\n\n if q.count >= 1\n song.cover_art = q[0].cover_art\n song.save\n return\n end\n\n TagLib::MPEG::File.open('public' + song.file_url) do |file|\n tag = file.id3v2_tag\n\n cover = tag.frame_list('APIC').first\n\n #Check if artwork ID3 tag exists\n if !cover.nil?\n picture = cover.picture\n\n file_name = 'public/directories/' + song.directory + '/' + File.basename(song.file_url, File.extname(song.file_url))\n\n #Create new file from attached cover artwork\n File.open(file_name + \".jpg\", \"wb\") do |f|\n f.write(picture)\n end\n\n #Resize Image\n image = MiniMagick::Image.open(file_name + \".jpg\")\n if image.dimensions != \"[300, 300]\"\n image.resize \"300x300\"\n end\n\n # Attempt to create unique file name\n new_file_name = \"artworks-#{SecureRandom.uuid}\"\n\n #Ensure file name is not already taken\n while Song.where(:cover_art => new_file_name).count != 0\n new_file_name = \"artworks-#{SecureRandom.uuid}\"\n end\n\n # Change images to PNG format\n image.format \"png\"\n image.write \"public/a/#{new_file_name}.png\"\n image_optim = ImageOptim.new()\n image_optim.optimize_image(\"public/a/#{new_file_name}.png\")\n\n File.delete(file_name + \".jpg\")\n\n bn = File.basename(\"#{song.file}\", File.extname(\"#{song.file}\"))\n\n song.cover_art = new_file_name + \".png\"\n song.save\n\n #Increase file size for song to account for new artwork file\n current_user.total_file_size += File.size(\"public/a/#{song.cover_art}\")\n current_user.save\n else\n #If no artwork ID3 tag exists, set to default image\n song.cover_art = \"defaultImg.png\"\n song.save\n end\n end\n end", "def find_album(artist,url_slug)\n logger.info \"in find album\"\n\t\tartist.albums.uniq.each do |album|\n\t\t\tif album.album_url_slug == url_slug\n\t\t\t\t@album = album\n\t\t\tend\n\t\tend\n\n\t\tlogger.info @album\n\tend", "def album_code\n code = self.link.match(/album\\/(.*)/)\n code.captures.first\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Everything should have the same year tag
def all_same_year?(tags) all_same_tag?(tags, :year) end
[ "def year() end", "def match_year?(doc, date)\n return true unless year\n\n idate = RelatonBib.parse_date doc[\"issued-date\"], false\n idate.between? date, date.next_year.prev_day\n end", "def year? = unit == 'year'", "def store_years_encompassed(doc)\n raw_values = [:date, :date_associated].map { |s| object.send(s) }.map(&:to_a).flatten\n years = raw_values.reduce([]) do |dates, date|\n parsed = Date.edtf(date)\n next (dates + [parsed.year]) if parsed.is_a? Date\n next dates if parsed.nil? || !parsed.respond_to?(:map)\n\n dates + parsed.map(&:year)\n end\n\n doc['years_encompassed_iim'] = years.sort.uniq\n end", "def could_be_year?(year); end", "def span_years; end", "def update_year\n @year = @year.to_i if (@year.length == 4 && (@year.to_i >= 1900 && DateTime.new(@year.to_i, DateTime.now.month, DateTime.now.day, 24) <= DateTime.now.next_year.next_year))\n end", "def is_same_year? date1, date2\n return date1.beginning_of_year == date2.beginning_of_year\n end", "def year\n published_at.year\n end", "def year\n @interval = 'year'\n self\n end", "def w_year; end", "def year_built\n self.dig_for_integer(\"yearBuilt\")\n end", "def year_renovated\n self.dig_for_integer(\"yearRenovated\")\n end", "def year\r\n if attributes[\"year\"].blank?\r\n self.published_at? ? self.published_at.year.to_s : \"\"\r\n else\r\n attributes[\"year\"]\r\n end\r\n end", "def year\n return @year\n end", "def multi_year?\n (multi_year)\n end", "def tibs_year?\n (@time.year % 4).zero? && @time.year % 100 != 0 || (@time.year % 400).zero?\n end", "def facet_year_group_for_solr\n result = \"\"\n years = associated_years\n logger.debug \"CHECKING: #{years}\"\n current_year = Time.now.year\n if years.length > 0\n #logger.debug \"YGFS:T1\"\n for year_string in years\n # logger.debug \"YGFS:T2\"\n year = year_string.to_i\n if year == current_year\n # logger.debug \"YGFS:T3 - current year match\"\n result << \"current \"\n elsif year == (current_year+1)\n # logger.debug \"YGFS:T4 - next year match\"\n result << \"next \"\n elsif year < (current_year)\n # logger.debug \"YGFS:T5 - previous years\"\n result << \"previous \"\n elsif year >> (current_year + 1)\n # logger.debug \"YGFS:T6 - future past next\"\n result << \"future \"\n end\n end\n #no years found\n else \n # logger.debug \"YGFS:T7 - none found\"\n result = \"none \"\n end\n \n # logger.debug \"YGFS: #{years} => #{result}\"\n result.strip.split(' ').uniq.sort.join(' ')\n end", "def is_year? y\n\t\treturn year.year == y.to_i\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
And probably of the same genre. (Who cares, really, about the genre tag anyway?)
def all_same_genre?(tags) all_same_tag?(tags, :genre) end
[ "def genres\n songs.collect do |song|\n song.genre\n end\n .uniq #does not return duplicate genres if the artist has more than one song of a particular genre (artist has many genres through songs)\n end", "def has_genre?(genre)\n map(&:genre).flatten.uniq.include? genre\n end", "def genres\n#collects genres through its songs instead of maintaining its own @genres instance (artist has many genres through songs), does not return duplicate genres\n songs.collect { |song| song.genre}.uniq\n end", "def genre_other?\n\t genre == \"other\"\n\tend", "def fav_genre\n # NOTE : DID NOT ADD GENRES YET\n # r.shows.genres\n \"WIP - no genres yet\"\n end", "def genre_name\n # self.genre.name\n self.genre ? self.genre.name : ''\n end", "def add_uniq_genre(genre)\n return if @genres.include?(genre)\n @genres << genre\n end", "def genre\n descMetadata.genre\n end", "def genre\n marc_genre_leader = Traject::TranslationMap.new(\"marc_genre_leader\")\n marc_genre_007 = Traject::TranslationMap.new(\"marc_genre_007\")\n\n results = marc_genre_leader[ record.leader.slice(6,2) ] ||\n marc_genre_leader[ record.leader.slice(6)] ||\n record.find_all {|f| f.tag == \"007\"}.collect {|f| marc_genre_007[f.value.slice(0)]}\n\n [results].flatten\n end", "def has_genre?(g)\n case g\n when String \n @genres.include?(g)\n when Regexp \n @genres.find { |s| s =~ g }\n end\n end", "def genres\n Genre.all.select{|genre| genre.book == self }\n end", "def map_genre(\n original_genre # String\n ) # Array<String>\n genre_map = {\n # Movie/Drama\n # NOTE: We don't include the general \"Movie/Drama\" category here since\n # it's rather specific and should only apply to _actual movies_, not\n # random TV shows and such.\n 'Action' => [ETSI_GENRE_ADVENTURE_WESTERN_WAR],\n 'Adventure' => [ETSI_GENRE_ADVENTURE_WESTERN_WAR],\n 'Comedy' => [ETSI_GENRE_COMEDY],\n 'Comedy drama' => [ETSI_GENRE_COMEDY, ETSI_GENRE_SERIOUS_CLASSICAL_RELIGIOUS_HISTORICAL_MOVIE_DRAMA],\n 'Drama' => [ETSI_GENRE_SERIOUS_CLASSICAL_RELIGIOUS_HISTORICAL_MOVIE_DRAMA],\n 'Fantasy' => [ETSI_GENRE_SCIENCE_FICTION_FANTASY_HORROR],\n 'Historical drama' => [ETSI_GENRE_SERIOUS_CLASSICAL_RELIGIOUS_HISTORICAL_MOVIE_DRAMA],\n 'Horror' => [ETSI_GENRE_SCIENCE_FICTION_FANTASY_HORROR],\n 'Mystery' => [ETSI_GENRE_SCIENCE_FICTION_FANTASY_HORROR],\n 'Romance' => [ETSI_GENRE_ROMANCE],\n 'Romantic comedy' => [ETSI_GENRE_COMEDY, ETSI_GENRE_ROMANCE],\n 'Science fiction' => [ETSI_GENRE_SCIENCE_FICTION_FANTASY_HORROR],\n 'Soap' => [ETSI_GENRE_SOAP_MELODRAMA_FOLKLORIC],\n 'Thriller' => [ETSI_GENRE_SCIENCE_FICTION_FANTASY_HORROR],\n 'War' => [ETSI_GENRE_ADVENTURE_WESTERN_WAR],\n 'Western' => [ETSI_GENRE_ADVENTURE_WESTERN_WAR],\n\n # News/Current affairs\n 'Documentary' => [ETSI_GENRE_NEWS_CURRENT_AFFAIRS, ETSI_GENRE_DOCUMENTARY],\n 'Interview' => [ETSI_GENRE_NEWS_CURRENT_AFFAIRS, ETSI_GENRE_DISCUSSION_INTERVIEW_DEBATE],\n 'News' => [ETSI_GENRE_NEWS_CURRENT_AFFAIRS, ETSI_GENRE_NEWS_WEATHER_REPORT],\n 'Newsmagazine' => [ETSI_GENRE_NEWS_CURRENT_AFFAIRS, ETSI_GENRE_NEWS_MAGAZINE],\n 'Politics' => [ETSI_GENRE_NEWS_CURRENT_AFFAIRS, ETSI_GENRE_DISCUSSION_INTERVIEW_DEBATE],\n 'Public affairs' => [ETSI_GENRE_NEWS_CURRENT_AFFAIRS, ETSI_GENRE_DISCUSSION_INTERVIEW_DEBATE],\n 'Weather' => [ETSI_GENRE_NEWS_CURRENT_AFFAIRS, ETSI_GENRE_NEWS_WEATHER_REPORT],\n\n # Show/Game show\n 'Entertainment' => [ETSI_GENRE_SHOW_GAME_SHOW, ETSI_GENRE_VARIETY_SHOW],\n 'Game show' => [ETSI_GENRE_SHOW_GAME_SHOW, ETSI_GENRE_GAME_SHOW_QUIZ_CONTEST],\n 'Reality' => [ETSI_GENRE_SHOW_GAME_SHOW, ETSI_GENRE_VARIETY_SHOW],\n 'Talk' => [ETSI_GENRE_SHOW_GAME_SHOW, ETSI_GENRE_TALK_SHOW],\n 'Variety' => [ETSI_GENRE_SHOW_GAME_SHOW, ETSI_GENRE_VARIETY_SHOW],\n 'Sports talk' => [ETSI_GENRE_SHOW_GAME_SHOW, ETSI_GENRE_TALK_SHOW, ETSI_GENRE_SPORTS],\n 'Standup' => [ETSI_GENRE_SHOW_GAME_SHOW, ETSI_GENRE_COMEDY],\n 'Sitcom' => [ETSI_GENRE_SHOW_GAME_SHOW, ETSI_GENRE_COMEDY],\n\n # Sports\n 'Action sports' => [ETSI_GENRE_SPORTS],\n 'Alpine skiing' => [ETSI_GENRE_SPORTS, ETSI_GENRE_WINTER_SPORTS],\n 'Auto racing' => [ETSI_GENRE_SPORTS, ETSI_GENRE_MOTOR_SPORT],\n 'Baseball' => [ETSI_GENRE_SPORTS, ETSI_GENRE_TEAM_SPORTS_EXCLUDING_FOOTBALL],\n 'Basketball' => [ETSI_GENRE_SPORTS, ETSI_GENRE_TEAM_SPORTS_EXCLUDING_FOOTBALL],\n 'Bowling' => [ETSI_GENRE_SPORTS],\n 'Boxing' => [ETSI_GENRE_SPORTS, ETSI_GENRE_MARTIAL_SPORTS],\n 'Bull riding' => [ETSI_GENRE_SPORTS],\n 'Figure skating' => [ETSI_GENRE_SPORTS, ETSI_GENRE_WINTER_SPORTS],\n 'Football' => [ETSI_GENRE_SPORTS, ETSI_GENRE_TEAM_SPORTS_EXCLUDING_FOOTBALL],\n 'Intl soccer' => [ETSI_GENRE_SPORTS, ETSI_GENRE_FOOTBALL_SOCCER],\n 'Mixed martial arts' => [ETSI_GENRE_SPORTS, ETSI_GENRE_MARTIAL_SPORTS],\n 'Motorcycle racing' => [ETSI_GENRE_SPORTS, ETSI_GENRE_MOTOR_SPORT],\n 'Multi-sport event' => [ETSI_GENRE_SPORTS, ETSI_GENRE_SPECIAL_EVENTS],\n 'Pro wrestling' => [ETSI_GENRE_SPORTS, ETSI_GENRE_MARTIAL_SPORTS],\n 'Sailing' => [ETSI_GENRE_SPORTS, ETSI_GENRE_WATER_SPORT],\n 'Soccer' => [ETSI_GENRE_SPORTS, ETSI_GENRE_FOOTBALL_SOCCER],\n 'Surfing' => [ETSI_GENRE_SPORTS, ETSI_GENRE_WATER_SPORT],\n 'Triathlon' => [ETSI_GENRE_SPORTS, ETSI_GENRE_ATHLETICS],\n 'Watersports' => [ETSI_GENRE_SPORTS, ETSI_GENRE_WATER_SPORT],\n 'Wrestling' => [ETSI_GENRE_SPORTS, ETSI_GENRE_MARTIAL_SPORTS],\n 'Yacht racing' => [ETSI_GENRE_SPORTS, ETSI_GENRE_WATER_SPORT],\n 'eSports' => [ETSI_GENRE_SPORTS],\n\n # Children's/Youth programmes\n 'Children' => [ETSI_GENRE_CHILDRENS_YOUTH_PROGRAMS],\n\n # Music/Ballet/Dance\n 'Dance' => [ETSI_GENRE_MUSIC_BALLET_DANCE],\n 'Music' => [ETSI_GENRE_MUSIC_BALLET_DANCE],\n 'Musical' => [ETSI_GENRE_MUSIC_BALLET_DANCE],\n\n # Arts/Culture (without music)\n 'Anthology' => [ETSI_GENRE_ARTS_CULTURE_WITHOUT_MUSIC],\n 'Art' => [ETSI_GENRE_ARTS_CULTURE_WITHOUT_MUSIC, ETSI_GENRE_FINE_ARTS],\n 'Awards' => [ETSI_GENRE_ARTS_CULTURE_WITHOUT_MUSIC, ETSI_GENRE_POPULAR_CULTURE_TRADITIONAL_ARTS],\n 'Dog show' => [ETSI_GENRE_ARTS_CULTURE_WITHOUT_MUSIC],\n 'Fashion' => [ETSI_GENRE_ARTS_CULTURE_WITHOUT_MUSIC, ETSI_GENRE_FASHION],\n 'Parade' => [ETSI_GENRE_ARTS_CULTURE_WITHOUT_MUSIC],\n 'Performing arts' => [ETSI_GENRE_ARTS_CULTURE_WITHOUT_MUSIC, ETSI_GENRE_PERFORMING_ARTS],\n 'Religious' => [ETSI_GENRE_ARTS_CULTURE_WITHOUT_MUSIC, ETSI_GENRE_RELIGION],\n\n # Social/Political issues/Economics\n 'Biography' => [ETSI_GENRE_SOCIAL_POLITICAL_ISSUES_ECONOMICS, ETSI_GENRE_REMARKABLE_PEOPLE],\n 'Bus./financial' => [ETSI_GENRE_SOCIAL_POLITICAL_ISSUES_ECONOMICS, ETSI_GENRE_ECONOMICS_SOCIAL_ADVISORY],\n 'Community' => [ETSI_GENRE_SOCIAL_POLITICAL_ISSUES_ECONOMICS],\n 'Crime' => [ETSI_GENRE_SOCIAL_POLITICAL_ISSUES_ECONOMICS],\n 'Crime drama' => [ETSI_GENRE_SOCIAL_POLITICAL_ISSUES_ECONOMICS],\n 'Gay/lesbian' => [ETSI_GENRE_SOCIAL_POLITICAL_ISSUES_ECONOMICS],\n\n # Education/Science/Factual topics\n 'Agriculture' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS, ETSI_GENRE_TECHNOLOGY_NATURAL_SCIENCES],\n 'American history' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS],\n 'Ancient history' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS],\n 'Animals' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS, ETSI_GENRE_NATURE_ANIMALS_ENVIRONMENT],\n 'Aviation' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS],\n 'EI' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS],\n 'Educational' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS],\n 'Environment' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS, ETSI_GENRE_NATURE_ANIMALS_ENVIRONMENT],\n 'History' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS],\n 'How-to' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS, ETSI_GENRE_FURTHER_EDUCATION],\n 'Law' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS],\n 'Medical' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS, ETSI_GENRE_MEDICINE_PHYSIOLOGY_PSYCHOLOGY],\n 'Military' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS],\n 'Nature' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS, ETSI_GENRE_NATURE_ANIMALS_ENVIRONMENT],\n 'Paranormal' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS, ETSI_GENRE_MEDICINE_PHYSIOLOGY_PSYCHOLOGY],\n 'Science' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS],\n 'Self improvement' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS],\n 'Technology' => [ETSI_GENRE_EDUCATION_SCIENCE_FACTUAL_TOPICS, ETSI_GENRE_TECHNOLOGY_NATURAL_SCIENCES],\n\n # Leisure hobbies\n 'Arts/crafts' => [ETSI_GENRE_LEISURE_HOBBIES, ETSI_GENRE_HANDICRAFT],\n 'Auction' => [ETSI_GENRE_LEISURE_HOBBIES, ETSI_GENRE_ADVERISEMENT_SHOPPING],\n 'Auto' => [ETSI_GENRE_LEISURE_HOBBIES, ETSI_GENRE_MOTORING],\n 'Card games' => [ETSI_GENRE_LEISURE_HOBBIES],\n 'Collectibles' => [ETSI_GENRE_LEISURE_HOBBIES],\n 'Consumer' => [ETSI_GENRE_LEISURE_HOBBIES, ETSI_GENRE_ADVERISEMENT_SHOPPING],\n 'Cooking' => [ETSI_GENRE_LEISURE_HOBBIES, ETSI_GENRE_COOKING],\n 'Exercise' => [ETSI_GENRE_LEISURE_HOBBIES, ETSI_GENRE_FITNESS_AND_HEALTH],\n 'Fishing' => [ETSI_GENRE_LEISURE_HOBBIES],\n 'Gaming' => [ETSI_GENRE_LEISURE_HOBBIES],\n 'Health' => [ETSI_GENRE_LEISURE_HOBBIES, ETSI_GENRE_FITNESS_AND_HEALTH],\n 'Holiday' => [ETSI_GENRE_LEISURE_HOBBIES],\n 'Home improvement' => [ETSI_GENRE_LEISURE_HOBBIES, ETSI_GENRE_HANDICRAFT],\n 'House/garden' => [ETSI_GENRE_LEISURE_HOBBIES, ETSI_GENRE_GARDENING],\n 'Outdoors' => [ETSI_GENRE_LEISURE_HOBBIES],\n 'Poker' => [ETSI_GENRE_LEISURE_HOBBIES],\n 'Shopping' => [ETSI_GENRE_LEISURE_HOBBIES, ETSI_GENRE_ADVERISEMENT_SHOPPING],\n 'Travel' => [ETSI_GENRE_LEISURE_HOBBIES, ETSI_GENRE_TOURISM_TRAVEL],\n }\n\n genre_map.fetch(original_genre, original_genre)\n end", "def get_genre_name\n \tself.genre.name\n end", "def genres\n to_array search_by_itemprop 'genre'\n end", "def recommended_books_by_genre(library, likedGenere, hatedGenre)\n liked_books = []\n recommended_books = []\n library.each { |book|\n if book[:genres].include?(likedGenere) && !book[:genres].include?(hatedGenre) #check if a book includes a preferred genre and doesn't have the hated genre \n text = \"Since you like #{likedGenere}, you should read #{book[:title]} by #{book[:author]}!\"\n liked_books << text\n elsif !book[:genres].include?(hatedGenre) \n text = \"I also recommend #{book[:title]} by #{book[:author]}.\"\n recommended_books << text \n end \n }\n liked_books.concat(recommended_books)\n \nend", "def genre\n return @genre\n end", "def translate_genre(unknown_genre)\n @genre_matches[unknown_genre]\n end", "def has_genre?(g)\n @page && @page.has_genre?(g)\n end", "def genre=(genre)\n @genre = genre #assigns a genre to the song (song belongs to genre)\n genre.songs << self unless genre.songs.include?(self) #adds the song to the genre's collection of songs (genre has many songs); does not add the song to the genre's collection of songs if it already exists therein\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the relevant tags for all files.
def all_tags(files) supported(files).map { |f| Aur::FileInfo.new(f).our_tags } end
[ "def tag_files\n Dir[File.join(@bag_dir, '*')].select { |f| File.file? f }\n end", "def tags_used\n s = Set.new\n @selected_files.each do |file|\n s.merge file.tags\n end\n s.to_a.map { |v| v.downcase }\n end", "def tags\n return @tags if @tags\n return @tags = TagsEngine.new(@file)\n end", "def tags\n Tag.load path\n end", "def tags\n return @tags_cache if (@tags_cache ||= nil)\n \n global_tags, tag_types = {}, {}\n \n f = nil\n # For each current .hgtags file in our history (including multi-heads), read in\n # the tags\n hg_tags_nodes.each do |rev, node, file_node|\n # get the file\n f = (f && f.file(file_node.file_node)) || self.versioned_file(\".hgtags\", :file_id => file_node.file_node)\n # read the tags, as global, because they're versioned.\n read_tags(f.data.split(\"\\n\"), f, \"global\", global_tags, tag_types)\n end\n \n # Now do locally stored tags, that aren't committed/versioned\n begin\n # get the local file, stored in .hg/\n data = @hg_opener.read(\"localtags\")\n # Read the tags as local, because they are not versioned\n read_tags(data.split_newlines, \"local_tags\", \"local\", global_tags, tag_types)\n rescue Errno::ENOENT\n # do nothing. most people don't have this file.\n end\n # Save our tags for use later. Use ivars.\n @tags_cache, @tags_type_cache = {}, {}\n \n # Go through the global tags to store them in the cache\n global_tags.each do |k, nh|\n # update the cache\n @tags_cache[k] = nh.first unless nh.first == NULL_ID\n @tags_type_cache[k] = tag_types[k]\n end\n \n # tip = special tag\n @tags_cache[\"tip\"] = self.changelog.tip\n \n # return our tags\n @tags_cache\n end", "def tag_files\n files = []\n if tagmanifest_files != []\n File.open(tagmanifest_files.first) do |f|\n f.each_line { |line| files << File.join(@bag_dir, line.split(\" \")[1]) }\n end\n end\n files\n end", "def tagmanifest_files\n files = Dir[File.join(@bag_dir, \"*\")].select { |f|\n File.file?(f) && File.basename(f) =~ /^tagmanifest-.*.txt$/\n }\n files\n end", "def tag_manifested_files\n tagmanifest_files.inject([]) do |acc, mf|\n files = File.open(mf) { |io|\n io.readlines.map do |line|\n _digest, path = line.chomp.split(/\\s+/, 2)\n path\n end\n }\n (acc + files).uniq\n end\n end", "def find_all_tags\n (find.all_tags + find_in_archive.all_tags).uniq.sort\n end", "def index\n @file_tags = FileTag.all\n end", "def list\n ::MachineTag::Set.new(read_tag_file(@tag_file))\n end", "def assets_tags\n self.assets.collect(&:tags).flatten.uniq\n end", "def get_other_files() \n\t\t\tget_document(@tag_type[2])\n\t\tend", "def get_all_tags include_virtual = true\n begin\n cache_get_or_else(\"get_all_tags(#{include_virtual.to_s})\") {\n tags = call_collins(\"get_all_tags\"){|c| c.get_all_tags}.map{|t|t.name}\n if include_virtual then\n [tags + Collins::Asset::Find.to_a].flatten.sort\n else\n tags.sort\n end\n }\n rescue Exception => e\n puts \"Error retrieving tags: #{e}\"\n []\n end\n end", "def get_all_tags\n taglist = %x[vorbiscomment -l #{@file.shellescape}].split(\"\\n\")\n tags = {}\n taglist.each do |line|\n key,value = line.split(\"=\")\n tags[key] = value\n end\n return tags\n end", "def tags\n get.tagGuids\n end", "def ruby_svn_tags\n raw_ruby_svn_tags.map { |t| expand_variants(t) }.flatten.uniq.sort\n end", "def return_all_tags\n @tags.uniq.each { |tag| puts tag }\n end", "def tags\n @tags ||= (tagGuids || []).map{|guid| note_store.getTag(guid)}\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a Hash of only the rakefiles that have tasks to be run. key = rakefile name, value = EvaluatedRakeFile Add the tasks to run for each EvaluatedRakeFile
def rakefiles_with_tasks_to_run rakefiles_with_tasks = new_hash_of_eval_rakefiles # This isn't efficient, but it's clear: all_tasks_to_run.each do |task_to_run| rakefilename = task_to_run.filename ev_rakefile_to_run = self.all_rakefiles[rakefilename] ev_rakefile_to_run.tasks_to_run << task_to_run rakefiles_with_tasks[rakefilename] = ev_rakefile_to_run end rakefiles_with_tasks end
[ "def all_evaluated_tasks_in_files(given_dir)\n eval_tasks = []\n\n [SOMETASK1, SOMETASK2, SOMETASK3, SOMETASK4, SOMETASK5].each do |sometask|\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(sometask), File.join(q1_dir(given_dir), SOME_TASKS_RAKEFILE))\n end\n\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(GOODTASK), File.join(blorf_dir(given_dir), GOOD_TASK2_RAKEFILE))\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(SET_WHEN_APPROVED_TASK), File.join(blorf_dir(given_dir), SET_WHEN_APPR2_RAKEFILE))\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(SIMPLETASK), File.join(blorf_dir(given_dir), SIMPLE_TASK_RAKEFILE))\n\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(SET_WHEN_APPROVED_TASK), File.join(blorf2_dir(given_dir), SET_WHEN_APPR_RAKEFILE))\n\n [SIMPLETASK, SOMETASK5].each do |blorf2_simplemore_task|\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(blorf2_simplemore_task), File.join(blorf2_dir(given_dir), SIMPLE_AND_SOME5_RAKEFILE))\n end\n\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(SIMPLETASK), File.join(given_dir, SIMPLE_TASK_RAKEFILE))\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(RUNTHISTASK), File.join(given_dir, RUN_THIS_RAKEFILE))\n\n eval_tasks\n end", "def get_task_execs_by_run()\n result = {}\n task_execs = TaskExecution.load_all_for_automation(self)\n task_execs.each do |exe|\n result[exe.automation_run] = [] if !result[exe.automation_run]\n result[exe.automation_run] << exe\n end\n return result\n end", "def task_files\r\n Dir.chdir(Rails.root.join('lib', 'tasks')) do |dir|\r\n @task_files = Dir[\"*.rake\"]\r\n end\r\n @task_files = @task_files.reject{|task|\r\n task !~ /\\Abg_worker_/}.map{|task|\r\n task.sub('bg_worker_', '')\r\n }\r\n end", "def onetime_rake_files\n tasks_dir = self.tasks_directory\n return [] unless Dir.exist?(tasks_dir) && !Dir.empty?(tasks_dir)\n\n Dir.glob(File.join('**', '*.rake'), base: tasks_dir)\n end", "def rakefiles\n @rakefiles ||= []\n end", "def tasks\n output = %x[ #{rake} -f #{@rakefile} -s -T ]\n @tasks ||= output.split(\"\\n\").map do |task|\n task.match(/^rake\\s([^\\s]+)\\s+#\\s(.+)/)[1..2]\n end.compact\n end", "def generate_rake_tasks\n @rake_tasks = filters.collect { |f| f.generate_rake_tasks }.flatten\n end", "def task_list\n return @task_list if @task_list\n @task_list = []\n spec_file_names.each do |file_name_spec|\n next if spec_is_disabled? file_name_spec\n next if skip_globals? file_name_spec\n next unless spec_included? file_name_spec\n get_spec_runs(file_name_spec).each do |run|\n next unless run[:hiera] and run[:facts]\n next unless facts_included? run[:facts]\n next unless hiera_included? run[:hiera]\n task = Noop::Task.new file_name_spec, run[:hiera], run[:facts]\n task.parallel = true if parallel_run?\n @task_list << task\n end\n end\n @task_list\n end", "def all_tasks_to_run\n self.all_tasks - all_tasks_previously_run - all_tasks_duplicates\n end", "def add_rakefile_and_tasks(rakefilename, task_names)\n\n # creates a new EvaluatedRakeFile entry if needed\n ev_rakefile = self.all_rakefiles[rakefilename]\n ev_rakefile.add_task_names(task_names)\n self.all_tasks.concat(ev_rakefile.all_tasks)\n\n ev_rakefile\n end", "def list_files_and_tasks(given_dir)\n puts \"\\nList of files and tasks in: #{given_dir}\"\n puts \" Note: this includes all files with 'rake' _anywhere_ in the extension so that it will show *.rake.run and more: Dir.glob(File.join('**', *.rake*')\\n\\n\"\n files = Dir.glob(File.join(\"**\", \"*.rake*\"), base: given_dir)\n\n Rake.with_application do\n\n files.each do |filename|\n puts \" #{filename}\"\n full_rakefile_path = File.absolute_path(File.join(given_dir, filename))\n\n begin\n onetime_rake_tasks = Rake.with_application do\n Rake.load_rakefile(full_rakefile_path)\n end\n rake_task_names = onetime_rake_tasks.tasks.map(&:name)\n\n rake_task_names.each do |taskname|\n puts \" #{taskname}\"\n end\n\n rescue => e\n puts \" - this file doesn't seem to be a Rakefile. Error with Rake.load_rakefile()\"\n puts e\n end\n\n puts \"\\n\"\n end\n end\n\n puts \"\\n\"\n end", "def tasks_for_all_configurations\n @configurations.keys.collect{ |name| \"#{@project_name}:#{name}\"}\n end", "def scheduled_tasks\n self.tasks.select { \n |t| t.interval != :startup && t.interval != :shutdown\n }\n end", "def read_tasks\n if File.exists? Syctask::DEFAULT_TASKS and not \\\n File.read(Syctask::DEFAULT_TASKS).empty?\n YAML.load_file(Syctask::DEFAULT_TASKS) \n else\n {}\n end\n end", "def all_prerequisite_tasks\n seen = {}\n collect_prerequisites(seen)\n seen.values\n end", "def has_task_file?\n Dir.glob(\"{Taskfile,Tasksfile,taskfile.rb,tasksfile.rb,Rakefile,rakefile.rb,tasks.rb}\").pop\n end", "def available_tasks\n task_names = Task.available_tasks.map(&:name)\n available_task_runs = Run.where(task_name: task_names)\n last_runs = Run.with_attached_csv.where(\n id: available_task_runs.select(\"MAX(id) as id\").group(:task_name)\n )\n\n task_names.map do |task_name|\n last_run = last_runs.find { |run| run.task_name == task_name }\n TaskData.new(task_name, last_run)\n end.sort_by!(&:name)\n end", "def task_file_names\n return @task_file_names if @task_file_names\n error \"No #{Noop::Config.dir_path_tasks_local} directory!\" unless Noop::Config.dir_path_tasks_local.directory?\n @task_file_names = find_files(Noop::Config.dir_path_tasks_local, Noop::Config.dir_path_tasks_local) do |file|\n file.to_s.end_with? '.pp'\n end\n end", "def rake_task_paths\n if check_subdirectory('lib/tasks')\n Dir[File.join(path.to_s, 'lib/tasks/**', '*.rake')]\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If there are tasks with the same name, mark them as duplicates and log them.
def set_and_log_duplicate_tasks(evaluated_tasks) return [] if evaluated_tasks.empty? # get all of the task_names that are duplicates (TODO ruby 2.7: replace this with .tally) duplicated_names = evaluated_tasks.group_by(&:name).select { |_name, tasks | tasks.size > 1 }.keys # Guard condition: no duplicate names, so just return return [] if duplicated_names.empty? # get the duplicated tasks for each name; return all of them duplicated_names.map{|dup_name| duplicated_tasks_for_name(dup_name, evaluated_tasks) }.flatten end
[ "def set_and_log_task_as_duplicate(duplicated_task, tasks_with_same_name)\n\n dup_filname = duplicated_task.filename\n\n # Get all of the other tasks that have this task name and set them as being a duplicate of this one\n the_other_dup_tasks = tasks_with_same_name.reject { |other_task| other_task == duplicated_task }\n # set these other tasks as having this one as a duplicate\n the_other_dup_tasks.each { |other_task| other_task.add_duplicate(dup_filname) }\n\n log_as_duplicate(duplicated_task)\n\n duplicated_task\n end", "def add_hardcoded_duplicates(task)\n task.add_duplicate('t1 duplicate 1')\n task.add_duplicate('t1 duplicate 2')\n end", "def ensure_unique_tasks_names! \n for i in 0..(@tasks_params.count-2)\n for j in (i+1)..(@tasks_params.count-1)\n raise RuntimeError, 'Duplicated tasks names' if @tasks_params[i.to_s][:name] == @tasks_params[j.to_s][:name]\n end\n end\n end", "def similar_task(user, taskname)\n can_create_task = true\n user.assignments.each do |assignment_instance|\n if assignment_instance.taskname.downcase == taskname.downcase\n # binding.pry \n can_create_task = false \n end \n end\n can_create_task\n end", "def invalid_duplication\n !Batchy.configure.allow_duplicates && already_running\n end", "def duplicated_name; end", "def merge_duplicates!\n Rails.logger.info \"Merging duplicates of #{url}\"\n duplicates.each do |dupe|\n dupe.merge_with!(self)\n end\n end", "def grouped_duplicates(collection); end", "def duplicate_task(name: required(\"name\"), include: nil, options: {}, **data)\n with_params = data.merge(name: name, include: include).reject { |_,v| v.nil? || Array(v).empty? }\n Resource.new(parse(client.post(\"/tasks/#{gid}/duplicate\", body: with_params, options: options)).first, client: client)\n end", "def verify_org_task_unique; end", "def verify_root_task_unique\n if appeal.tasks.where(\n type: type\n ).any?\n fail(\n Caseflow::Error::DuplicateOrgTask,\n docket_number: appeal.docket_number,\n task_type: self.class.name,\n assignee_type: assigned_to.class.name\n )\n end\n end", "def warn_if_filenames_repeated\n all_files = @items.inject([]){|a,item| a += item.filenames}\n dup_files = all_files.find_all{|f| all_files.count(f) > 1}.uniq\n\n if dup_files.length > 0\n STDERR.puts \"\\nWARNING: A reference to one or more 'dspace.files' has been repeated.\"\n dup_files.sort.each{|f| STDERR.puts \"- 'dspace.files' filename: #{f}\"}\n end\n end", "def check_for_duplicate_backup(name)\n check_for_duplicate(name, @backups, \"backup\")\n end", "def check_and_fix_duplicated_events( meeting_id )\n ms_ids = MeetingSession.where( meeting_id: meeting_id ).map { |r| r.id }\n mes = MeetingEvent.where( \"meeting_session_id IN (?)\", ms_ids )\n puts \"-> Tot. events #{mes.size}, IDs: #{mes.map{ |r| r.id }.inspect}\"\n # Find the list of possibly duplicated MeetingEvents (only the ones from data-import):\n mes_preexisting = mes.select { |r| !r.is_autofilled }\n mes_duplicated = mes.select { |r| r.is_autofilled }\n puts \" pre-existing, non-autofilled ME: #{mes_preexisting.map{ |r| r.id }}\"\n puts \" autofilled with data-import ME: #{mes_duplicated.map{ |r| r.id }}\" if mes_duplicated.size > 0\n if mes_preexisting.size > 0\n puts \" Searching for possible duplicated MEs as candidates for removal...\"\n else\n puts \" Everything seems fine...\"\n end\n\n # Foreach pre-existing row, find the extra rows among the possible duplicates:\n mes_preexisting.each do |me_preexisting|\n puts \"\\r\\nChecking duplication for ME #{me_preexisting.id}, event type #{me_preexisting.event_type_id}, heat: #{me_preexisting.heat_type_id}\"\n mes_extra = mes_duplicated.select do |me_duplicated|\n ( me_preexisting.event_type_id == me_duplicated.event_type_id ) &&\n ( me_preexisting.heat_type_id == me_duplicated.heat_type_id )\n end\n puts \"-> Duplication: #{mes_extra.size}, ME IDs: #{mes_extra.map{ |r| r.id }.inspect}\"\n puts \" -- WARNING! -- More than 1 candidate for removal found. You may need to run this task more than once to fix everything.\" if mes_extra.size > 1\n me_candidate_for_removal = mes_extra.first\n# DEBUG\n# puts \" first: #{me_candidate_for_removal.inspect}\"\n if me_candidate_for_removal\n check_and_fix_single_meeting_event( me_candidate_for_removal, me_preexisting )\n else\n puts \" No existing duplicates found for this ME. MPRGs are not duplicated. Nothing else to fix here. :-)\"\n end\n end\nend", "def create_trip_dup_report\n puts \"Creating trip-duplicate report (#{File.basename(FNAME_TRIP_DUP_CSV)}) ...\"\n\n File.open(FNAME_TRIP_DUP_CSV, 'w'){|fh|\n fh.puts \"trip,files_with_duplicate_trip\"\t# CSV header line\n\n @files_by_sorted_trip.each{|trip,list|\n next unless list.length > 1\n fh.puts \"#{trip},#{list.join(\"|\")}\"\t# CSV data line\n }\n }\n end", "def verify_org_task_unique\n return if !active?\n\n if appeal.tasks.active.where(\n type: type,\n assigned_to: assigned_to,\n parent: parent\n ).any? && assigned_to.is_a?(Organization)\n fail(\n Caseflow::Error::DuplicateOrgTask,\n appeal_id: appeal.id,\n task_type: self.class.name,\n assignee_type: assigned_to.class.name,\n parent_id: parent&.id\n )\n end\n end", "def verify_org_task_unique\n if Task.where(type: type, assigned_to: assigned_to, appeal: appeal)\n .where.not(status: Constants.TASK_STATUSES.completed).any? &&\n assigned_to.is_a?(Organization)\n fail(\n Caseflow::Error::DuplicateOrgTask,\n appeal_id: appeal.id,\n task_type: self.class.name,\n assignee_type: assigned_to.class.name\n )\n end\n end", "def check_and_increment\n similar_hosts = get_all_with_same_name name\n if similar_hosts.count < 1\n self.name = \"#{self.name} 1\"\n else\n next_num = similar_hosts.max_by{|m| m.name.scan(/\\d+/)}.name.scan(/\\d+/).first.nil? ? 1 : similar_hosts.max_by{|m| m.name.scan(/\\d+/)}.name.scan(/\\d+/).first.to_i + 1\n self.name = \"#{self.name} #{next_num}\"\n end\n end", "def on_duplicate; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all of the tasks that should be run: No duplicates, no tasks that have previously been run successfully.
def all_tasks_to_run self.all_tasks - all_tasks_previously_run - all_tasks_duplicates end
[ "def complete_tasks\n tasks.select { |t| t.done? }\n end", "def successful_tasks\n @successful_tasks ||= @tasks_results.select(&:success?)\n end", "def all_completed\n completed_tasks = []\n @task_list.each do |task|\n if task.done?\n completed_tasks << task\n end\n end\n completed_tasks\n end", "def complete_tasks\n results = []\n @tasks.each do |task|\n if task.complete?\n results << task\n end \n end\n\n results.sort_by { |task| task.completed_at }\n end", "def complete_tasks\n results = []\n @tasks.each do |task|\n if !task.completed_at.nil?\n results << task\n end\n end\n\n results.sort_by { |task| task.completed_at }\n end", "def incomplete_tasks\n\t\ttasks.select{ |t| !t.completed? }\n\tend", "def include_not_completed_tasks\n @container.select {|t| t.task_done == false}\n end", "def incomplete_tasks\n results = []\n @tasks.each do |task|\n if task.incomplete?\n results << task\n end\n end\n\n results.sort_by { |task| task.created_at }\n end", "def incomplete_tasks\n results = []\n @tasks.each do |task|\n # Demeterize this, too.\n if task.incomplete?\n results << task\n end\n end\n\n results.sort_by { |task| task.created_at }\n end", "def successful_tasks\n return @successful_tasks\n end", "def actionable_tasks\n\t\tnext_tasks.select{ |t| !t.deferred? }\n\tend", "def repeated_task_executions()\n return @repeated_task_execs if @repeated_task_execs\n result = {}\n tasks = {}\n @test_cases.each do |tc|\n if tc.automation_run\n tc.repeat_task_uuids.each do |rt|\n #puts \"#{rt.inspect}\"\n rt = [rt] if !rt.kind_of?(Array)\n tc_id = tc #tc.uuid\n result[tc_id] = {} if !result[tc_id]\n result[tc_id][rt] = [] if !result[tc_id][rt]\n rt.each do |repeated_task|\n #execs = tc.task_executions(repeated_task)\n #tasks[repeated_task] = Task.find(\"uuid\"=>repeated_task)[0] if !tasks[repeated_task]\n tasks[repeated_task] = @automation.get_task(repeated_task, true)\n #puts \"===> #{tasks[repeated_task]}\"\n execs = TaskExecution.find(\n :task_id => tasks[repeated_task].id, \n :automation_run_id => tc.automation_run.id\n ).to_a\n execs.sort! { |a,b|\n a.start_time <=> b.start_time\n }\n execs.each_with_index do |exec,idx|\n if result[tc_id][rt].size <= idx\n result[tc_id][rt] << []\n end\n result[tc_id][rt][idx] << exec\n end\n end\n end\n end\n end\n @repeated_task_execs = result\n return result\n end", "def available_tasks\n task_names = Task.available_tasks.map(&:name)\n available_task_runs = Run.where(task_name: task_names)\n last_runs = Run.with_attached_csv.where(\n id: available_task_runs.select(\"MAX(id) as id\").group(:task_name)\n )\n\n task_names.map do |task_name|\n last_run = last_runs.find { |run| run.task_name == task_name }\n TaskData.new(task_name, last_run)\n end.sort_by!(&:name)\n end", "def unfinished_tasks\n tasks.unfinished\n end", "def tasks_list\n (self.tasks || EMPTY_STRING).scan(/\\d+/).map{|x| x.to_i}.sort.uniq\n end", "def done\n done_ids = @tasks.keys.find_all do |id|\n @tasks[id].done?\n end\n done_tasks = done_ids.inject({}) do |map, id|\n map[id] = @tasks[id]\n map\n end\n done_ids.each do |id|\n @tasks.delete(id)\n end\n return done_tasks\n end", "def scheduled_tasks\n self.tasks.select { \n |t| t.interval != :startup && t.interval != :shutdown\n }\n end", "def task_list\n return @task_list if @task_list\n @task_list = []\n spec_file_names.each do |file_name_spec|\n next if spec_is_disabled? file_name_spec\n next if skip_globals? file_name_spec\n next unless spec_included? file_name_spec\n get_spec_runs(file_name_spec).each do |run|\n next unless run[:hiera] and run[:facts]\n next unless facts_included? run[:facts]\n next unless hiera_included? run[:hiera]\n task = Noop::Task.new file_name_spec, run[:hiera], run[:facts]\n task.parallel = true if parallel_run?\n @task_list << task\n end\n end\n @task_list\n end", "def completed_tasks\n @tasklist.select { |value| value.status == 'done' }\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
All .rake files in the onetime_tasks_path
def onetime_rake_files tasks_dir = self.tasks_directory return [] unless Dir.exist?(tasks_dir) && !Dir.empty?(tasks_dir) Dir.glob(File.join('**', '*.rake'), base: tasks_dir) end
[ "def task_files\r\n Dir.chdir(Rails.root.join('lib', 'tasks')) do |dir|\r\n @task_files = Dir[\"*.rake\"]\r\n end\r\n @task_files = @task_files.reject{|task|\r\n task !~ /\\Abg_worker_/}.map{|task|\r\n task.sub('bg_worker_', '')\r\n }\r\n end", "def rakefiles\n @rakefiles ||= []\n end", "def load_tasks\n each_railtie_file('tasks/*.rake') { |rake_file| load rake_file } \n end", "def rake_task_paths\n if check_subdirectory('lib/tasks')\n Dir[File.join(path.to_s, 'lib/tasks/**', '*.rake')]\n end\n end", "def load_rakefiles\n Dir[\"#{recipe_dir}/*/*.rake\"].each do |recipe|\n logger.debug \"loading #{recipe}\"\n import recipe\n end\n end", "def list_files_and_tasks(given_dir)\n puts \"\\nList of files and tasks in: #{given_dir}\"\n puts \" Note: this includes all files with 'rake' _anywhere_ in the extension so that it will show *.rake.run and more: Dir.glob(File.join('**', *.rake*')\\n\\n\"\n files = Dir.glob(File.join(\"**\", \"*.rake*\"), base: given_dir)\n\n Rake.with_application do\n\n files.each do |filename|\n puts \" #{filename}\"\n full_rakefile_path = File.absolute_path(File.join(given_dir, filename))\n\n begin\n onetime_rake_tasks = Rake.with_application do\n Rake.load_rakefile(full_rakefile_path)\n end\n rake_task_names = onetime_rake_tasks.tasks.map(&:name)\n\n rake_task_names.each do |taskname|\n puts \" #{taskname}\"\n end\n\n rescue => e\n puts \" - this file doesn't seem to be a Rakefile. Error with Rake.load_rakefile()\"\n puts e\n end\n\n puts \"\\n\"\n end\n end\n\n puts \"\\n\"\n end", "def rakefiles_with_tasks_to_run\n\n rakefiles_with_tasks = new_hash_of_eval_rakefiles\n\n # This isn't efficient, but it's clear:\n all_tasks_to_run.each do |task_to_run|\n rakefilename = task_to_run.filename\n ev_rakefile_to_run = self.all_rakefiles[rakefilename]\n ev_rakefile_to_run.tasks_to_run << task_to_run\n rakefiles_with_tasks[rakefilename] = ev_rakefile_to_run\n end\n\n rakefiles_with_tasks\n end", "def tasks\n output = %x[ #{rake} -f #{@rakefile} -s -T ]\n @tasks ||= output.split(\"\\n\").map do |task|\n task.match(/^rake\\s([^\\s]+)\\s+#\\s(.+)/)[1..2]\n end.compact\n end", "def generate_rake_tasks\n @rake_tasks = filters.collect { |f| f.generate_rake_tasks }.flatten\n end", "def tasks_file(name)\n File.expand_path(File.join(@path, %w[ application tasks ], name))\n end", "def load_tasks\n RakeLoader.new.load_tasks\n end", "def load_rake_tasks\n plugins.each do |plugin_id|\n rake_tasks_glob = File.join(PLUGINS_AVAILABLE_DIR, plugin_id, 'lib/tasks/**/*.rake')\n Dir[rake_tasks_glob].sort.each { |plugin_rake_task| load plugin_rake_task }\n end\n end", "def known_tasks\n task_factory_manager.known_tasks\n end", "def load_tasks\n all_files_for(:tasks).each { |file| load(file) }\n self.class.tasks_loaded = true\n end", "def rake_tasks(&block)\n self.class.rake_tasks(&block)\n end", "def all_evaluated_tasks_in_files(given_dir)\n eval_tasks = []\n\n [SOMETASK1, SOMETASK2, SOMETASK3, SOMETASK4, SOMETASK5].each do |sometask|\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(sometask), File.join(q1_dir(given_dir), SOME_TASKS_RAKEFILE))\n end\n\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(GOODTASK), File.join(blorf_dir(given_dir), GOOD_TASK2_RAKEFILE))\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(SET_WHEN_APPROVED_TASK), File.join(blorf_dir(given_dir), SET_WHEN_APPR2_RAKEFILE))\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(SIMPLETASK), File.join(blorf_dir(given_dir), SIMPLE_TASK_RAKEFILE))\n\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(SET_WHEN_APPROVED_TASK), File.join(blorf2_dir(given_dir), SET_WHEN_APPR_RAKEFILE))\n\n [SIMPLETASK, SOMETASK5].each do |blorf2_simplemore_task|\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(blorf2_simplemore_task), File.join(blorf2_dir(given_dir), SIMPLE_AND_SOME5_RAKEFILE))\n end\n\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(SIMPLETASK), File.join(given_dir, SIMPLE_TASK_RAKEFILE))\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(RUNTHISTASK), File.join(given_dir, RUN_THIS_RAKEFILE))\n\n eval_tasks\n end", "def startup_tasks\n self.tasks.select { |t| t.interval == :startup }\n end", "def generate_rake_tasks\n @rake_tasks = outputs.map do |output, inputs|\n additional_paths = []\n inputs.each do |input|\n\n create_file_task(input.fullpath).dynamic do\n additional_paths += additional_dependencies(input)\n end\n end\n additional_paths.each { |path| create_file_task(path) }\n\n create_file_task(output.fullpath, inputs.map(&:fullpath)) do\n output.create { generate_output(inputs, output) }\n end\n end\n end", "def list_available_build_tasks\n cd 'cookbooks/example'\n unset_bundler_env_vars\n run_simple 'bundle exec rake -T'\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new EvaluatedRakeFile for the rakefilename if we don't already have it. Add all task names to the EvalutedRakeFile that it doesn't already have.
def add_rakefile_and_tasks(rakefilename, task_names) # creates a new EvaluatedRakeFile entry if needed ev_rakefile = self.all_rakefiles[rakefilename] ev_rakefile.add_task_names(task_names) self.all_tasks.concat(ev_rakefile.all_tasks) ev_rakefile end
[ "def add_eval_task_named(task_name)\n new_ev_task = EvaluatedRakeTask.new(task_name, self.filename)\n add_eval_task(new_ev_task)\n\n new_ev_task\n end", "def rakefiles_with_tasks_to_run\n\n rakefiles_with_tasks = new_hash_of_eval_rakefiles\n\n # This isn't efficient, but it's clear:\n all_tasks_to_run.each do |task_to_run|\n rakefilename = task_to_run.filename\n ev_rakefile_to_run = self.all_rakefiles[rakefilename]\n ev_rakefile_to_run.tasks_to_run << task_to_run\n rakefiles_with_tasks[rakefilename] = ev_rakefile_to_run\n end\n\n rakefiles_with_tasks\n end", "def all_evaluated_tasks_in_files(given_dir)\n eval_tasks = []\n\n [SOMETASK1, SOMETASK2, SOMETASK3, SOMETASK4, SOMETASK5].each do |sometask|\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(sometask), File.join(q1_dir(given_dir), SOME_TASKS_RAKEFILE))\n end\n\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(GOODTASK), File.join(blorf_dir(given_dir), GOOD_TASK2_RAKEFILE))\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(SET_WHEN_APPROVED_TASK), File.join(blorf_dir(given_dir), SET_WHEN_APPR2_RAKEFILE))\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(SIMPLETASK), File.join(blorf_dir(given_dir), SIMPLE_TASK_RAKEFILE))\n\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(SET_WHEN_APPROVED_TASK), File.join(blorf2_dir(given_dir), SET_WHEN_APPR_RAKEFILE))\n\n [SIMPLETASK, SOMETASK5].each do |blorf2_simplemore_task|\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(blorf2_simplemore_task), File.join(blorf2_dir(given_dir), SIMPLE_AND_SOME5_RAKEFILE))\n end\n\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(SIMPLETASK), File.join(given_dir, SIMPLE_TASK_RAKEFILE))\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(RUNTHISTASK), File.join(given_dir, RUN_THIS_RAKEFILE))\n\n eval_tasks\n end", "def [](task_name)\n task_name = task_name.to_s\n if task = TASKS[task_name]\n return task\n end\n if task = enhance_with_matching_rule(task_name)\n return task\n end\n if File.exist?(task_name)\n return FileTask.define_task(task_name)\n end\n fail \"Don't know how to rake #{task_name}\"\n end", "def record_set_prev_onetime_task_as_ran(task_name)\n\n File.open(full_filename_set_prev_run_task_has_run, 'w') do |f|\n f.puts '---'\n f.puts '# DO NOT DELETE THIS FILE.'\n f.puts \"# This file is here to record that the task #{task_name} has been run.\"\n f.puts '#'\n f.puts '# Other rake tasks will check to see if this file exists or not and may run tasks accordingly.'\n f.puts 'tasks:'\n\n indent_amt = 2\n indent = indent_amt\n task_sections = task_name.split(':')\n task_sections.each do |s|\n f.puts \"#{' ' * indent}#{s}:\"\n indent += indent_amt\n end\n f.puts \"#{' ' * indent}ran: true\"\n f.puts \"#{' ' * indent}date_ran: #{Time.zone.now}\"\n end\n end", "def add_task_names(task_names)\n return if task_names.empty?\n\n missing_task_names = task_names - all_tasks.map(&:name)\n\n missing_task_names.each { |task_name| add_eval_task_named(task_name) }\n\n all_tasks\n end", "def add_rakefiles(*rakefiles)\n @rakefiles ||= ['merb-core/test/tasks/spectasks']\n @rakefiles += rakefiles\n end", "def add_rakefiles(*rakefiles)\n @rakefiles ||= []\n @rakefiles += rakefiles\n end", "def enhance_with_matching_rule(task_name)\n RULES.each do |pattern, extensions, block|\n if pattern.match(task_name)\n ext = extensions.first\n deps = extensions[1..-1]\n case ext\n when String\n source = task_name.sub(/\\.[^.]*$/, ext)\n when Proc\n source = ext.call(task_name)\n else\n raise \"Don't know how to handle rule dependent: #{ext.inspect}\"\n end\n if File.exist?(source)\n task = FileTask.define_task({task_name => [source]+deps}, &block)\n task.source = source\n return task\n end\n end\n end\n nil\n end", "def [](task_name)\n task_name = task_name.to_s\n if task = TASKS[task_name]\n return task\n end\n if task = enhance_with_matching_rule(task_name)\n return task\n end\n if File.exist?(task_name)\n return FileTask.define_task(task_name)\n end\n raise \"Don't know how to #{MiniRake::Meta::NAME} #{task_name}\"\n end", "def enhance_with_matching_rule(task_name)\n RULES.each do |pattern, extensions, block|\n if pattern.match(task_name)\n ext = extensions.first\n deps = extensions[1..-1]\n case ext\n when String\n source = task_name.sub(/\\.[^.]*$/, ext)\n when Proc\n source = ext.call(task_name)\n else\n fail \"Don't know how to handle rule dependent: #{ext.inspect}\"\n end\n if File.exist?(source)\n task = FileTask.define_task({task_name => [source]+deps}, &block)\n task.source = source\n return task\n end\n end\n end\n nil\n end", "def add_eval_task(ev_task)\n self.all_tasks << ev_task\n end", "def declare_rakefile\n @flavor.class.do_declare_resources do\n # :nocov:\n lazy_vars = Chef::DelayedEvaluator.new do\n { tasks: rake_tasks }\n end\n # :nocov:\n add_templates(%w(Rakefile), :create, variables: lazy_vars)\n end\n end", "def set_and_log_duplicate_tasks(evaluated_tasks)\n\n return [] if evaluated_tasks.empty?\n\n # get all of the task_names that are duplicates (TODO ruby 2.7: replace this with .tally)\n duplicated_names = evaluated_tasks.group_by(&:name).select { |_name, tasks | tasks.size > 1 }.keys\n\n # Guard condition: no duplicate names, so just return\n return [] if duplicated_names.empty?\n\n # get the duplicated tasks for each name; return all of them\n duplicated_names.map{|dup_name| duplicated_tasks_for_name(dup_name, evaluated_tasks) }.flatten\n end", "def load_rakefile; end", "def import_tasks file_name\n raise IOError, \"File not found: #{file_name}\" unless File.exists?(file_name)\n\n tasks = {}\n File.open(file_name, 'r') do |f|\n # Write array of task hashes.\n tasks = YAML.load(f)\n end\n\n existing_tasks = current_task_names\n\n tasks.each do |name, data|\n if existing_tasks.include?(name)\n modify_task(data, name)\n else\n create_task(data)\n end\n end\n end", "def evaluate_pre_tasks\n if using_rake? and Pkg::Config.pre_tasks\n unless Pkg::Config.pre_tasks.is_a?(Hash)\n fail \"The 'pre_tasks' key must be a Hash of depender => dependency pairs\"\n end\n Pkg::Config.pre_tasks.each do |depender, dependency|\n add_dependency(depender, dependency)\n end\n end\n end", "def load_rakefiles\n Dir[\"#{recipe_dir}/*/*.rake\"].each do |recipe|\n logger.debug \"loading #{recipe}\"\n import recipe\n end\n end", "def create_rake_files(base_dir)\n\n one_task_fn = File.join(base_dir, 'one_task.rake')\n make_tasks_in_file(['one_task'], one_task_fn) if ok_to_create?(one_task_fn)\n\n another_task_fn = File.join(base_dir, 'another_task.rake')\n make_tasks_in_file(['another_task'], another_task_fn) if ok_to_create?(another_task_fn)\n\n my_tasks_mine_fn = File.join(base_dir, 'my_tasks_all_mine.rake')\n make_tasks_in_file(['task1', 'task2', 'task3', 'task4'], my_tasks_mine_fn, namespace: 'mine') if ok_to_create?(my_tasks_mine_fn)\n\n tasks_run_all_fn = File.join(base_dir, 'other_tasks_run_all.rake')\n make_tasks_in_file(['other_task1_run_me', 'other_task2_run_me', 'other_task3_run_me', 'other_task_not_run_yet'], tasks_run_all_fn) if ok_to_create?(tasks_run_all_fn)\n\n tasks_mixed_duplicates_fn = File.join(base_dir, 'other_tasks_mixed_duplicates.rake')\n make_tasks_in_file(['other_task2_run_me', 'other_task3_run_me'], tasks_mixed_duplicates_fn) if ok_to_create?(tasks_mixed_duplicates_fn)\n\n task2_duplicate_fn = File.join(base_dir, 'task2_duplicate.rake')\n make_tasks_in_file(['task2'], task2_duplicate_fn, namespace: 'mine') if ok_to_create?(task2_duplicate_fn)\n\n task4_duplicate_fn = File.join(base_dir, 'task4_duplicate.rake')\n make_tasks_in_file(['task4'], task4_duplicate_fn, namespace: 'mine') if ok_to_create?(task4_duplicate_fn)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find a SuccessfulAttempt for the EvaluatedTask. if a SuccessfulAttempt is found, return the first one found. else return nil if none found
def find_successful_attempt_for_task(evaluated_task) self.successful_task_attempts.detect { |already_ran_task| already_ran_task.task_name == evaluated_task.name } end
[ "def get_attempt(problem)\n\t\tif problem\n\t\t\treturn self.attempts.where(problem_id: problem.id).first\n\t\tend\n\tend", "def get_first_failed_job()\n # the first failed job if any, nil otherwise\n return (@retry_jobs_queue.size() > 0)? @retry_jobs_queue.deq() : nil\n end", "def find_task\n task = KanbanpadAPI::Task.find(\n id,\n :params => { :project_id => project_id, :step_id => step_id }\n )\n if task\n return task\n else\n raise TaskMapper::Exception.new \"Task with #{id} was not found\"\n end\n end", "def assignment_solution(ass_id)\n self.final_completed_assignments.select{ |a| a.assignment_id == ass_id }.first\n end", "def get_recovery_exercise_for(task_step:, required_tag_names: ['os-practice-problems'])\n\n # Randomize LO order\n los = (task_step.tasked.los + task_step.tasked.aplos).shuffle\n\n # Try to find unassigned exercises first\n taskees = task_step.task.taskings.collect{|t| t.role}\n los.each do |lo|\n exercise = run(:search,\n not_assigned_to: taskees,\n tag: required_tag_names + [lo]\n ).outputs.items.shuffle.first\n\n return exercise unless exercise.nil?\n end\n\n # No unassigned exercises found, so return a previously assigned exercise\n los.each do |lo|\n exercise = run(:search,\n tag: required_tag_names + [lo]\n ).outputs.items.shuffle.first\n\n return exercise unless exercise.nil?\n end\n\n # Nothing found\n nil\n end", "def best_task_response\n if complete?\n best_score = Float::INFINITY\n best_task = nil\n tasks.each do |t|\n score = t.response_fitness\n if score < best_score\n best_task = t \n best_score = score\n end\n end\n best_task.response_values\n end\n end", "def find_job_placeholder_by_id(id)\n if task = find_job_by_id(id)\n task.planned_task || task\n end\n end", "def is_successful?\n roll if @result.blank?\n return @result[0]\n end", "def get_best_individual_result(score_method_sym = :standard_points)\n meeting_individual_results.is_valid.has_points(score_method_sym).order(score_method_sym).last\n end", "def lookup_task(tg,id)\n result = nil\n tg[0].each do |task|\n result = task if task[0] == id\n end\n result\nend", "def current_user_next_task\n current_user.tasks.to_complete.where(type: type).first || next_unassigned_task\n end", "def find(task_id)\n raise \"task_id is required\" if task_id.nil?\n task = @tasks.select { |task| task.id == task_id.to_i }.first\n raise \"No task with id #{task_id}\" if task.nil?\n task\n end", "def first\n return if error?\n result.first\n end", "def find action, mime_type\n tasks.each do |k,task|\n if task[:action] == action && mime_type =~ %r[#{task[:mime_type_pattern]}]\n return task\n end\n end\n raise TaskNotFound.new action, mime_type\n end", "def next_attempt\n return @next_attempt\n end", "def puzzle_attempt\n @puzzle_attempt = user_rating.rated_puzzle_attempts\n .find_by(id: params[:id])\n end", "def get_run_result(run_name = @config_manager['run.name'])\n RunResult.where(run_name: run_name).first\n end", "def find(name)\n return self if name == self.name\n tasks.inject(nil) { |result, task| result || task.find(name) }\n end", "def next_task_id\n\n # If the non_completed_task_ids array is empty, we're done.\n if non_completed_task_ids.empty?\n :lesson_finished\n\n # Else, if the user is completing the last lesson, return them to the first lesson they skipped and didn't complete\n elsif current_task_id == lesson.tasks.last.id\n non_completed_task_ids.min\n\n # Otherwise, just go on to the next lesson\n else\n current_task_id + 1\n end\n\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new element on any method missing calls. Returns self, so you can chain calls (eg html.div('foo').span('bar') )
def method_missing(method, *args, &block) parts = method.to_s.match(/^([a-z]+[0-9]?)$/) if parts # Assume it's a new element, create the tag tag(parts[1], *args, &block) else # There really is no method... super end end
[ "def method_missing(method, *args, &block)\n super(method, *args) unless block_given?\n options, attrs, element = (args.detect { |arg| arg.is_a?(Hash) } || {}), {}, nil\n\n # handle methods separately if they match the pre-defined elements\n if ELEMENTS.include?(method.to_sym)\n attrs, element = options, method\n else \n attrs, element = { :class => method.to_s.downcase.gsub('_', options[:glue] || ' ') }, :div \n end\n \n wrapper(element, attrs, @template.capture(&block), block.binding)\n end", "def method_missing(m, *args, &block)\n if @page.class.elements.member? m\n @page.send(m, *args, &block).with_parent self\n else\n wrap_watir_call(m, *args, &block)\n end\n end", "def create\n @element = factory.create_element(self, @domtype, @parent, @options) if @domtype \n end", "def element\n return @element if @element\n\n @element = create_element\n @element.add_class class_name\n setup_events\n\n @element\n end", "def method_missing(meth, *args, &block) # :nodoc:\n xpath = _xpath_for_element(meth.to_s, args.shift)\n return nil if xpath.empty?\n\n if block_given?\n xpath.each_with_index do |node, idx|\n @nodes.push(node)\n case block.arity\n when 1\n yield idx\n when 2\n yield self.class.new(node, @namespaces, false), idx\n else\n yield\n end\n @nodes.pop\n end\n self\n else\n node = xpath.first\n\n if node.xpath('text()').length == 1\n content = node.xpath('text()').first.content\n case meth.to_s\n when /\\?$/\n !! Regexp.new(/(t(rue)?|y(es)?|1)/i).match(content)\n else\n content\n end\n else\n self.class.new(node, @namespaces, false)\n end\n end\n end", "def factory_twiml_block(meth, *args)\n if meth =~ /twiml_appointments_/\n klass = meth.to_s.gsub(\"twiml_appointments_\", \"skej/twiml/appointments/\").classify\n else\n klass = meth.to_s.gsub(\"twiml_\", \"skej/twiml/\").classify\n end\n\n # Make the string representation a real Class object.\n klass = klass.constantize\n\n # Prepare view local variables\n data = { device: @device, session: @session, debug: generate_debug_formatted_message }\n if args.length > 0 and args[0].kind_of? Hash\n data.merge! args[0]\n end\n\n log \"twiml_view_factory -> #{klass.name.underscore}\"\n\n # Instantiate the new instance from the dynamic Klass\n # we generated earlier.\n instance = klass.new(data)\n\n # Return the TwiML view instance\n instance\n end", "def create_element(name, *contents_or_attrs, &block); end", "def element(name, klass)\n define_method(name.to_sym) do |*args, &block|\n base = klass.send(:new, self, *args, &block)\n instance_variable_get(:@children) << base\n base\n end\n end", "def method_missing(method, *args, &block)\n return super unless builder\n\n builder.send(method, *args, &block)\n end", "def add_form_element(obj = nil, method = 'attribute', options = {}, html_options = {})\n type = options[:type] || 'text'\n type = nil unless %w(file text hidden textarea password select checkbox).include?(type)\n label = options[:label] || method.humanize.titleize\n\n description = options[:description]\n\n html_options[:class] = \"#{type} form_elem #{html_options[:class]}\"\n label_for = if html_options.key?(:id)\n html_options[:id]\n else\n \"#{obj}_#{method}\"\n end\n\n element = case type\n when 'text'\n text_field(obj, method, html_options)\n when 'hidden'\n hidden_field(obj, method, html_options)\n when 'textarea'\n text_area(obj, method, html_options)\n when 'password'\n password_field(obj, method, html_options)\n when 'select'\n select_options = options[:select_options]\n selected = options[:selected]\n include_blank = options[:include_blank]\n\n select(obj, method, select_options, { selected: selected, include_blank: include_blank }, html_options)\n when 'checkbox'\n if [true, 'true', 1, '1'].include?(html_options[:value])\n html_options[:checked] = 'checked'\n else\n ''\n end\n check_box(obj, method, html_options)\n when 'file'\n file_field(obj, method, html_options)\n else\n ''\n end\n\n case type\n when 'hidden'\n element\n else\n <<-EOS.html_safe\n<div class=\"group clearfix\">\n <div class=\"row\">\n <div class=\"column grid2of5\">\n <div class=\"spacer\">\n <label for=\"#{label_for}\">#{label}<span>#{description}</span></label>\n </div>\n </div>\n\n <div class=\"column grid3of5\">\n <div class=\"#{'boxed ' unless type == 'checkbox'}spacer\">\n #{element}\n </div>\n </div>\n </div>\n</div>\n EOS\n end\n end", "def method_missing(method_name, *args, &block)\n case \n when KNOWN_ELEMENTS.include?(method_name.to_s.gsub(/^uniq_/,''))\n # page_object.uniq_xxx(hash)\n meth = method_name.to_s.gsub(/^uniq_/,'')\n e = Element.new(method_name.to_sym, meth)\n e.instance_eval { locator(args[0]); required(true) }\n @elements << e\n when has_eset?(method_name)\n # page_object.some_elements_set\n eset = eset_for(method_name)\n PageObjectWrapper.current_result = PageObject.return_array_of_watir_elements(eset)\n when has_element?(method_name)\n # page_object.some_element\n element = element_for(method_name)\n PageObjectWrapper.current_result = PageObject.return_watir_element element\n when FEED_ALL.match(method_name)\n # page_object.feed_all(:fresh_food)\n PageObjectWrapper.current_result = feed_elements(@elements, *args)\n when (FEED.match(method_name) and has_eset?($1))\n # page_object.feed_some_elements_set(:fresh_food)\n eset = eset_for($1)\n PageObjectWrapper.current_result = feed_elements(eset.elements, *args)\n when (FEED.match(method_name) and has_element?($1))\n # page_object.feed_some_element(:fresh_food)\n e = element_for($1)\n if [true, false].include? args[0] or args[0].is_a? String \n PageObjectWrapper.current_result = feed_field(e, args[0])\n else\n PageObjectWrapper.current_result = feed_elements([e], *args)\n end\n when (FIRE_ACTION.match(method_name) and has_action?($1))\n # page_object.fire_some_action\n a = action_for($1)\n PageObjectWrapper.current_result = fire_action(a, *args)\n when (FIRE_ACTION.match(method_name) and has_alias?($1))\n # page_object.fire_some_action\n a = alias_for($1)\n PageObjectWrapper.current_result = fire_action(a, *args)\n when (VALIDATE.match(method_name) and has_validator?($1))\n # page_object.validate_something\n v = validator_for($1)\n PageObjectWrapper.current_result = run_validator(v, *args)\n when (SELECT_FROM.match(method_name) and has_table?($1))\n # page_object.select_from_some_table(:header_column, {:column => 'value'})\n table = table_for($1)\n PageObjectWrapper.current_result = select_from(table, *args)\n when (SELECT_ROW_FROM.match(method_name) and has_table?($1))\n # page_object.select_row_from_some_table(:number => 1, :column1 => value1, :column2 => value3, ...)\n table = table_for($1)\n PageObjectWrapper.current_result = select_row_from(table, args[0])\n when (PAGINATION_EACH.match(method_name) and has_pagination?($1))\n # page_object.each_pagination\n pagination = pagination_for($1)\n PageObjectWrapper.current_result = run_each_subpage(pagination, *args, &block)\n when (PAGINATION_OPEN.match(method_name) and has_pagination?($1))\n # page_object.open_padination(1)\n pagination = pagination_for($1)\n PageObjectWrapper.current_result = open_subpage(pagination, *args)\n when (PRESS.match(method_name) and has_element?($1))\n # page_object.press_element\n element = element_for($1)\n PageObjectWrapper.current_result = press(element)\n else\n super\n end\n end", "def method_missing(method, *args, &block)\n return super unless builder\n\n builder.send(method, *args, &block)\n end", "def create_element\n scope = (self.parent ? parent.element : Element)\n\n if el = self.class.element\n scope.find el\n else\n scope.new tag_name\n end\n end", "def temporary(&block)\n build Element, &block\n end", "def get(*arguments)\n return element unless callable_selector?\n if (arguments.length > 0) || !requires_parameters?\n element(@selector.call(*arguments))\n else\n self\n end\n end", "def factory_method_for(tag); end", "def build(klass, *args, &block)\n element = klass.new(arbre_context)\n within(element) { element.build! *args, &block }\n element\n end", "def method_missing(method, *arguments, &block)\n if xhtml_block?(method, arguments)\n @xml.__send__(method, *arguments) do\n @xml.div(xmlns: \"http://www.w3.org/1999/xhtml\") do |xhtml|\n block.call(xhtml)\n end\n end\n else\n @xml.__send__(method, *arguments, &block)\n end\n end", "def method_missing(meth, *args, &block)\n # Check to see if it can be evaluated\n if(matches? meth)\n #Defines the method and caches it to the class\n self.class.send(:define_method, meth) do\n if element_id_exists_method?(meth)\n if respond_to?(meth.to_s.chop)\n begin\n send meth.to_s.chop\n rescue Selenium::WebDriver::Error::NoSuchElementError => e\n return false\n end\n return true\n end\n elsif wait_method?(meth)\n send :wait_for, meth.to_s.sub('wait_for_','').to_sym\n elsif navigate_method?(meth)\n send :navigate_to, instance_variable_get(\"@#{meth.to_s.sub('navigate_to_','')}\")\n elsif element_id_method?(meth)\n @driver.find_element(:id, meth)\n end\n end\n # calls the method\n send meth, *args, &block\n else\n super\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /public_repositories GET /public_repositories.json
def index @public_repositories = PublicRepository.all end
[ "def repositories\n response = self.class.get('/repositories').body\n JSON.parse(response)\n end", "def list_repositories\n JSON.parse(request(:get, ''))\n end", "def repositories\n get_request(\"/1.0/user/repositories\")\n end", "def public_repositories\n raw_repos = GitHub::API.json(\"/organizations/#{self.login}/public_repositories\")['repositories']\n repos = []\n\n raw_repos.each do |repo|\n repos << GitHub::Repository.new(repo)\n end\n\n return repos\n end", "def get_public_repos(user_name)\n get(\"/users/#{user_name}/repos\")\n end", "def fetch_repositories\n client.repositories\n end", "def repos\n Rails.logger.info \"> GitHubApi: repos\"\n return ReposAPI.new(self)\n end", "def find_repositories\n @repos = GithubApi.call :repos\n end", "def get(base_url, options)\n Repositories.new(\"#{base_url}/api/repositories\", options)\n end", "def github_request\n \tgithub = Github.new\n \trepos = github.repos.list user: params['username']\n\n \trespond_to do |format|\n format.json { render json: repos }\n end\n end", "def repos\n ReposAPI.new(self)\n end", "def index\n @git_hub_repos = GitHubRepo.all\n end", "def show\n @repo = @user.repos.find_by_name!(params[:id])\n render json: to_json(@repo)\n end", "def repos(project)\n get_api(\"projects/#{project}/repos?limit=1000\")\n end", "def fetch_all_repos\n access_token = User.first.oauth_token\n url = \"https://api.github.com/orgs/zense/repos?access_token=#{access_token}\"\n all_repos = parse_json(url)\n return all_repos\n end", "def repos\n api.repos.map(&:to_hash)\n end", "def index\n repos = CodeburnerUtil.get_repos\n\n render(:json => { \"count\": repos.length, \"results\": repos })\n end", "def repos\n @repos ||= get(\"/repos/show/#{login}\")['repositories'].map { |r| Repo.new(connection, r) }\n end", "def repositories\n result = {}\n repositories = @catalog.server.request_json(:get, self.path(:repositories),\n :expected_status_code => 200).each do |repo|\n result[repo['id']] = Repository.new(:catalog => self, :id => repo['id'])\n end\n result\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /public_repositories POST /public_repositories.json
def create @public_repository = PublicRepository.new(public_repository_params) respond_to do |format| if @public_repository.save format.html { redirect_to @public_repository, notice: 'Public repository was successfully created.' } format.json { render :show, status: :created, location: @public_repository } else format.html { render :new } format.json { render json: @public_repository.errors, status: :unprocessable_entity } end end end
[ "def index\n @public_repositories = PublicRepository.all\n end", "def create\n #@repo = Repo.new(repo_params)\n\n user= params[:user]\n repo= params[:repos]\n\n url = BASE_URL + \"repos/\" + user + \"/\" + repo + \"/collaborators\"\n # url = BASE_URL + \"repos/rails/rails/collaborators\"\n # url = BASE_URL + \"repositories\"\n @repo = JSON.parse(open(url).read)\n\n # respond_to do |format|\n # if @repo.save\n # format.html { redirect_to @repo, notice: 'Repo was successfully created.' }\n # format.json { render action: 'show', status: :created, location: @repo }\n # else\n # format.html { render action: 'new' }\n # format.json { render json: @repo.errors, status: :unprocessable_entity }\n # end\n # end\n end", "def create\n params[:repo].delete(:pull_requests)\n @repo = Repo.new(params[:repo])\n\n respond_to do |format|\n if @repo.save\n format.json { render json: @repo, status: :created, location: @repo }\n else\n format.json { render json: @repo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @repository = current_user.repositories.new(params[:repository])\n\n respond_to do |format|\n if @repository.save\n format.html { redirect_to @repository, notice: 'Repository was successfully created.' }\n format.json { render json: @repository, status: :created, location: @repository }\n else\n format.html { render action: \"new\" }\n format.json { render json: @repository.errors, status: :unprocessable_entity }\n end\n end\n end", "def repositories\n response = self.class.get('/repositories').body\n JSON.parse(response)\n end", "def create!\n Dydra::Client.post \"#{account}/repositories\", { :dydra_repository => { :name => name }}\n end", "def list_repositories\n JSON.parse(request(:get, ''))\n end", "def create\n Rails.logger.info \">> GitthubRepoController: create\"\n\n github_client = GitHubApi.new\n github_client.init_with_token(current_user.github_account.access_token)\n @github_repository = github_client.repos.get( params[:owner], params[:repository])\n\n Rails.logger.info \">> Chosen Repo: #{@github_repository.url}\"\n\n respond_to do |format|\n if @project.create_github_repository(name: params[:repository], owner: params[:owner], url: @github_repository.url, user_id: current_user.id )\n format.html { redirect_to project_github_path(@project), flash: { success: 'Github repository was successfully linked.' }}\n format.json { render json: @project.github_repository, status: :created, location: @tools_github_repository }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.github_repository.errors, status: :unprocessable_entity }\n end\n end\n end", "def repositories\n get_request(\"/1.0/user/repositories\")\n end", "def public_repositories\n raw_repos = GitHub::API.json(\"/organizations/#{self.login}/public_repositories\")['repositories']\n repos = []\n\n raw_repos.each do |repo|\n repos << GitHub::Repository.new(repo)\n end\n\n return repos\n end", "def push_repositories\n @push_repositories\n end", "def create_repo\n info = JSON.parse(HTTPRequest.repo(@owner, @repo))\n GitAnalysis::Repository.new(info['id'], info['name'], info['owner']['login'], info['language'])\n end", "def create\n @git_hub_repo = GitHubRepo.new(git_hub_repo_params)\n\n respond_to do |format|\n if @git_hub_repo.save\n format.html { redirect_to @git_hub_repo, notice: 'Git hub repo was successfully created.' }\n format.json { render :show, status: :created, location: @git_hub_repo }\n else\n format.html { render :new }\n format.json { render json: @git_hub_repo.errors, status: :unprocessable_entity }\n end\n end\n end", "def github_request\n \tgithub = Github.new\n \trepos = github.repos.list user: params['username']\n\n \trespond_to do |format|\n format.json { render json: repos }\n end\n end", "def repos\n Rails.logger.info \"> GitHubApi: repos\"\n return ReposAPI.new(self)\n end", "def fetch_repositories\n client.repositories\n end", "def create_repository(name, proxy, url, id, policy, provider)\n json = if proxy\n create_proxy_repository_json(name, url, id, policy, provider)\n else\n create_hosted_repository_json(name, id, policy, provider)\n end\n response = nexus.post(nexus_url(\"service/local/repositories\"), :body => json, :header => DEFAULT_CONTENT_TYPE_HEADER)\n case response.status\n when 201\n return true\n when 400\n raise CreateRepsitoryException.new(response.content)\n else\n raise UnexpectedStatusCodeException.new(response.status)\n end\n end", "def add_repo\n url = params[:url]\n\n # read owner and name from url\n ident = url.gsub(\"https://github.com/\", \"\").strip\n owner = ident.split(\"/\")[0].strip\n name = ident.split(\"/\")[1].strip\n\n # find_or_initialize repo (to ensure that there are no duplicates)\n repo = Repo.find_or_initialize_by_owner_and_name(owner, name)\n\n respond_to do |format|\n # Initialize Repo, including check whether or not it exists on github\n if repo.new_record?\n # repo is a new record, up to now unknown\n if repo.initialize_repo\n # repo is now in database\n format.html { redirect_to \"/repo/#{repo.ident}/\", notice: \"Repo '#{repo.ident}' added. What might be good tags for it?.\" }\n else\n # repo did not exist on github\n format.html { redirect_to :root, notice: \"Repo '#{repo.ident}' could not be found on github.\"}\n end\n else\n # Repo already in database\n # run an update\n if repo.initialize_repo\n format.html { redirect_to \"/repo/#{repo.ident}/\", notice: \"Repo '#{repo.ident}' added. What might be good tags for it?\" }\n else\n format.html { redirect_to :root, notice: \"Repo '#{repo.ident}' could not be found on github.\"}\n end\n end\n end\n end", "def create_repo(name)\n project = Project.find_by_slug($in_project)\n repo = Repository.new({\n :project => project,\n :user => project.user,\n :owner => project.owner,\n :merge_requests_enabled => \"0\"\n }.merge(name)) \n repo.save\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /public_repositories/1 DELETE /public_repositories/1.json
def destroy @public_repository.destroy respond_to do |format| format.html { redirect_to public_repositories_url, notice: 'Public repository was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @repository = Repository.find(params[:id])\n @repository.destroy\n\n respond_to do |format|\n format.html { redirect_to repositories_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @repo = Repo.find(params[:id])\n @repo.destroy\n\n respond_to do |format|\n format.html { redirect_to repos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @repository = @project.repositories.find(params[:id])\n @repository.destroy\n\n respond_to do |format|\n format.html { redirect_to project_repositories_path }\n format.xml { head :ok }\n end\n end", "def delete(path, params)\n headers = {:Authorization => \"token #{token}\", :content_type => :json, :accept => :json}\n res = RestClient.delete(\"#{github_api_uri}/#{path}\", params.to_json, headers)\n Yajl.load(res)\n end", "def destroy\n @repo.destroy\n respond_to do |format|\n format.html { redirect_to repos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @repository = Repository.find(params[:id])\n @repository.destroy\n\n respond_to do |format|\n format.html { redirect_to(repositories_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @client_repo.destroy\n respond_to do |format|\n format.html { redirect_to client_repos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n repo = assets_repo\n repo.destroy(params[:id])\n\n respond_to do |format|\n format.html { redirect_to v_assets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @repo = Repo.find(params[:id])\n @repo.destroy\n\n respond_to do |format|\n format.html { redirect_to(repos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @gb_repo = GbRepo.find(params[:id])\n @gb_repo.destroy\n\n respond_to do |format|\n format.html { redirect_to gb_repos_url }\n format.json { head :no_content }\n end\n end", "def delete!\n @repo.delete!\n end", "def delete_repositories\n handle_repository_delete(@object_id)\n end", "def destroy\n @project.github_repository.destroy\n respond_to do |format|\n format.html { redirect_to project_github_path(@project), flash: { success: 'Github repository was successfully unlinked.' } }\n format.json { head :no_content }\n end\n end", "def destroy\n @repository_portion = RepositoryPortion.find(params[:id])\n @repository_portion.destroy\n\n respond_to do |format|\n format.html { redirect_to repository_portions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @git_repo = GitRepo.find(params[:id])\n @git_repo.destroy\n\n respond_to do |format|\n format.html { redirect_to(git_repos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @source_repo.destroy\n respond_to do |format|\n format.html { redirect_to source_repos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @git_hub_repo.destroy\n respond_to do |format|\n format.html { redirect_to git_hub_repos_url, notice: 'Git hub repo was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete(*args)\n arguments(args, required: [:user, :repo])\n\n delete_request(\"/repos/#{arguments.user}/#{arguments.repo}\", arguments.params)\n end", "def destroy\n authorize! :destroy, @repo\n @repo_cred.destroy\n respond_to do |format|\n format.html { redirect_to @repo, notice: 'Repo cred was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use this method in DSL methods to add a file pattern to config
def add_file_pattern(name, pattern_string) if name.to_s !~ FILE_PATTERN_NAME_REGEX raise ArgumentError.new("A file pattern name must match this regex: #{ FILE_PATTERN_NAME_REGEX.inspect }") end @file_patterns[name.to_sym] = pattern_string.to_s end
[ "def file_pattern(name, pattern_string = nil, &pattern_block)\n if block_given?\n config.add_file_pattern(name, pattern_block.call)\n elsif pattern_string\n config.add_file_pattern(name, pattern_string)\n else\n raise(RtfileError, \"You must provide either pattern_string or pattern_block arguments to file_pattern\")\n end\n nil\n end", "def pattern=(pattern)\n @root, @wildcard = Wow::Package::FilePattern.split_pattern(pattern)\n end", "def add_matching(pattern)\n Path.glob( pattern ) do | path |\n exclude?( path ) or self << path\n end\n end", "def add_pattern(pattern)\n @patterns << pattern\n end", "def setup_file_member(member, pattern, &block)\n old_value = instance_variable_get(\"@#{member}\")\n new_value = FileList[pattern].find_all { |path| File.file?(path) }\n new_value.map!(&block) if block\n instance_variable_set(\"@#{member}\", old_value + new_value)\n end", "def test_files_pattern=(pattern)\n warn 'test_files_pattern= is deprecated in QUnited rake task config, use test_files= with a pattern'\n @test_files = pattern\n end", "def add_pattern(pattern)\n patterns << pattern\n end", "def patterns_for_file( file )\n Hash(config_file(file)[:patterns]).keys + \\\n Hash(defaults[:patterns]).keys\n end", "def source_files_pattern=(pattern)\n warn 'source_files_pattern= is deprecated in QUnited rake task config, use source_files= with a pattern'\n @source_files = pattern\n end", "def pattern_definition\n pattern_definitions[pattern_definition_filename] ||= begin\n m = platform::PatternDefinition.new(manually_register: true)\n name = \"#{pattern_definition_filename}_pattdef.csv\"\n if Origen.config.program_prefix\n unless name =~ /^#{Origen.config.program_prefix}/i\n name = \"#{Origen.config.program_prefix}_#{name}\"\n end\n end\n m.filename = name\n m.id = pattern_definition_filename\n m\n end\n end", "def ignore_files=(patterns)\n @finder.add_patterns(patterns)\n end", "def validate_file_patterns\n attributes = DSL.attributes.values.select(&:file_patterns?)\n attributes.each do |attrb|\n patterns = consumer.send(attrb.name)\n if patterns.is_a?(Hash)\n patterns = patterns.values.flatten(1)\n end\n patterns.each do |pattern|\n if pattern.start_with?('/')\n error \"File patterns must be relative and cannot start with a \" \\\n \"slash (#{attrb.name}).\"\n end\n end\n end\n end", "def validate_file_patterns\n attributes = DSL.attributes.values.select(&:file_patterns?)\n attributes.each do |attrb|\n patterns = consumer.send(attrb.name)\n if patterns.is_a?(Hash)\n patterns = patterns.values.flatten(1)\n end\n patterns.each do |pattern|\n if pattern.start_with?('/')\n error '[File Patterns] File patterns must be relative ' \\\n \"and cannot start with a slash (#{attrb.name}).\"\n end\n end\n end\n end", "def register_parsed(config, filepath, options)\n allow_configatron_changes do\n directive = {\n config: config,\n filepath: filepath,\n options: options,\n }\n\n validate_config(directive)\n @registrations << directive\n\n allow_configatron_changes do\n mixin_config(directive)\n end\n end\n end", "def add_pattern( pattern )\n type_check( pattern, Elements::Pattern )\n assert( !name_defined?(name), \"name [#{name}] is already in use\" )\n \n @patterns[pattern.name] = pattern\n end", "def validate_file_patterns\n attributes = DSL.attributes.values.select(&:file_patterns?)\n attributes.each do |attrb|\n patterns = consumer.send(attrb.name)\n\n if patterns.is_a?(Hash)\n patterns = patterns.values.flatten(1)\n end\n\n if patterns.respond_to?(:each)\n patterns.each do |pattern|\n if pattern.respond_to?(:start_with?) && pattern.start_with?('/')\n results.add_error('File Patterns', 'File patterns must be ' \\\n \"relative and cannot start with a slash (#{attrb.name}).\")\n end\n end\n end\n end\n end", "def add_file_parsing_patterns(hash)\n hash.each_pair do |regexp, parser|\n file_parsers[regexp] = parser\n end\n end", "def load_config(filename)\n yml = YAML.load_file(filename)\n yml.each do |key, value| \n next if key == 'Templates'\n\n if key == 'PackageDirs'\n # PackageDirs.register value\n elsif key == 'AppDirs' \n # ApplicationDirMatcher.register value\n else\n app_matcher.register value\n end \n end\n end", "def add_matching(pattern)\n self.class.glob(pattern).each do |fn|\n self << fn unless excluded_from_list?(fn)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use this method in DSL methods to add a kramdown converter method to config
def add_kramdown_converter_method(name, method_name) @kramdown_converter_methods[name.to_sym] = method_name.to_sym end
[ "def kramdown_converter_method(name, method_name)\n config.add_kramdown_converter_method(name, method_name)\n end", "def kramdown_converter_method(name)\n get_config_val(@kramdown_converter_methods, name)\n end", "def kramdown_conversion_method_name\n :to_kramdown_repositext\n end", "def kramdown_parser(name, class_name)\n config.add_kramdown_parser(name, class_name)\n end", "def html_converter_class\n ::Kramdown::Converter::Html\n end", "def converter\n\n end", "def convert_save(*)\n RPF::Plugin::Kramdown.convert_save_to_html\n end", "def to_karat(**options) = convert_to('karat', **options)", "def converter(name, &blk)\n if blk\n (converters[name.to_sym] ||= new(name.to_sym)).instance_eval(&blk)\n else\n converters[name.to_sym] or raise ::ArgumentError, \"No converter #{name.to_s.dump} found\"\n end\n end", "def method_missing(id, *attr, &block)\n if id.to_s =~ /^to_(\\w+)$/ && (name = Utils.camelize($1)) &&\n try_require('converter', name) && Converter.const_defined?(name)\n output, warnings = Converter.const_get(name).convert(@root, @options)\n @warnings.concat(warnings)\n output\n else\n super\n end\n end", "def define_ch_config_method(ch)\n klass_name = ch.to_s.split('_').map(&:capitalize).join\n method_proc = -> { self.class.const_get(klass_name).config }\n self.class.send(:define_method, ch, method_proc)\n end", "def translate(config)\n end", "def converter_for(method_name, *converters, &default)\n # puts \"[converter for #{self}, #{method_name}]\"\n sheep = lambda do |direct, this, *values|\n converter = converters.find { |e| e.length == values.length }\n converter = Array.new(values.length, default) unless converter\n\n # FIXME: Better error reporting on many things which can fail\n i = 0\n values = values.inject([]) do |s, value|\n conv = converter[i]\n if conv.kind_of? Proc\n s << conv.call(value)\n else\n s << CONVERTERS[converter[i]].call(value)\n end\n i += 1\n s\n end\n if direct\n return this.method(\"set_\" + method_name.to_s).call(*values)\n else\n return values\n end\n end\n # define a setter for normal usage\n unless method_name == :new\n self.__send__(:define_method, method_name.to_s + \"=\") do |*values|\n sheep.call(true, self, *values)\n end\n end\n # define a build/with usage\n self.__send__(:define_method, method_name.to_s + ARG_CONVERTER_SUFFIX) do |*values|\n sheep.call(false, self, *values)\n end\n end", "def register_style_converter(ast_node, prop_name, converter); end", "def add_config(converter, config)\n converter.instance_exec(:\"@config\") do |var|\n instance_variable_set(var, config)\n end\n converter\n end", "def setup\n @config[\"syntax_highlighter\"] ||= highlighter\n @config[\"syntax_highlighter_opts\"] ||= {}\n @config[\"syntax_highlighter_opts\"][\"default_lang\"] ||= \"plaintext\"\n @config[\"syntax_highlighter_opts\"][\"guess_lang\"] = @config[\"guess_lang\"]\n @config[\"coderay\"] ||= {} # XXX: Legacy.\n modernize_coderay_config\n make_accessible\n end", "def translations_converter\n @translations_converter || ->(raw_data) { raw_data.to_yaml }\n end", "def setup\n @config[\"syntax_highlighter\"] ||= highlighter\n @config[\"syntax_highlighter_opts\"] ||= {}\n @config[\"syntax_highlighter_opts\"][\"default_lang\"] ||= \"plaintext\"\n @config[\"syntax_highlighter_opts\"][\"guess_lang\"] = @config[\"guess_lang\"]\n @config[\"coderay\"] ||= {} # XXX: Legacy.\n modernize_coderay_config\n end", "def transformation_command\n super + CONVERT_OPTIONS\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve a kramdown converter method
def kramdown_converter_method(name) get_config_val(@kramdown_converter_methods, name) end
[ "def kramdown_conversion_method_name\n :to_kramdown_repositext\n end", "def kramdown_converter_method(name, method_name)\n config.add_kramdown_converter_method(name, method_name)\n end", "def add_kramdown_converter_method(name, method_name)\n @kramdown_converter_methods[name.to_sym] = method_name.to_sym\n end", "def html_converter_class\n ::Kramdown::Converter::Html\n end", "def processing_method_symb\n name=\"convert_#{@conversion_type}_to_#{@preview_format_symb}\"\n if @conversion_type.eql?(:video)\n case @preview_format_symb\n when :mp4\n name=\"#{name}_using_#{@options.video_conversion}\"\n when :png\n name=\"#{name}_using_#{@options.video_png_conv}\"\n end\n end\n Log.log.debug(\"method: #{name}\")\n return name.to_sym\n end", "def converter\n\n end", "def converter_for transform\n @converter_cache[transform]\n end", "def get_converter\n eval(\"RedmineCharts::#{get_type.to_s.camelize}DataConverter\")\n end", "def genability_method_name_converter(method_name)\n method_name.to_s.gsub(/(?:^|_)(.)/){ $1.upcase }.gsub(/^[A-Z]/){ $&.downcase }.to_sym\n end", "def converter_for transform\n @converter_map[transform] ||= find_converter transform\n end", "def convert_save(*)\n RPF::Plugin::Kramdown.convert_save_to_html\n end", "def converter\n @converter ||= self.site.converters.find { |c| c.matches(self.ext) }\n end", "def converter\n unit.converter\n end", "def to_kilogram(**options) = convert_to('kilogram', **options)", "def kramdown_parser(name, class_name)\n config.add_kramdown_parser(name, class_name)\n end", "def kcode\n end", "def html5_converter\n converter.instance_variable_get(\"@delegate_converter\")\n end", "def my_convert\n `which convert`.chomp\nend", "def converter(name, &blk)\n if blk\n (converters[name.to_sym] ||= new(name.to_sym)).instance_eval(&blk)\n else\n converters[name.to_sym] or raise ::ArgumentError, \"No converter #{name.to_s.dump} found\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes a glob pattern from file spec
def compute_glob_pattern(file_spec) segments = file_spec.split(Repositext::Cli::FILE_SPEC_DELIMITER) r = '' if segments.all? { |e| e =~ BASE_DIR_NAME_REGEX || e =~ FILE_PATTERN_NAME_REGEX } # file_spec consists of named base_dir and/or file_pattern bd = segments.detect { |e| e =~ BASE_DIR_NAME_REGEX } # e.g., 'content_dir' fp = segments.detect { |e| e =~ FILE_PATTERN_NAME_REGEX } # e.g., 'at_files' r << base_dir(bd) if bd r << file_pattern(fp) if fp else # interpret file_spec as glob pattern, either an absolute path, or # a relative path, based on current working directory. # NOTE: this doesn't necessarily have to contain '*'. It could be the # path to a single file. if '/' == file_spec[0] # absolute path, use as is r = file_spec else # relative path, based on current working directory # Note: we could use just the file_spec since relative paths are # based on pwd by default. I just wanted to make the behavior obvious. r = File.expand_path(file_spec, Dir.pwd) end end r end
[ "def glob(path); end", "def private_glob_expression\n \"#{base_path}/*_spec.rb\"\n end", "def pattern_with_glob_pattern(*pattern, **options)\n options[:uri_decode] ||= false\n pattern = Mustermann.new(*pattern.flatten, **options)\n @glob_patterns ||= {}\n @glob_patterns[pattern] ||= GlobPattern.generate(pattern)\n [pattern, @glob_patterns[pattern]]\n end", "def generate_glob_filter(glob)\n # Negative glob starts with '!'\n negative = glob.start_with?('!')\n # Strip leading '!' then\n glob.remove_prefix!('!') if negative\n lambda do |path|\n matches = File.fnmatch(glob, path, GLOB_MATCH_MODE)\n # inverse match if glob is negative\n matches = !matches if negative\n matches\n end\n end", "def glob2pattern(glob_string)\n inner_pattern = glob_string.gsub(/(.)/) do |c|\n GLOB_PATTERN_MAP[c] || Regexp::escape(c)\n end\n return Regexp.new(\"^#{inner_pattern}$\")\n end", "def file_glob\n if file_types.nil?\n '*'\n else\n \"*{#{file_types.join(',')}}\"\n end\n end", "def collapse_glob_patterns; end", "def glob\n user_specified_options[:glob]\n end", "def public_glob_expression\n \"#{base_path}/#{expanded_name}_spec.rb\"\n end", "def glob_to_regexp(glob)\n is_glob_pattern = glob.include?('*')\n\n regexp = if is_glob_pattern\n glob.\n gsub(%r{/\\*\\*$}, '<<to_eol_wildcards>>').\n gsub('**', '<<to_wildcards>>').\n gsub('*', '[^/]*').\n gsub('.', '\\.').\n gsub('<<to_eol_wildcards>>', '.*').\n gsub('<<to_wildcards>>', '.*')\n else\n \"#{glob}.*\"\n end\n\n Regexp.new(\"^#{regexp}$\", Regexp::IGNORECASE)\n end", "def glob_match (filenames, pattern)\n\t# Escape the '*', '?', and '.' characters\n\tpattern.gsub!(/[\\*\\?\\.]/, '*' => '.*', '?' => '.', '.' => '\\.') \t\n\tregex = Regexp.new(pattern)\n\t#select returns a new array\n\tfilenames.select do |filename|\n\t\tfilename =~ regex\n\tend\nend", "def parse_simple_glob(glob)\n glob\n end", "def glob(pattern)\n if hrx?\n @archive.glob(pattern).select {|e| e.is_a?(HRX::File)}.map(&:path)\n else\n recursive = pattern.include?(\"**\")\n physical_pattern = recursive ? \"{#{pattern},**/*.hrx}\" : pattern\n Dir.glob(File.join(@path, physical_pattern), File::FNM_EXTGLOB).flat_map do |path|\n relative = Pathname.new(path).relative_path_from(@path).to_s\n next relative unless recursive && path.end_with?(\".hrx\")\n\n dir = path[0...-\".hrx\".length]\n relative_dir = relative[0...-\".hrx\".length]\n archive = self.class._hrx_cache[dir] ||= HRX::Archive.load(path)\n archive.glob(pattern).map {|inner| \"#{relative_dir}/#{inner.path}\"}\n end\n end\n end", "def glob(*args)\n Glob.new(self, *args)\n end", "def rel_glob(pattern, expand: false)\n\t\t\t\tg=[]\n\t\t\t\tself.cd { g=Dir.glob(pattern) }\n\t\t\t\tif expand\n\t\t\t\t\tg.map {|f| self+f} \n\t\t\t\telse\n\t\t\t\t\tg.map {|f| Pathname.new(f)}\n\t\t\t\tend\n\t\t\tend", "def glob\n \"**/*\"\n end", "def getFilePattern(filePattern)\n return if filePattern.nil?\n File.split(filePattern).inject do |memo, obj| \n File.join(memo, obj.split(/\\./).join('*.'))\n end\nend", "def glob_and_padding_for(path)\n plen = 0\n glob_pattern = path.gsub(NUMBERS_AT_END) do\n plen = $1.length\n ('[0-9]' * plen) + $2.to_s\n end\n return nil if glob_pattern == path\n \n [glob_pattern, plen]\n end", "def glob(*patterns)\n patterns << \"**/*\" if patterns.empty?\n patterns.collect! {|pattern| expand(pattern) }\n Dir[*patterns].uniq\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes a hash with validation file specs from input_file_specs
def compute_validation_file_specs(input_file_specs) input_file_specs.inject({}) { |m,(fs_name, fs_string)| base_dir, file_pattern = fs_string.split(Repositext::Cli::FILE_SPEC_DELIMITER).compact if base_dir.nil? || file_pattern.nil? raise ArgumentError.new("file_spec requires both base_dir and file_pattern: #{ fs_string.inspect } in #{ input_file_specs.inspect }") end if base_dir !~ BASE_DIR_NAME_REGEX raise ArgumentError.new("base_dir is not valid: #{ base_dir.inspect }") end if file_pattern !~ FILE_PATTERN_NAME_REGEX raise ArgumentError.new("file_pattern is not valid: #{ file_pattern.inspect }") end m[fs_name] = [base_dir(base_dir), file_pattern(file_pattern)] m } end
[ "def compute_validation_file_specs(input_file_specs)\n input_file_specs.inject({}) { |m,(fs_name, fs_attrs)|\n a_base_dir, a_file_selector, a_file_extension = fs_attrs\n m[fs_name] = [\n compute_base_dir(a_base_dir),\n compute_file_selector(a_file_selector),\n compute_file_extension(a_file_extension)\n ]\n m\n }\n end", "def file_hash(file_path)\r\n\r\n @digest.reset\r\n @base_str = nil\r\n @digest.file(file_path).to_s\r\n end", "def file_hashes\n @file_hashes ||= file_field_sets.map do |file_field_set|\n instantiation_fields, file_fields = file_field_set.partition do |field|\n instantiation_header?(field.header)\n end\n\n file_hash = fields_to_hash(file_fields)\n file_hash['files'] = [fields_to_hash(instantiation_fields)]\n\n file_hash\n end\n end", "def file_hash(f)\n Digest::SHA1.hexdigest(File.read(f))\nend", "def calculate_fileset_hash(database)\n hash_files(database, collect_fileset_for_hash(database))\n end", "def process_files\n SignatureMatrix.calculate_min_hashes(@files)\n @locality = LocalityHasher.new(@files) \n end", "def files_digest(paths); end", "def iddupe_files(options = {})\r\n required_input_files :scan_index, :analysis\r\n required_output_files :iddupe_files, :sha256_cache\r\n\r\n # load up the analysis, so we know which file-sizes may have duplicates\r\n analysis = File.open(input_file(:analysis)){|f| JSON.load(f)}\r\n file_sizes = analysis['file_sizes']\r\n\r\n # create a list of file sizes that should be inspected more carefully\r\n collection_by_file_size = {} # { file_size => { sha256 => [path1, path2, ...]} }\r\n file_sizes.each do |size, num|\r\n size_i = size.to_i\r\n if size_i > 0 && num > 1\r\n collection_by_file_size[size_i] = {} # this hash will collect SHA256 checksums for all files of this size\r\n end\r\n end\r\n\r\n sha256_by_path = {} # { path => sha256 }\r\n\r\n\r\n # read the index file\r\n IndexFile::Reader.new(input_file(:scan_index)) do |index_file|\r\n # state objects, updated during parsing\r\n dirscan = {}\r\n dir = {}\r\n\r\n # iterate over all the entries\r\n while not index_file.eof? do\r\n object = index_file.read_object\r\n\r\n case object[:type].to_sym\r\n\r\n when :dirscan\r\n dirscan = object\r\n when :dir\r\n dir = object\r\n when :file\r\n file = object\r\n size = file[:size]\r\n collection = collection_by_file_size[size]\r\n if collection\r\n # puts \"dirscan[:scan_root] = #{dirscan[:scan_root]}\"\r\n # puts \"dir[:path] = #{dir[:path]}\"\r\n # puts \"file[:name] = #{file[:name]}\"\r\n full_path = File.join(dir[:path], file[:name])\r\n sha256 = FileHash.sha256(full_path)\r\n if sha256\r\n collection[sha256] ||= []\r\n collection[sha256] << full_path\r\n\r\n sha256_by_path[full_path] = sha256\r\n end\r\n end\r\n end\r\n end\r\n\r\n # remove sha256-arrays with only a single entry (i.e. only one file has a given sha256)\r\n collection_by_file_size.each do |file_size, collection|\r\n collection.keys.each do |sha256|\r\n if collection[sha256].size == 1\r\n collection.delete(sha256)\r\n end\r\n end\r\n end\r\n # remove empty collections (file-sizes without any duplicates)\r\n collection_by_file_size.keys.each do |file_size|\r\n if collection_by_file_size[file_size].empty?\r\n collection_by_file_size.delete(file_size)\r\n end\r\n end\r\n\r\n result = {\r\n :collection_by_file_size => collection_by_file_size,\r\n }\r\n\r\n # write the text file\r\n File.open(output_file(:iddupe_files), 'w') do |text_file|\r\n text_file.write JSON.pretty_generate(result) + \"\\n\"\r\n end\r\n\r\n if output_file(:sha256_cache, {default: nil})\r\n cache_data = {\r\n :sha256_by_path => sha256_by_path,\r\n }\r\n File.open(output_file(:sha256_cache), 'w') do |cache_file|\r\n cache_file.write JSON.pretty_generate(cache_data)\r\n end\r\n end\r\n \r\n return result\r\n end\r\n end", "def get_hash(file)\n Digest::MD5.digest file\n end", "def content_file_checksums\n @manifest_files.map { |f| identity_hash(f) }\n end", "def build_input_spec(app, scope)\n files_copies = copy_default_input_files(app, scope)\n\n input_spec = app.input_spec\n\n files_copies.each do |object, source|\n input_spec = input_spec.map do |spec|\n spec[:default] = object.uid if spec[:class] == \"file\" && spec[:default] == source.uid\n spec\n end\n end\n\n input_spec\n end", "def compute_hash( path )\n res = '0'\n autorelease_pool { res = NSData.sha1FromContentsOfFile(path) }\n res\n end", "def build_hash(file_list)\n\t\tresults = {}\n\t\tfile_list.each do |path|\n\t\t\tcontent = File.read(path)\n\t\t\tresults[path] = content\n\t\tend\n\t\treturn results\n\tend", "def checksum_for(*filenames)\n filenames.flatten.map do |filename|\n digest = Digest::SHA2.new\n File.open(filename, 'r') do |io|\n until io.eof\n data = io.readpartial(2**10)\n digest.update(data)\n end\n end\n digest.hexdigest\n end.join('-')\n end", "def compute_hashes(path, part_size)\n raise \"Cannot process empty file!\" if File.size(path)==0\n file = File.open(path, 'rb')\n linear_hash = Digest::SHA256.new\n \n parts = []\n while(data = file.read(1.megabyte))\n linear_hash << data\n \n sha256sum = Digest::SHA256.new\n sha256sum << data\n parts << sha256sum\n end\n \n current_part_size = 1.megabyte\n parts_for_transport = []\n next_parts = []\n\n while true\n parts_for_transport = parts if current_part_size == part_size\n break if parts.length == 1\n\n index = 0\n while(!(pair = parts.slice(index,2)).blank?)\n if pair.size == 1\n next_parts << pair[0] \n break\n end\n \n sha256sum = Digest::SHA256.new\n sha256sum << pair[0].digest\n sha256sum << pair[1].digest\n next_parts << sha256sum\n index += 2\n end\n \n parts = next_parts\n next_parts = []\n current_part_size = current_part_size * 2\n end\n {:linear_hash => linear_hash.to_s, :tree_hash => parts.first.to_s, :hashes_for_transport => parts_for_transport}\n end", "def file_name_hash\n Digest::MD5.hexdigest(file_name)\n end", "def file_hash(file_name)\n file = file_name.split('/').last.split('.amps').first\n fhash = Hash.new\n file.split(':').each{|x| eqpos = x.index('=') \n fhash[x.slice(0...eqpos)] = x.slice(eqpos+1..x.length-1)\n }\n fhash\nend", "def compare_hashes_handler(hash_, file_, hash_class, _bit_size)\n # noinspection RubyStringKeysInHashInspection,RubyResolve\n hash_class_reference = {1 => Digest::SHA1, 2 => Digest::SHA2, 5 => Digest::MD5}\n # Check if hash_ is a raw hash or a csv db\n if File.file? hash_\n # hash_ is a csv database with hashes to check\n # Handler for databse\n file_object = File.open hash_, 'r'\n # All the lines of the db\n lines = file_object.readlines\n # Close the file because we don't need it anymore\n file_object.close\n # Fist line of this file is the configuration line that is the function and its bit size (if is sha2)\n hash_class, _bit_size = lines[0].strip.split('-')\n # Has_class can be transformed to int corresponding to its number\n hash_class = {\"SHA1\" => 1, \"SHA2\" => 2, \"MD5\" => 5}[hash_class]\n # When a bit size was specified transform it to int\n if _bit_size.is_a? String\n _bit_size = _bit_size.to_i\n end\n # Parameters for the setup of the hash_function\n hash_class = hash_class_reference[hash_class]\n\n #puts hash_class, chunk_size\n lines = lines[1..]\n lines.each do |line|\n file_path, hash = line.strip.split(',')\n compare file_path, hash_class, _bit_size, hash\n end\n else\n # hash_ variable is a raw hash\n # Get the hash class from the string provided\n hash_class = hash_class_reference[hash_class]\n # Compare the raw hash (hash_) with the file provided\n compare file_,hash_class, _bit_size, hash_\n end\nend", "def compute_hash\n filesize = File.size(@filename)\n File.open(@filename, 'rb') do |f|\n first = f.read(CHUNK_SIZE)\n f.seek([0, filesize - CHUNK_SIZE].max, IO::SEEK_SET)\n second = f.read(CHUNK_SIZE)\n hash = [first, second].inject(filesize) do |hash, part|\n part.reverse! if BIG_ENDIAN\n part.unpack(\"Q*\").inject(hash) do |hash, n|\n hash + n & 0xffffffffffffffff\n end\n end\n \n \"%016x\" % hash\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the absolute path of primary_repo with a guaranteed trailing slash at the end
def primary_repo_base_dir File.expand_path( setting(:relative_path_to_primary_repo), base_dir(:rtfile_dir) ).sub(/\/?\z/, '') + '/' end
[ "def get_repo_abs_path( dirname )\n\t\t\tif dirname == nil then\n\t\t\t\t@repo\n\t\t\telse\n\t\t\t\tFile.join( @repo, dirname )\n\t\t\tend\n\t\tend", "def repo_path\n @config.get_value('GIT_REPO_ROOT')\n end", "def abspath\n \"#{repo_base_path}/#{self.git_repo_path}\"\n end", "def repository_path identifier\n \"#{REPOSITORY_BASE}/#{identifier}\"\nend", "def repository_root\n File.expand_path(@repo.path + \"/../\")\n end", "def repo_root\n File.dirname(@path)\n end", "def local_repo_path\n @resolver.getLocalRepoPath()\n end", "def repo_relative_path(include_repo_root=false)\n leading_path_segments = if include_repo_root\n # Remove repo root dir from leading_path_segments to keep it\n Pathname.new(repository.base_dir).parent.to_s\n else\n repository.base_dir\n end\n # Remove leading path segments plus any leading slashes\n filename.sub(leading_path_segments, '').sub(/\\A\\//, '')\n end", "def repo_name\n # the repo is the last part of the path\n return self.cmd_opt.gsub(\"'\",\"\").split(\"/\")[-1] if !self.cmd_opt.empty?\n end", "def relative_to_repo_dir(path)\n path[(@cookbook.repo_dir.length + 1)..-1]\n end", "def uri_path_repo_top\n Pathname.new(uri_path).join(search_assets_top_rel.dirname).dirname\n end", "def repo_name\n @repo_name = `git rev-parse --show-toplevel`.chomp.split(\"/\").last\n @repo_name.to_s\n \"#{@repo_name}\"\n end", "def gitolite_repository_name\n if (parent_path = get_full_parent_path).empty?\n project.identifier\n else\n File.join(parent_path, project.identifier)\n end\n end", "def repo_path\n context.repo_path\n end", "def repo_base_dir\n File.join(Repositext::PARENT_DIR, repo_base_dir_name)\n end", "def repository_root\n return unless available?\n root = Licensed::Shell.execute(\"git\", \"rev-parse\", \"--show-toplevel\", allow_failure: true)\n return nil if root.empty?\n root\n end", "def relative_path\n File.join(@repo, @bundle)\n end", "def repository_path\n @repository_path\n end", "def child_repo_path(child_name)\n File.join(repo_path, child_name)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a key's value from container. Raises if an unknown key is requested.
def get_config_val(container, key, raise_on_unknown_key = true) key = key.to_sym if raise_on_unknown_key && !container.keys.include?(key) raise RtfileError.new("You requested an unknown key: #{ key.inspect }") end container[key] end
[ "def get(key)\n position = find(key)\n if position != nil\n @values[position]\n else\n nil\n end\n end", "def fetch(key)\n return @keys[key] ? @keys[key] : \"value not found\"\n end", "def get_value(collection, key)\n @data[collection][key]\n end", "def get(key)\n get_all(key).first\n end", "def fetch_value( oid, key )\n\t\toid = normalize_oid( oid )\n\t\tkey = normalize_key( key )\n\t\tdata = @storage[ oid ] or return nil\n\n\t\treturn data[ key ]\n\tend", "def get key\n content = nil\n begin\n content = @fast.get(key) \n rescue Exception\n end\n\n return content unless content.nil?\n\n begin\n content = @slow.get(key) \n rescue Exception\n end\n return content\n end", "def get( key )\n key = UniMap.str_to_key( key ) unless key.is_a?( Key )\n key && get_k( key )\n end", "def find(key)\n values[key]\n end", "def get(key_name)\n val = get_or_default(key_name, \"\")\n end", "def [](key)\n return nil if @collection.nil?\n return_item_value key\n end", "def [](key)\n retrieve(key)\n end", "def get_item(key)\n @items.find { |item| item.key == key }\n end", "def get(key)\n return nil unless @items.key?(key)\n @items[key].call\n end", "def get(k)\r\n if @hashtable.contains?(k)\r\n return @hashtable.get(k).value # return value v\r\n else # raise an error\r\n raise \"Error, key not found in dictionary\"\r\n end\r\n end", "def catalog_value(key)\n return catalog[key]\n end", "def get_tag_value(key)\n get_tag(key).try(:tag_value).try(:value)\n end", "def lookup_value(id, key)\n lookup(id).try(:[], key)\n end", "def get(key)\n index = @entries_index[key.to_i]\n if index\n case index\n when Array\n return @entries.values_at(*index)\n else\n return @entries[index]\n end\n end\n nil\n end", "def get_key(key, default: nil, error: false)\n if(has_key?(key))\n return self[key]\n end\n \n raise ArgumentError.new(\"Value #{key} not found.\") unless !error\n return default\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
title:legend: xAxis: yAxis: tooltip: credits: :plotOptions
def defaults_options self.title({ :text=>"example test title from highcharts gem"}) self.legend({ :layout=>"vertical", :style=>{} }) self.xAxis({}) self.yAxis({ :title=> {:text=> nil}, :labels=>{} }) self.tooltip({ :enabled=>true }) self.credits({ :enabled => false}) self.plotOptions({ :areaspline => { } }) self.chart({ :defaultSeriesType=>"areaspline" , :renderTo => nil}) self.subtitle({}) end
[ "def legend; end", "def show_legend; end", "def legend_position; end", "def defaults_options\n self.title({:text => nil})\n self.legend({:layout => \"vertical\", :style => {}})\n self.xAxis({})\n self.yAxis({:title => {:text => nil}, :labels => {}})\n self.tooltip({:enabled => true})\n self.credits({:enabled => false})\n self.plotOptions({:areaspline => {}})\n self.chart({:defaultSeriesType => \"line\", :renderTo => nil})\n self.subtitle({})\n end", "def configurePlot\n end", "def plot_scatter; end", "def plot_against e1, e2\n Flot.new('experiment_roc_plot') do |f|\n f.points\n f.grid :hoverable => true\n f.legend :position => \"se\"\n f.yaxis 1\n f.series \"#{e1.title} against #{e2.title}\", e1.aucs_against(e2), :points => {:show => true, :radius => 1.5}\n end\nend", "def add_title(input_args=Hash.new)\n @content[:options] ||= Hash.new\n @content[:options][:scales] ||= Hash.new\n if @args[:title]\n @content[:options][:title] = {\n display: true,\n text: @args[:title]\n }\n end\n\n # adjust where x-axis start or end\n x_scale_ticks = { } # Note this doesn't work for Time, which needs to specifies its own Time Min and Max\n y_scale_ticks = { }\n\n y_axes_left = { position: 'left', id: 'y-axis-left', ticks: y_scale_ticks}\n y_axes_right = {position: 'right', id: 'y-axis-right', ticks: y_scale_ticks}\n x_axes = { ticks: x_scale_ticks }\n\n \n\n # y_label(left) is always the first color, and y_label_right is always the second color\n if @args[:y_label]\n y_axes_left[:scaleLabel] = { display: true, labelString: @args[:y_label], fontColor: @colors[0] }\n end\n if @args[:y_right_label] # Jason 090216 right y axis label doesn't work\n y_axes_right[:scaleLabel] = { display: true, labelString: @args[:y_right_label] , fontColor: @colors[1] }\n\n end\n\n if @args[:stacked] \n x_axes[:stacked] = true\n y_axes_left[:stacked] = true \n end\n @content[:options][:scales][:yAxes] = [ y_axes_left]\n if @args[:y_right_label] # Jason 090216 right y axis label doesn't work\n @content[:options][:scales][:yAxes] << y_axes_right\n end\n @content[:options][:maintainAspectRatio] = @args[:aspect_ratio]\n @content[:options][:showLines] = @args[:showLines] if @args.has_key? :showLines\n\n # Chart Zoom plugin options\n @content[:options][:pan] = { enabled: true, mode: 'xy' }\n @content[:options][:zoom] = { enabled: true, mode: 'xy'}\n\n if self.class == ChartMaker::Scatter\n if @args[:time] # x axis is time (same as localtime, time since 1970) \n x_axes[:type] = 'time'\n else # x axis is number\n x_axes[:type] = 'linear'\n end\n x_axes[:position] = 'bottom'\n end\n \n if @args[:x_label]\n x_axes[:scaleLabel] = { display: true, labelString: @args[:x_label] }\n end\n if @args[:time]\n if ! ['hour','day','week','month','year'].include? @args[:time] # check Chart.js Time Scale for all the different Time Units\n raise \"unsupported time format #{@args[:time]}\"\n end\n x_axes[:time] = {}\n x_axes[:time][:unit] = @args[:time] \n x_axes[:time][:tooltipFormat] = \"MMMM Do YYYY, h a\" # need this or time will be display in integer in tooltip mode (when you hover over data point), note this will return invalid if tooltip doesn't contain time\n if input_args[:last_month]\n #puts \"show just last month\"\n a_month_ago = Time.now.to_i - (86400 * 30) # 30 days in terms of seconds\n x_axes[:time][:min] = to_js_time(a_month_ago)\n # also if last_month, then you know a good time unit is week\n x_axes[:time][:unit] = 'week'\n end\n end\n @content[:options][:scales][:xAxes] = [ x_axes]\n=begin\n jchen I have my own tooltips callback function, check def script_content()\n so below is not needed\n @content[:options][:tooltips] = Hash.new\n @content[:options][:tooltips][:callbacks] = Hash.new\n @content[:options][:tooltips][:callbacks][:label] = \"function(tooltipItem,data) { return \\\"jason\\\"; }\"\n=end\n\n end", "def legend\n title\n end", "def xaxis\n end", "def setup_series\r\n keys = @options.keys.sort { |a,b| a.to_s <=> b.to_s }\r\n @xml.chart_data do \r\n # Setup axis categories\r\n unless @options[:axis_category_text].nil?\r\n @options[:axis_category_text].insert( 0, nil ) if named_series? keys\r\n gen_data_points( :axis_category_text )\r\n end\r\n keys.each do |k| \r\n gen_data_points( k ) unless k.to_s.index( 'series_' ).nil?\r\n end\r\n end \r\n @xml.chart_value_text do\r\n size = has_labels keys\r\n if ( size > 0 )\r\n labels = []\r\n (1..(size-1)).each { |i| labels << '' }\r\n @options[:labels] = labels\r\n gen_labels( :labels )\r\n end\r\n keys.each do |k|\r\n unless k.to_s.index( \"labels_\" ).nil?\r\n gen_labels( k ) \r\n end\r\n end\r\n end \r\n end", "def xaxis\n end", "def plot_line; end", "def set_legend(params)\n @legend_position = params[:position] || 'right'\n @legend_delete_series = params[:delete_series]\n end", "def beanplot\n end", "def initialize(type, title, subtitle, chart, credits, x_opts, y_opts, legend_opts, series)\n @type = type\n @title = title\n @subtitle = subtitle\n @chart = chart\n @credits = credits\n @x_opts = XAxis.new(x_opts[:title], x_opts[:categories], x_opts[:labels], x_opts[:type], x_opts[:min], x_opts[:max])\n @y_opts = YAxis.new(y_opts[:title], y_opts[:categories], y_opts[:labels], y_opts[:type], y_opts[:min], y_opts[:max])\n @legend_opts = Legend.new(legend_opts[:layout], legend_opts[:align], legend_opts[:vertical_align], legend_opts[:x], legend_opts[:y], legend_opts[:floating])\n\n @series = []\n series.each_with_index { |value, index|\n @series[index] = Series.new(value[:name], value[:data_array])\n }\n\n puts \"begin structure\"\n puts @type\n puts @title\n puts @subtitle\n puts @chart\n puts @credits\n puts @x_opts\n puts @y_opts\n puts @legend_opts\n puts @series\n puts \"end structure\"\n\n # TODO: may be used later\n # @plot_opts = PlotOptions.new()\n # @response_opts = Responsive.new()\n # @tool_opts = Tooltip.new()\n end", "def yaxis\n end", "def plot(title, legend_titles, data)\n graph = Scruffy::Graph.new\n graph.title = title\n graph.renderer = Scruffy::Renderers::Standard.new\n data.each_index do |idx|\n graph.add(:line, legend_titles[idx], data[idx],\n {'stroke-width'=> 7, :stroke => 'black'})\n end\n graph.render :to => \"#{title}.svg\", :width=>500, :height=>400\nend", "def scatterStyle; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method will generate the options as a string suitable for straight use. This is required because of the addition of the datetime capability put in. The dates need to be formatted in a JS specific way.
def options_string options_collection = [] options.keys.each do |key| k = key.to_s.camelize.gsub!(/\b\w/) { $&.downcase } options_collection << "\"#{k}\": #{options[key].to_json}" end # This check is put in to catch for those graphs that are time series charts. In that event the # data needs to be reformated rather than just a blind JSON conversion if data.first[:data].first.class == Array and (data.first[:data].first.first.instance_of? DateTime or data.first[:data].first.first.instance_of? Date) series_string = "\"series\": [" data.each do |single_series| series_string << "{\"name\":\"#{single_series[:name]}\", \"data\":[" single_series[:data].each do |single_data| series_string << "[#{single_data[0].strftime('%s').to_i * 1000},#{single_data[1]}]" series_string << "," unless single_data == single_series[:data].last end series_string << "]}" series_string << "," unless single_series == data.last end series_string << "]" options_collection << series_string else # If this isn't a time series chart then just convert the data to JSON directly options_collection << "series: #{data.to_json}" end return "{#{options_collection.join(',')}}" end
[ "def to_s\n @options.join(' ')\n end", "def format_options\n return \"\" if @parameters.options.empty?\n\n longest_option = @parameters.options.map(&:long)\n .compact.max_by(&:length).length\n any_short = @parameters.options.map(&:short).compact.any?\n ordered_options = @order.(@parameters.options)\n\n ordered_options.reduce([]) do |acc, option|\n next acc if option.hidden?\n acc << format_option(option, longest_option, any_short)\n end.join(NEWLINE)\n end", "def options_as_string\r\n buff = \"\"\r\n options.each_pair do |k,v|\r\n buff << (buff.size == 0 ? \":#{k} => '#{v}'\" : \",:#{k} => '#{v}'\") unless v.nil?\r\n end\r\n buff\r\n end", "def to_s\n @options.join \" \"\n end", "def date_format_select_options(selected_value)\n unless @date_format_select_options\n @date_format_select_options = []\n AppConfig['date_formats'].each_with_index do |date_format, index|\n @date_format_select_options << \"<option value='#{index}'>#{date_format}</option>\"\n end\n @date_format_select_options = @date_format_select_options.join(\"\") \n end\n set_selected_option(@date_format_select_options, selected_value)\n end", "def format_date options = {}\n dates = options[:start_date].strftime(\"%D\") if options[:start_date]\n dates << \" -- \" + options[:end_date].strftime(\"%D\") if options[:end_date]\n dates = \"N/A\" if !dates\n return dates\n end", "def render_options\n values = \"\"\n if( !@options.nil? )\n @options.each do |k, v|\n values << \" data-#{k}='#{v}'\"\n end\n end\n return values\n end", "def options_str(opts)\n options = []\n \n opts.each do |(key, value)|\n unless key.kind_of?(String)\n key = key.to_s.gsub('_', '-')\n end\n \n unless key[0] == ?-\n prefix = key.length == 1 ? '-' : '--'\n key = \"#{prefix}#{key}\"\n end\n \n case value\n when true\n options << key\n when false, nil\n next\n else\n options << \"#{key} #{quote(value.to_s)}\"\n end\n end\n \n options.sort\n end", "def values_to_s( with_price = true )\n values_string = \"\"\n return values_string if number_of_options == 1 and option_value_1 == \"Default\"\n \n option_values.each_with_index do |value, index| \n unless index == number_of_options - 1\n values_string << \"#{ value } / \" unless value.blank?\n else\n values_string << \"#{ value }\" unless value.blank?\n end\n end\n \n values_string << \" -- #{ price.format }\" if with_price\n values_string\n end", "def options_as_string\n buff = []\n opts = options\n opts.keys.sort{ |a,b| a.to_s <=> b.to_s }.each do |k|\n value = opts[k]\n buff << sprintf( \":%s => '%s'\", k, value.to_s ) if !value.nil? and !value.is_a? YAML::Omap\n end \n buff.join( \",\" )\n end", "def compile_options\n str = String.new\n @options.each { |o| str = str + ' ' + o.compile }\n return str\n end", "def build_option_string(opt)\n before_for(opt) << padding_for(opt) << padding << after_for(opt).rstrip << \"\\n\"\n end", "def ui_options\n {\n rangeStartTitle: start_date_text, rangeEndTitle: end_date_text, nextLinkText: next_text, prevLinkText: previous_text, doneButtonText: done_text,\n earliestDate: earliest_date, latestDate: latest_date, dateFormat: date_format\n }\n end", "def options_string(options)\n return nil if Hash(options).size.zero?\n\n options.map do |k, v|\n [k.to_s, v.to_s].join\n end.join.gsub(/[^A-Za-z0-9\\-_]/, '')\n end", "def to_s(options={})\n\t\tnames = get_names_override(options)\n\t\t#puts \"Debug: @day_names=#{@day_names.inspect}, names=#{names}\"\n\t\tmin_span = DayRange.get_option(:min_span, options, @min_span)\n\t\tweek_start = DayRange.get_option(:week_start, options, @week_start)\n\t\n\t\tresult = \"\"\n\t\tadjusted_ranges(min_span,week_start).map {|range| \n\t\t\trange.first == range.last ? \n \"#{names[ws_unadj(range.first, week_start)]}\" : \n\t\t\t \"#{names[ws_unadj(range.first, week_start)]}-#{names[ws_unadj(range.last,week_start)]}\"\n\t\t}.join(\", \")\n\tend", "def options_str(opts)\n options = []\n \n opts.each do |(key, value)|\n unless key.kind_of?(String)\n key = key.to_s.gsub('_', '-')\n end\n \n unless key[0] == ?-\n prefix = key.length == 1 ? '-' : '--'\n key = \"#{prefix}#{key}\"\n end\n \n case value\n when true\n options << key\n when false, nil\n next\n else\n options << \"#{key} #{quote(value.to_s)}\"\n end\n end\n \n options.sort\nend", "def option_values_to_s\n option_values_string = \"\"\n \n option_values.by_option_type_id.each_with_index do |option_value, index|\n option_values_string << option_value.option_type.name\n option_values_string << \": \" + option_value.name\n option_values_string << \" / \" unless ( index + 1 ) == option_values.size\n end\n \n option_values_string\n end", "def format_options(options)\n data = []\n options.each do |name, option_spec|\n data << format_option(option_spec)\n end\n \"Options:\\n\" + render_table(data, \": \")\n end", "def build_era_name_options(selected, options = {})\n start = options.delete(:start) || 0\n stop = options.delete(:end) || 59\n step = options.delete(:step) || 1\n leading_zeros = options.delete(:leading_zeros).nil? ? true : false\n\n select_options = []\n start.step(stop, step) do |i|\n value = leading_zeros ? sprintf(\"%02d\", i) : i\n tag_options = { :value => value }\n tag_options[:selected] = \"selected\" if selected == i\n select_options << content_tag(:option, year_with_era_name(value), tag_options)\n end\n select_options.join(\"\\n\") + \"\\n\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a test which tests authorization code. It assumes a method called access_denied? on the test case. The access_denied? method should return true when access is denied (ie. a 403 status code) and false in other cases. Example: should.allow.get :index
def allow Test::Spec::Rails::Macros::Authorization::TestGenerator.new(test_case, :access_denied?, false, 'Expected access to be allowed' ) end
[ "def test_index_authorized\n authorize @valid_user\n get :index\n assert_response :success\n assert_template \"index\"\n end", "def generate_authorization_testcase(testplan)\n fail \"nil\" if testplan.nil?\n id = testplan[\"id\"]\n\n tc = \"Feature: CWE-285: Improper Authorization\\n\"\n tc += \" The software does not perform or incorrectly performs an \\n\"\n tc += \" authorization check when an actor attempts to access a \\n\"\n tc += \" resource or perform an action.\\n\"\n tc += \"\\n\"\n\n # TODO: CanCan\n if testplan[\"testcase_type\"] == 'automatic'\n strong_privilege_user = testplan['strong_privilege_user']\n weak_privilege_user = testplan['weak_privilege_user']\n strong_privilege_path = testplan[\"strong_privilege_path\"]\n success_text = testplan[\"success_text\"]\n error_text = testplan[\"error_text\"]\n\n tc += \" Scenario: #{id}[0]\\n\"\n tc += \" authorized access\\n\\n\"\n tc += \" Given a logged in #{strong_privilege_user}\\n\"\n tc += \" When I visit the #{strong_privilege_path}\\n\"\n tc += \" Then I should see \\\"#{success_text}\\\"\\n\"\n tc += \"\\n\"\n tc += \" Scenario: #{id}[1]\\n\"\n tc += \" non-authorized access\\n\\n\"\n tc += \" Given a logged in #{weak_privilege_user}\\n\"\n tc += \" When I visit the #{strong_privilege_path}\\n\"\n tc += \" Then I should see \\\"#{error_text}\\\"\\n\"\n tc += \"\\n\"\n else\n $log.error \"TODO:\"\n end\n return tc\n end", "def it_should_deny(user_sym, spec_desc = \"\")\n it \"should deny #{user_sym} \" + spec_desc, auth: true do\n maybe_grant_always_sign_in(user_sym)\n do_request\n is_expected.to render_template(\"403\")\n end\nend", "def test_default_privilege_deny\n assert_equal false, @acl.allowed?(nil, nil, 'some_privilege')\n end", "def test_negative_scenario\n result = perform_login\n testFinalActionEqual(result.postAuthResult, \"Allow\")\n end", "def authorization_denied\n render :template => \"errors/authorization_denied\", :status => :forbidden\n end", "def test_privilege_assert\n @acl.allow!(nil, nil, 'some_privilege', MockAssertion.new(true))\n assert_equal true, @acl.allowed?(nil, nil, 'some_privilege')\n\n @acl.allow!(nil, nil, 'some_privilege', MockAssertion.new(false))\n assert_equal false, @acl.allowed?(nil, nil, 'some_privilege')\n end", "def test_negative_scenario\n use_location :country => \"United States\", :state => \"New York\"\n result = perform_login\n testFinalActionEqual(result.postAuthResult, \"Allow\")\n end", "def expect_forbidden_status\n is_expected.to respond_with 403\n end", "def test_access_to_protected_page_passing_wrong_credentials\n # Requesting the protectedPage of the application.\n request = @requester.get( URI.escape('/protectedPage'),\n { 'HTTP_AUTHORIZATION'=> encode_credentials('myWrongUsername', 'myWrongPassword') } )\n\n # The response should be OK (200)\n assert_equal 401, request.status\n # Content type should be HTML\n assert_equal 'text/html', request.content_type\n # Should contain a header with 'WWW-Authenticate'.\n assert request.headers['WWW-Authenticate'] != nil\n # Checking if the response contains the expected text.\n expected_body = 'Access Denied'\n assert_contains expected_body, request.body\n end", "def test_access_to_protected_page_passing_no_credentials\n # Requesting the protectedPage of the application.\n request = @requester.get URI.escape('/protectedPage')\n # The response should be Unauthorized (401).\n assert_equal 401, request.status\n # Content type should be HTML\n assert_equal 'text/html', request.content_type\n # Should contain a header with 'WWW-Authenticate'.\n assert request.headers['WWW-Authenticate'] != nil\n # Checking if the response contains the expected text.\n expected_body = 'Access Denied'\n assert_contains expected_body, request.body\n end", "def hyves_access_denied\n access_denied\n end", "def test_negative_scenario\n use_location :country => \"United States\"\n result = perform_login\n testFinalActionEqual(result.preAuthResult, \"Allow\")\n end", "def authorize_fail\n if request.format == :json\n render :text => \"Unauthorized action.\"\n else\n render :file => \"static/401\", :formats => [:html], :status => :unauthorized\n end\n return false\n end", "def test_default_rule_set_privilege\n @acl.allow!\n assert_equal true, @acl.allowed?(nil, nil, 'some_privilege')\n @acl.deny!\n assert_equal false, @acl.allowed?(nil, nil, 'some_privilege')\n end", "def do_authorization_fail(ticket, reason)\n # Call Authlete's /auth/authorization/fail API.\n response = call_authorization_fail_api(ticket, reason)\n\n # The content of the response to the client.\n content = response[\"responseContent\"]\n\n # \"action\" denotes the next action.\n case response[\"action\"]\n when \"INTERNAL_SERVER_ERROR\"\n # 500 Internal Server Error\n # The API request from this implementation was wrong\n # or an error occurred in Authlete.\n return WebResponse.new(500, content).json.to_response\n\n when \"BAD_REQUEST\"\n # 400 Bad Request\n # The ticket is no longer valid (deleted or expired)\n # and the reason of the invalidity was probably due\n # to the end-user's too-delayed response to the\n # authorization UI.\n return WebResponse.new(400, content).json.to_response\n\n when \"LOCATION\"\n # 302 Found\n # The authorization request was invalid and the error\n # is reported to the redirect URI using Location header.\n return WebResponse.new(302).location(content).to_response\n\n when \"FORM\"\n # 200 OK\n # The authorization request was invalid and the error\n # is reported to the redirect URI using HTML Form Post.\n return WebResponse.new(200, content).html.to_response\n\n else\n # This never happens.\n return WebResponse.new(500, \"Unknown action\").plain.to_response\n end\nend", "def require_login\n Test::Spec::Rails::Macros::Authorization::TestGenerator.new(test_case,\n :login_required?, true,\n 'Expected login to be required'\n )\n end", "def test_role_privilege_deny\n role_guest = Rend::Acl::Role.new('guest')\n @acl.add_role!(role_guest)\n @acl.allow!(role_guest)\n @acl.deny!(role_guest, nil, 'some_privilege')\n assert_equal false, @acl.allowed?(role_guest, nil, 'some_privilege')\n end", "def test_index_unauthorized\n get :index\n assert_response :redirect\n assert_redirected_to :action => \"login\"\n assert_equal \"Please log in first\", flash[:notice]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a test which tests authorization code. It assumes a method called access_denied? on the test case. The login_required? method should return true when the visitor was asked for credentials (ie. a 401 status code or a redirect to a login page) and false in other cases. Example: should.require_login.get :index
def require_login Test::Spec::Rails::Macros::Authorization::TestGenerator.new(test_case, :login_required?, true, 'Expected login to be required' ) end
[ "def allow\n Test::Spec::Rails::Macros::Authorization::TestGenerator.new(test_case,\n :access_denied?, false,\n 'Expected access to be allowed'\n )\n end", "def test_index_authorized\n authorize @valid_user\n get :index\n assert_response :success\n assert_template \"index\"\n end", "def test_negative_scenario\n result = perform_login\n testFinalActionEqual(result.postAuthResult, \"Allow\")\n end", "def test_index_unauthorized\n get :index\n assert_response :redirect\n assert_redirected_to :action => \"login\"\n assert_equal \"Please log in first\", flash[:notice]\n end", "def generate_authorization_testcase(testplan)\n fail \"nil\" if testplan.nil?\n id = testplan[\"id\"]\n\n tc = \"Feature: CWE-285: Improper Authorization\\n\"\n tc += \" The software does not perform or incorrectly performs an \\n\"\n tc += \" authorization check when an actor attempts to access a \\n\"\n tc += \" resource or perform an action.\\n\"\n tc += \"\\n\"\n\n # TODO: CanCan\n if testplan[\"testcase_type\"] == 'automatic'\n strong_privilege_user = testplan['strong_privilege_user']\n weak_privilege_user = testplan['weak_privilege_user']\n strong_privilege_path = testplan[\"strong_privilege_path\"]\n success_text = testplan[\"success_text\"]\n error_text = testplan[\"error_text\"]\n\n tc += \" Scenario: #{id}[0]\\n\"\n tc += \" authorized access\\n\\n\"\n tc += \" Given a logged in #{strong_privilege_user}\\n\"\n tc += \" When I visit the #{strong_privilege_path}\\n\"\n tc += \" Then I should see \\\"#{success_text}\\\"\\n\"\n tc += \"\\n\"\n tc += \" Scenario: #{id}[1]\\n\"\n tc += \" non-authorized access\\n\\n\"\n tc += \" Given a logged in #{weak_privilege_user}\\n\"\n tc += \" When I visit the #{strong_privilege_path}\\n\"\n tc += \" Then I should see \\\"#{error_text}\\\"\\n\"\n tc += \"\\n\"\n else\n $log.error \"TODO:\"\n end\n return tc\n end", "def it_should_deny(user_sym, spec_desc = \"\")\n it \"should deny #{user_sym} \" + spec_desc, auth: true do\n maybe_grant_always_sign_in(user_sym)\n do_request\n is_expected.to render_template(\"403\")\n end\nend", "def test_site_requirement(required, actions)\n login_as(:admin)\n activate_site(nil)\n condition = required ? \n lambda { response.should redirect_to(new_admin_site_path) } :\n lambda { response.should_not redirect_to(new_admin_site_path) }\n test_action_requirements(actions, condition)\nend", "def test_navigation_logged_in\n user = users(:valid_user)\n authorize user\n get :index\n assert_tag \"a\", :content => /Logout/, :attributes => { :href => '/user/logout' }\n \n assert_no_tag \"a\", :content => /Register/, :attributes => { :href => \"/user/register\" }\n assert_no_tag \"a\", :content => /Login/, :attributes => { :href => \"/user/login\" }\n end", "def test_navigation_logged_in\n authorize @valid_user\n get :index\n assert_tag \"a\", :content => /Logout/,\n :attributes => { :href => \"/user/logout\"}\n assert_no_tag \"a\", :content => /Register/\n assert_no_tag \"a\", :content => /Login/\n end", "def test_negative_scenario\n use_location :country => \"United States\", :state => \"New York\"\n result = perform_login\n testFinalActionEqual(result.postAuthResult, \"Allow\")\n end", "def login_required\n login_by_token unless logged_in?\n login_by_basic_auth unless logged_in?\n access_denied unless logged_in? && authorized?\n end", "def test_negative_scenario\n use_location :country => \"United States\"\n result = perform_login\n testFinalActionEqual(result.preAuthResult, \"Allow\")\n end", "def test_access_to_protected_page_passing_no_credentials\n # Requesting the protectedPage of the application.\n request = @requester.get URI.escape('/protectedPage')\n # The response should be Unauthorized (401).\n assert_equal 401, request.status\n # Content type should be HTML\n assert_equal 'text/html', request.content_type\n # Should contain a header with 'WWW-Authenticate'.\n assert request.headers['WWW-Authenticate'] != nil\n # Checking if the response contains the expected text.\n expected_body = 'Access Denied'\n assert_contains expected_body, request.body\n end", "def test_access_lead \n \n #client \n login_as('lead') \n \n msg = \"Lead don't have privileges to access lead/\"\n \n #new\n get :new\n assert_response :success\n assert_template 'error' , msg + \"new\" \n \n #show\n get :show\n assert_response :success\n assert_template 'error' , msg + \"show\" \n \n #create\n get :create\n assert_response :success\n assert_template 'error' , msg + \"create\" \n \n #edit\n get :edit\n assert_response :success\n assert_template 'error' , msg + \"edit\" \n \n #update\n get :update\n assert_response :success\n assert_template 'error' , msg + \"update\" \n \n #destroy\n get :destroy\n assert_response :success\n assert_template 'error' , msg + \"destroy\" \n \n \n \n \n logout() \n end", "def test_login_controls\n get :login_controls\n assert_response :success\n assert_nil session[:user]\n end", "def test_access_to_protected_page_passing_wrong_credentials\n # Requesting the protectedPage of the application.\n request = @requester.get( URI.escape('/protectedPage'),\n { 'HTTP_AUTHORIZATION'=> encode_credentials('myWrongUsername', 'myWrongPassword') } )\n\n # The response should be OK (200)\n assert_equal 401, request.status\n # Content type should be HTML\n assert_equal 'text/html', request.content_type\n # Should contain a header with 'WWW-Authenticate'.\n assert request.headers['WWW-Authenticate'] != nil\n # Checking if the response contains the expected text.\n expected_body = 'Access Denied'\n assert_contains expected_body, request.body\n end", "def check_access\n return {code: access_status, message: 'Not authenticated'} unless access_status == 200 || access_status == '200'\n end", "def test_authentication\n load_token\n return false if !@token || @token.empty?\n res = get '/'\n !res.key?('error')\n end", "def authorize_fail\n if request.format == :json\n render :text => \"Unauthorized action.\"\n else\n render :file => \"static/401\", :formats => [:html], :status => :unauthorized\n end\n return false\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }