repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
arscan/mintkit
lib/mintkit/client.rb
Mintkit.Client.transactions
def transactions raw_transactions = @agent.get("https://wwws.mint.com/transactionDownload.event?").body transos = [] raw_transactions.split("\n").each_with_index do |line,index| if index > 1 line_array = line.split(",") transaction = { :date => Date.strptime(remove_quotes(line_array[0]), '%m/%d/%Y'), :description=>remove_quotes(line_array[1]), :original_description=>remove_quotes(line_array[2]), :amount=>remove_quotes(line_array[3]).to_f, :type=>remove_quotes(line_array[4]), :category=>remove_quotes(line_array[5]), :account=>remove_quotes(line_array[6]), :labels=>remove_quotes(line_array[7]), :notes=>remove_quotes(line_array[8]) } transos << transaction if block_given? yield transaction end end end transos end
ruby
def transactions raw_transactions = @agent.get("https://wwws.mint.com/transactionDownload.event?").body transos = [] raw_transactions.split("\n").each_with_index do |line,index| if index > 1 line_array = line.split(",") transaction = { :date => Date.strptime(remove_quotes(line_array[0]), '%m/%d/%Y'), :description=>remove_quotes(line_array[1]), :original_description=>remove_quotes(line_array[2]), :amount=>remove_quotes(line_array[3]).to_f, :type=>remove_quotes(line_array[4]), :category=>remove_quotes(line_array[5]), :account=>remove_quotes(line_array[6]), :labels=>remove_quotes(line_array[7]), :notes=>remove_quotes(line_array[8]) } transos << transaction if block_given? yield transaction end end end transos end
[ "def", "transactions", "raw_transactions", "=", "@agent", ".", "get", "(", "\"https://wwws.mint.com/transactionDownload.event?\"", ")", ".", "body", "transos", "=", "[", "]", "raw_transactions", ".", "split", "(", "\"\\n\"", ")", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "if", "index", ">", "1", "line_array", "=", "line", ".", "split", "(", "\",\"", ")", "transaction", "=", "{", ":date", "=>", "Date", ".", "strptime", "(", "remove_quotes", "(", "line_array", "[", "0", "]", ")", ",", "'%m/%d/%Y'", ")", ",", ":description", "=>", "remove_quotes", "(", "line_array", "[", "1", "]", ")", ",", ":original_description", "=>", "remove_quotes", "(", "line_array", "[", "2", "]", ")", ",", ":amount", "=>", "remove_quotes", "(", "line_array", "[", "3", "]", ")", ".", "to_f", ",", ":type", "=>", "remove_quotes", "(", "line_array", "[", "4", "]", ")", ",", ":category", "=>", "remove_quotes", "(", "line_array", "[", "5", "]", ")", ",", ":account", "=>", "remove_quotes", "(", "line_array", "[", "6", "]", ")", ",", ":labels", "=>", "remove_quotes", "(", "line_array", "[", "7", "]", ")", ",", ":notes", "=>", "remove_quotes", "(", "line_array", "[", "8", "]", ")", "}", "transos", "<<", "transaction", "if", "block_given?", "yield", "transaction", "end", "end", "end", "transos", "end" ]
login to my account get all the transactions
[ "login", "to", "my", "account", "get", "all", "the", "transactions" ]
b1f7a87b3f10f0e8d7144d6f3e7c778cfbd2b265
https://github.com/arscan/mintkit/blob/b1f7a87b3f10f0e8d7144d6f3e7c778cfbd2b265/lib/mintkit/client.rb#L19-L50
train
flyingmachine/whoops_logger
lib/whoops_logger/configuration.rb
WhoopsLogger.Configuration.set_with_string
def set_with_string(config) if File.exists?(config) set_with_yaml(File.read(config)) else set_with_yaml(config) end end
ruby
def set_with_string(config) if File.exists?(config) set_with_yaml(File.read(config)) else set_with_yaml(config) end end
[ "def", "set_with_string", "(", "config", ")", "if", "File", ".", "exists?", "(", "config", ")", "set_with_yaml", "(", "File", ".", "read", "(", "config", ")", ")", "else", "set_with_yaml", "(", "config", ")", "end", "end" ]
String should be either a filename or YAML
[ "String", "should", "be", "either", "a", "filename", "or", "YAML" ]
e1db5362b67c58f60018c9e0d653094fbe286014
https://github.com/flyingmachine/whoops_logger/blob/e1db5362b67c58f60018c9e0d653094fbe286014/lib/whoops_logger/configuration.rb#L106-L112
train
kete/kete_trackable_items
lib/kete_trackable_items/list_management_controllers.rb
KeteTrackableItems.ListManagementControllers.remove_from_list
def remove_from_list begin matching_results_ids = session[:matching_results_ids] matching_results_ids.delete(params[:remove_id].to_i) session[:matching_results_ids] = matching_results_ids render :nothing => true rescue render :nothing => true, :status => 500 end end
ruby
def remove_from_list begin matching_results_ids = session[:matching_results_ids] matching_results_ids.delete(params[:remove_id].to_i) session[:matching_results_ids] = matching_results_ids render :nothing => true rescue render :nothing => true, :status => 500 end end
[ "def", "remove_from_list", "begin", "matching_results_ids", "=", "session", "[", ":matching_results_ids", "]", "matching_results_ids", ".", "delete", "(", "params", "[", ":remove_id", "]", ".", "to_i", ")", "session", "[", ":matching_results_ids", "]", "=", "matching_results_ids", "render", ":nothing", "=>", "true", "rescue", "render", ":nothing", "=>", "true", ",", ":status", "=>", "500", "end", "end" ]
assumes matching_results_ids in the session drops a given remove_id from the session variable
[ "assumes", "matching_results_ids", "in", "the", "session", "drops", "a", "given", "remove_id", "from", "the", "session", "variable" ]
5998ecd83967108c1ed1378161e43feb80d6b886
https://github.com/kete/kete_trackable_items/blob/5998ecd83967108c1ed1378161e43feb80d6b886/lib/kete_trackable_items/list_management_controllers.rb#L7-L16
train
kete/kete_trackable_items
lib/kete_trackable_items/list_management_controllers.rb
KeteTrackableItems.ListManagementControllers.restore_to_list
def restore_to_list begin matching_results_ids = session[:matching_results_ids] session[:matching_results_ids] = matching_results_ids << params[:restore_id].to_i render :nothing => true rescue render :nothing => true, :status => 500 end end
ruby
def restore_to_list begin matching_results_ids = session[:matching_results_ids] session[:matching_results_ids] = matching_results_ids << params[:restore_id].to_i render :nothing => true rescue render :nothing => true, :status => 500 end end
[ "def", "restore_to_list", "begin", "matching_results_ids", "=", "session", "[", ":matching_results_ids", "]", "session", "[", ":matching_results_ids", "]", "=", "matching_results_ids", "<<", "params", "[", ":restore_id", "]", ".", "to_i", "render", ":nothing", "=>", "true", "rescue", "render", ":nothing", "=>", "true", ",", ":status", "=>", "500", "end", "end" ]
assumes matching_results_ids in the session puts back a given restore_id in the session variable
[ "assumes", "matching_results_ids", "in", "the", "session", "puts", "back", "a", "given", "restore_id", "in", "the", "session", "variable" ]
5998ecd83967108c1ed1378161e43feb80d6b886
https://github.com/kete/kete_trackable_items/blob/5998ecd83967108c1ed1378161e43feb80d6b886/lib/kete_trackable_items/list_management_controllers.rb#L20-L28
train
Thermatix/ruta
lib/ruta/context.rb
Ruta.Context.sub_context
def sub_context id,ref,attribs={} @sub_contexts << ref self.elements[id] = { attributes: attribs, type: :sub_context, content: ref, } end
ruby
def sub_context id,ref,attribs={} @sub_contexts << ref self.elements[id] = { attributes: attribs, type: :sub_context, content: ref, } end
[ "def", "sub_context", "id", ",", "ref", ",", "attribs", "=", "{", "}", "@sub_contexts", "<<", "ref", "self", ".", "elements", "[", "id", "]", "=", "{", "attributes", ":", "attribs", ",", "type", ":", ":sub_context", ",", "content", ":", "ref", ",", "}", "end" ]
mount a context as a sub context here @param [Symbol] id of component to mount context to @param [Symbol] ref of context to be mounted @param [{Symbol => String,Number,Boolean}] list of attributes to attach to tag
[ "mount", "a", "context", "as", "a", "sub", "context", "here" ]
b4a6e3bc7c0c4b66c804023d638b173e3f61e157
https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/context.rb#L50-L57
train
smartdict/smartdict-core
lib/smartdict/translator/base.rb
Smartdict.Translator::Base.call
def call(word, opts) validate_opts!(opts) driver = Smartdict::Core::DriverManager.find(opts[:driver]) translation_model = Models::Translation.find(word, opts[:from_lang], opts[:to_lang], opts[:driver]) unless translation_model translation = driver.translate(word, opts[:from_lang], opts[:to_lang]) translation_model = Models::Translation.create_from_struct(translation) end log_query(translation_model) if opts[:log] translation_model.to_struct end
ruby
def call(word, opts) validate_opts!(opts) driver = Smartdict::Core::DriverManager.find(opts[:driver]) translation_model = Models::Translation.find(word, opts[:from_lang], opts[:to_lang], opts[:driver]) unless translation_model translation = driver.translate(word, opts[:from_lang], opts[:to_lang]) translation_model = Models::Translation.create_from_struct(translation) end log_query(translation_model) if opts[:log] translation_model.to_struct end
[ "def", "call", "(", "word", ",", "opts", ")", "validate_opts!", "(", "opts", ")", "driver", "=", "Smartdict", "::", "Core", "::", "DriverManager", ".", "find", "(", "opts", "[", ":driver", "]", ")", "translation_model", "=", "Models", "::", "Translation", ".", "find", "(", "word", ",", "opts", "[", ":from_lang", "]", ",", "opts", "[", ":to_lang", "]", ",", "opts", "[", ":driver", "]", ")", "unless", "translation_model", "translation", "=", "driver", ".", "translate", "(", "word", ",", "opts", "[", ":from_lang", "]", ",", "opts", "[", ":to_lang", "]", ")", "translation_model", "=", "Models", "::", "Translation", ".", "create_from_struct", "(", "translation", ")", "end", "log_query", "(", "translation_model", ")", "if", "opts", "[", ":log", "]", "translation_model", ".", "to_struct", "end" ]
Just to make the interface compatible
[ "Just", "to", "make", "the", "interface", "compatible" ]
d2a83a7ca10daa085ffb740837891057a9c2bcea
https://github.com/smartdict/smartdict-core/blob/d2a83a7ca10daa085ffb740837891057a9c2bcea/lib/smartdict/translator/base.rb#L8-L19
train
mdoza/mongoid_multiparams
lib/mongoid_multiparams.rb
Mongoid.MultiParameterAttributes.process_attributes
def process_attributes(attrs = nil) if attrs errors = [] attributes = attrs.class.new attributes.permit! if attrs.respond_to?(:permitted?) && attrs.permitted? multi_parameter_attributes = {} attrs.each_pair do |key, value| if key =~ /\A([^\(]+)\((\d+)([if])\)$/ key, index = $1, $2.to_i (multi_parameter_attributes[key] ||= {})[index] = value.empty? ? nil : value.send("to_#{$3}") else attributes[key] = value end end multi_parameter_attributes.each_pair do |key, values| begin values = (values.keys.min..values.keys.max).map { |i| values[i] } field = self.class.fields[database_field_name(key)] attributes[key] = instantiate_object(field, values) rescue => e errors << Errors::AttributeAssignmentError.new( "error on assignment #{values.inspect} to #{key}", e, key ) end end unless errors.empty? raise Errors::MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes" end super(attributes) else super end end
ruby
def process_attributes(attrs = nil) if attrs errors = [] attributes = attrs.class.new attributes.permit! if attrs.respond_to?(:permitted?) && attrs.permitted? multi_parameter_attributes = {} attrs.each_pair do |key, value| if key =~ /\A([^\(]+)\((\d+)([if])\)$/ key, index = $1, $2.to_i (multi_parameter_attributes[key] ||= {})[index] = value.empty? ? nil : value.send("to_#{$3}") else attributes[key] = value end end multi_parameter_attributes.each_pair do |key, values| begin values = (values.keys.min..values.keys.max).map { |i| values[i] } field = self.class.fields[database_field_name(key)] attributes[key] = instantiate_object(field, values) rescue => e errors << Errors::AttributeAssignmentError.new( "error on assignment #{values.inspect} to #{key}", e, key ) end end unless errors.empty? raise Errors::MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes" end super(attributes) else super end end
[ "def", "process_attributes", "(", "attrs", "=", "nil", ")", "if", "attrs", "errors", "=", "[", "]", "attributes", "=", "attrs", ".", "class", ".", "new", "attributes", ".", "permit!", "if", "attrs", ".", "respond_to?", "(", ":permitted?", ")", "&&", "attrs", ".", "permitted?", "multi_parameter_attributes", "=", "{", "}", "attrs", ".", "each_pair", "do", "|", "key", ",", "value", "|", "if", "key", "=~", "/", "\\A", "\\(", "\\(", "\\d", "\\)", "/", "key", ",", "index", "=", "$1", ",", "$2", ".", "to_i", "(", "multi_parameter_attributes", "[", "key", "]", "||=", "{", "}", ")", "[", "index", "]", "=", "value", ".", "empty?", "?", "nil", ":", "value", ".", "send", "(", "\"to_#{$3}\"", ")", "else", "attributes", "[", "key", "]", "=", "value", "end", "end", "multi_parameter_attributes", ".", "each_pair", "do", "|", "key", ",", "values", "|", "begin", "values", "=", "(", "values", ".", "keys", ".", "min", "..", "values", ".", "keys", ".", "max", ")", ".", "map", "{", "|", "i", "|", "values", "[", "i", "]", "}", "field", "=", "self", ".", "class", ".", "fields", "[", "database_field_name", "(", "key", ")", "]", "attributes", "[", "key", "]", "=", "instantiate_object", "(", "field", ",", "values", ")", "rescue", "=>", "e", "errors", "<<", "Errors", "::", "AttributeAssignmentError", ".", "new", "(", "\"error on assignment #{values.inspect} to #{key}\"", ",", "e", ",", "key", ")", "end", "end", "unless", "errors", ".", "empty?", "raise", "Errors", "::", "MultiparameterAssignmentErrors", ".", "new", "(", "errors", ")", ",", "\"#{errors.size} error(s) on assignment of multiparameter attributes\"", "end", "super", "(", "attributes", ")", "else", "super", "end", "end" ]
Process the provided attributes casting them to their proper values if a field exists for them on the document. This will be limited to only the attributes provided in the suppied +Hash+ so that no extra nil values get put into the document's attributes. @example Process the attributes. person.process_attributes(:title => "sir", :age => 40) @param [ Hash ] attrs The attributes to set. @since 2.0.0.rc.7
[ "Process", "the", "provided", "attributes", "casting", "them", "to", "their", "proper", "values", "if", "a", "field", "exists", "for", "them", "on", "the", "document", ".", "This", "will", "be", "limited", "to", "only", "the", "attributes", "provided", "in", "the", "suppied", "+", "Hash", "+", "so", "that", "no", "extra", "nil", "values", "get", "put", "into", "the", "document", "s", "attributes", "." ]
9cbc4ed87a27f6635184b472ef2e5c4fc4160f74
https://github.com/mdoza/mongoid_multiparams/blob/9cbc4ed87a27f6635184b472ef2e5c4fc4160f74/lib/mongoid_multiparams.rb#L79-L115
train
inside-track/remi
lib/remi/data_subjects/s3_file.rb
Remi.Loader::S3File.load
def load(data) init_kms(@kms_opt) @logger.info "Writing file #{data} to S3 #{@bucket_name} as #{@remote_path}" s3.bucket(@bucket_name).object(@remote_path).upload_file(data, encrypt_args) true end
ruby
def load(data) init_kms(@kms_opt) @logger.info "Writing file #{data} to S3 #{@bucket_name} as #{@remote_path}" s3.bucket(@bucket_name).object(@remote_path).upload_file(data, encrypt_args) true end
[ "def", "load", "(", "data", ")", "init_kms", "(", "@kms_opt", ")", "@logger", ".", "info", "\"Writing file #{data} to S3 #{@bucket_name} as #{@remote_path}\"", "s3", ".", "bucket", "(", "@bucket_name", ")", ".", "object", "(", "@remote_path", ")", ".", "upload_file", "(", "data", ",", "encrypt_args", ")", "true", "end" ]
Copies data to S3 @param data [Object] The path to the file in the temporary work location @return [true] On success
[ "Copies", "data", "to", "S3" ]
f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7
https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/data_subjects/s3_file.rb#L252-L258
train
OiNutter/skeletor
lib/skeletor/builder.rb
Skeletor.Builder.build_skeleton
def build_skeleton(dirs,path=@path) dirs.each{ |node| if node.kind_of?(Hash) && !node.empty?() node.each_pair{ |dir,content| dir = replace_tags(dir) puts 'Creating directory ' + File.join(path,dir) Dir.mkdir(File.join(path,dir)) if content.kind_of?(Array) && !content.empty?() build_skeleton(content,File.join(path,dir)) end } elsif node.kind_of?(Array) && !node.empty?() node.each{ |file| write_file(file,path) } end } end
ruby
def build_skeleton(dirs,path=@path) dirs.each{ |node| if node.kind_of?(Hash) && !node.empty?() node.each_pair{ |dir,content| dir = replace_tags(dir) puts 'Creating directory ' + File.join(path,dir) Dir.mkdir(File.join(path,dir)) if content.kind_of?(Array) && !content.empty?() build_skeleton(content,File.join(path,dir)) end } elsif node.kind_of?(Array) && !node.empty?() node.each{ |file| write_file(file,path) } end } end
[ "def", "build_skeleton", "(", "dirs", ",", "path", "=", "@path", ")", "dirs", ".", "each", "{", "|", "node", "|", "if", "node", ".", "kind_of?", "(", "Hash", ")", "&&", "!", "node", ".", "empty?", "(", ")", "node", ".", "each_pair", "{", "|", "dir", ",", "content", "|", "dir", "=", "replace_tags", "(", "dir", ")", "puts", "'Creating directory '", "+", "File", ".", "join", "(", "path", ",", "dir", ")", "Dir", ".", "mkdir", "(", "File", ".", "join", "(", "path", ",", "dir", ")", ")", "if", "content", ".", "kind_of?", "(", "Array", ")", "&&", "!", "content", ".", "empty?", "(", ")", "build_skeleton", "(", "content", ",", "File", ".", "join", "(", "path", ",", "dir", ")", ")", "end", "}", "elsif", "node", ".", "kind_of?", "(", "Array", ")", "&&", "!", "node", ".", "empty?", "(", ")", "node", ".", "each", "{", "|", "file", "|", "write_file", "(", "file", ",", "path", ")", "}", "end", "}", "end" ]
Builds the directory structure
[ "Builds", "the", "directory", "structure" ]
c3996c346bbf8009f7135855aabfd4f411aaa2e1
https://github.com/OiNutter/skeletor/blob/c3996c346bbf8009f7135855aabfd4f411aaa2e1/lib/skeletor/builder.rb#L46-L76
train
OiNutter/skeletor
lib/skeletor/builder.rb
Skeletor.Builder.write_file
def write_file(file,path) #if a pre-existing file is specified in the includes list, copy that, if not write a blank file if @template.includes.has_key?(file) begin content = Includes.copy_include(@template.includes[file],@template.path) file = replace_tags(file) rescue TypeError => e puts e.message exit end else file = replace_tags(file) puts 'Creating blank file: ' + File.join(path,file) content='' end File.open(File.join(path,file),'w'){|f| f.write(replace_tags(content))} end
ruby
def write_file(file,path) #if a pre-existing file is specified in the includes list, copy that, if not write a blank file if @template.includes.has_key?(file) begin content = Includes.copy_include(@template.includes[file],@template.path) file = replace_tags(file) rescue TypeError => e puts e.message exit end else file = replace_tags(file) puts 'Creating blank file: ' + File.join(path,file) content='' end File.open(File.join(path,file),'w'){|f| f.write(replace_tags(content))} end
[ "def", "write_file", "(", "file", ",", "path", ")", "if", "@template", ".", "includes", ".", "has_key?", "(", "file", ")", "begin", "content", "=", "Includes", ".", "copy_include", "(", "@template", ".", "includes", "[", "file", "]", ",", "@template", ".", "path", ")", "file", "=", "replace_tags", "(", "file", ")", "rescue", "TypeError", "=>", "e", "puts", "e", ".", "message", "exit", "end", "else", "file", "=", "replace_tags", "(", "file", ")", "puts", "'Creating blank file: '", "+", "File", ".", "join", "(", "path", ",", "file", ")", "content", "=", "''", "end", "File", ".", "open", "(", "File", ".", "join", "(", "path", ",", "file", ")", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "replace_tags", "(", "content", ")", ")", "}", "end" ]
Checks if file is listed in the includes list and if so copies it from the given location. If not it creates a blank file.
[ "Checks", "if", "file", "is", "listed", "in", "the", "includes", "list", "and", "if", "so", "copies", "it", "from", "the", "given", "location", ".", "If", "not", "it", "creates", "a", "blank", "file", "." ]
c3996c346bbf8009f7135855aabfd4f411aaa2e1
https://github.com/OiNutter/skeletor/blob/c3996c346bbf8009f7135855aabfd4f411aaa2e1/lib/skeletor/builder.rb#L98-L114
train
OiNutter/skeletor
lib/skeletor/builder.rb
Skeletor.Builder.execute_tasks
def execute_tasks(tasks,template_path) if File.exists?(File.expand_path(File.join(template_path,'tasks.rb'))) load File.expand_path(File.join(template_path,'tasks.rb')) end tasks.each{ |task| puts 'Running Task: ' + task task = replace_tags(task); options = task.split(', ') action = options.slice!(0) if(Tasks.respond_to?(action)) Tasks.send action, options.join(', ') else send action, options.join(', ') end } end
ruby
def execute_tasks(tasks,template_path) if File.exists?(File.expand_path(File.join(template_path,'tasks.rb'))) load File.expand_path(File.join(template_path,'tasks.rb')) end tasks.each{ |task| puts 'Running Task: ' + task task = replace_tags(task); options = task.split(', ') action = options.slice!(0) if(Tasks.respond_to?(action)) Tasks.send action, options.join(', ') else send action, options.join(', ') end } end
[ "def", "execute_tasks", "(", "tasks", ",", "template_path", ")", "if", "File", ".", "exists?", "(", "File", ".", "expand_path", "(", "File", ".", "join", "(", "template_path", ",", "'tasks.rb'", ")", ")", ")", "load", "File", ".", "expand_path", "(", "File", ".", "join", "(", "template_path", ",", "'tasks.rb'", ")", ")", "end", "tasks", ".", "each", "{", "|", "task", "|", "puts", "'Running Task: '", "+", "task", "task", "=", "replace_tags", "(", "task", ")", ";", "options", "=", "task", ".", "split", "(", "', '", ")", "action", "=", "options", ".", "slice!", "(", "0", ")", "if", "(", "Tasks", ".", "respond_to?", "(", "action", ")", ")", "Tasks", ".", "send", "action", ",", "options", ".", "join", "(", "', '", ")", "else", "send", "action", ",", "options", ".", "join", "(", "', '", ")", "end", "}", "end" ]
Parses the task string and runs the task. Will check *Skeleton::Tasks* module first before running tasks from the `tasks.rb` file in the template directory.
[ "Parses", "the", "task", "string", "and", "runs", "the", "task", "." ]
c3996c346bbf8009f7135855aabfd4f411aaa2e1
https://github.com/OiNutter/skeletor/blob/c3996c346bbf8009f7135855aabfd4f411aaa2e1/lib/skeletor/builder.rb#L120-L144
train
wedesoft/multiarray
lib/multiarray/pointer.rb
Hornetseye.Pointer_.assign
def assign( value ) if @value.respond_to? :assign @value.assign value.simplify.get else @value = value.simplify.get end value end
ruby
def assign( value ) if @value.respond_to? :assign @value.assign value.simplify.get else @value = value.simplify.get end value end
[ "def", "assign", "(", "value", ")", "if", "@value", ".", "respond_to?", ":assign", "@value", ".", "assign", "value", ".", "simplify", ".", "get", "else", "@value", "=", "value", ".", "simplify", ".", "get", "end", "value", "end" ]
Store a value in this native element @param [Object] value New value for native element. @return [Object] Returns +value+. @private
[ "Store", "a", "value", "in", "this", "native", "element" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/pointer.rb#L178-L185
train
wedesoft/multiarray
lib/multiarray/pointer.rb
Hornetseye.Pointer_.store
def store( value ) result = value.simplify self.class.target.new(result.get).write @value result end
ruby
def store( value ) result = value.simplify self.class.target.new(result.get).write @value result end
[ "def", "store", "(", "value", ")", "result", "=", "value", ".", "simplify", "self", ".", "class", ".", "target", ".", "new", "(", "result", ".", "get", ")", ".", "write", "@value", "result", "end" ]
Store new value in this pointer @param [Object] value New value for this pointer object. @return [Object] Returns +value+. @private
[ "Store", "new", "value", "in", "this", "pointer" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/pointer.rb#L194-L198
train
stormbrew/user_input
lib/user_input/option_parser.rb
UserInput.OptionParser.define_value
def define_value(short_name, long_name, description, flag, default_value, validate = nil) short_name = short_name.to_s long_name = long_name.to_s if (short_name.length != 1) raise ArgumentError, "Short name must be one character long (#{short_name})" end if (long_name.length < 2) raise ArgumentError, "Long name must be more than one character long (#{long_name})" end info = Info.new(short_name, long_name, description, flag, default_value, nil, validate) @options[long_name] = info @options[short_name] = info @order.push(info) method_name = long_name.gsub('-','_') method_name << "?" if (flag) (class <<self; self; end).class_eval do define_method(method_name.to_sym) do return @options[long_name].value || @options[long_name].default_value end end return self end
ruby
def define_value(short_name, long_name, description, flag, default_value, validate = nil) short_name = short_name.to_s long_name = long_name.to_s if (short_name.length != 1) raise ArgumentError, "Short name must be one character long (#{short_name})" end if (long_name.length < 2) raise ArgumentError, "Long name must be more than one character long (#{long_name})" end info = Info.new(short_name, long_name, description, flag, default_value, nil, validate) @options[long_name] = info @options[short_name] = info @order.push(info) method_name = long_name.gsub('-','_') method_name << "?" if (flag) (class <<self; self; end).class_eval do define_method(method_name.to_sym) do return @options[long_name].value || @options[long_name].default_value end end return self end
[ "def", "define_value", "(", "short_name", ",", "long_name", ",", "description", ",", "flag", ",", "default_value", ",", "validate", "=", "nil", ")", "short_name", "=", "short_name", ".", "to_s", "long_name", "=", "long_name", ".", "to_s", "if", "(", "short_name", ".", "length", "!=", "1", ")", "raise", "ArgumentError", ",", "\"Short name must be one character long (#{short_name})\"", "end", "if", "(", "long_name", ".", "length", "<", "2", ")", "raise", "ArgumentError", ",", "\"Long name must be more than one character long (#{long_name})\"", "end", "info", "=", "Info", ".", "new", "(", "short_name", ",", "long_name", ",", "description", ",", "flag", ",", "default_value", ",", "nil", ",", "validate", ")", "@options", "[", "long_name", "]", "=", "info", "@options", "[", "short_name", "]", "=", "info", "@order", ".", "push", "(", "info", ")", "method_name", "=", "long_name", ".", "gsub", "(", "'-'", ",", "'_'", ")", "method_name", "<<", "\"?\"", "if", "(", "flag", ")", "(", "class", "<<", "self", ";", "self", ";", "end", ")", ".", "class_eval", "do", "define_method", "(", "method_name", ".", "to_sym", ")", "do", "return", "@options", "[", "long_name", "]", ".", "value", "||", "@options", "[", "long_name", "]", ".", "default_value", "end", "end", "return", "self", "end" ]
If a block is passed in, it is given self.
[ "If", "a", "block", "is", "passed", "in", "it", "is", "given", "self", "." ]
593a1deb08f0634089d25542971ad0ac57542259
https://github.com/stormbrew/user_input/blob/593a1deb08f0634089d25542971ad0ac57542259/lib/user_input/option_parser.rb#L52-L78
train
stormbrew/user_input
lib/user_input/option_parser.rb
UserInput.OptionParser.argument
def argument(short_name, long_name, description, default_value, validate = nil, &block) return define_value(short_name, long_name, description, false, default_value, validate || block) end
ruby
def argument(short_name, long_name, description, default_value, validate = nil, &block) return define_value(short_name, long_name, description, false, default_value, validate || block) end
[ "def", "argument", "(", "short_name", ",", "long_name", ",", "description", ",", "default_value", ",", "validate", "=", "nil", ",", "&", "block", ")", "return", "define_value", "(", "short_name", ",", "long_name", ",", "description", ",", "false", ",", "default_value", ",", "validate", "||", "block", ")", "end" ]
This defines a command line argument that takes a value.
[ "This", "defines", "a", "command", "line", "argument", "that", "takes", "a", "value", "." ]
593a1deb08f0634089d25542971ad0ac57542259
https://github.com/stormbrew/user_input/blob/593a1deb08f0634089d25542971ad0ac57542259/lib/user_input/option_parser.rb#L89-L91
train
stormbrew/user_input
lib/user_input/option_parser.rb
UserInput.OptionParser.flag
def flag(short_name, long_name, description, &block) return define_value(short_name, long_name, description, true, false, block) end
ruby
def flag(short_name, long_name, description, &block) return define_value(short_name, long_name, description, true, false, block) end
[ "def", "flag", "(", "short_name", ",", "long_name", ",", "description", ",", "&", "block", ")", "return", "define_value", "(", "short_name", ",", "long_name", ",", "description", ",", "true", ",", "false", ",", "block", ")", "end" ]
This defines a command line argument that's either on or off based on the presense of the flag.
[ "This", "defines", "a", "command", "line", "argument", "that", "s", "either", "on", "or", "off", "based", "on", "the", "presense", "of", "the", "flag", "." ]
593a1deb08f0634089d25542971ad0ac57542259
https://github.com/stormbrew/user_input/blob/593a1deb08f0634089d25542971ad0ac57542259/lib/user_input/option_parser.rb#L95-L97
train
mrsimonfletcher/roroacms
app/controllers/roroacms/setup_controller.rb
Roroacms.SetupController.create
def create # To do update this table we loop through the fields and update the key with the value. # In order to do this we need to remove any unnecessary keys from the params hash remove_unwanted_keys # loop through the param fields and update the key with the value validation = Setting.manual_validation(params) respond_to do |format| if validation.blank? Setting.save_data(params) clear_cache format.html { redirect_to administrator_setup_index_path, notice: I18n.t("controllers.admin.setup.general.success") } else format.html { # add breadcrumb and set title @settings = params @settings['errors'] = validation render action: "index" } end end end
ruby
def create # To do update this table we loop through the fields and update the key with the value. # In order to do this we need to remove any unnecessary keys from the params hash remove_unwanted_keys # loop through the param fields and update the key with the value validation = Setting.manual_validation(params) respond_to do |format| if validation.blank? Setting.save_data(params) clear_cache format.html { redirect_to administrator_setup_index_path, notice: I18n.t("controllers.admin.setup.general.success") } else format.html { # add breadcrumb and set title @settings = params @settings['errors'] = validation render action: "index" } end end end
[ "def", "create", "remove_unwanted_keys", "validation", "=", "Setting", ".", "manual_validation", "(", "params", ")", "respond_to", "do", "|", "format", "|", "if", "validation", ".", "blank?", "Setting", ".", "save_data", "(", "params", ")", "clear_cache", "format", ".", "html", "{", "redirect_to", "administrator_setup_index_path", ",", "notice", ":", "I18n", ".", "t", "(", "\"controllers.admin.setup.general.success\"", ")", "}", "else", "format", ".", "html", "{", "@settings", "=", "params", "@settings", "[", "'errors'", "]", "=", "validation", "render", "action", ":", "\"index\"", "}", "end", "end", "end" ]
Create the settings for the Admin panel to work!
[ "Create", "the", "settings", "for", "the", "Admin", "panel", "to", "work!" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/setup_controller.rb#L22-L46
train
mrsimonfletcher/roroacms
app/controllers/roroacms/setup_controller.rb
Roroacms.SetupController.create_user
def create_user @admin = Admin.new(administrator_params) @admin.access_level = 'admin' @admin.overlord = 'Y' respond_to do |format| if @admin.save Setting.save_data({setup_complete: 'Y'}) clear_cache session[:setup_complete] = true format.html { redirect_to admin_path, notice: I18n.t("controllers.admin.setup.general.success") } else format.html { render action: "administrator" } end end end
ruby
def create_user @admin = Admin.new(administrator_params) @admin.access_level = 'admin' @admin.overlord = 'Y' respond_to do |format| if @admin.save Setting.save_data({setup_complete: 'Y'}) clear_cache session[:setup_complete] = true format.html { redirect_to admin_path, notice: I18n.t("controllers.admin.setup.general.success") } else format.html { render action: "administrator" } end end end
[ "def", "create_user", "@admin", "=", "Admin", ".", "new", "(", "administrator_params", ")", "@admin", ".", "access_level", "=", "'admin'", "@admin", ".", "overlord", "=", "'Y'", "respond_to", "do", "|", "format", "|", "if", "@admin", ".", "save", "Setting", ".", "save_data", "(", "{", "setup_complete", ":", "'Y'", "}", ")", "clear_cache", "session", "[", ":setup_complete", "]", "=", "true", "format", ".", "html", "{", "redirect_to", "admin_path", ",", "notice", ":", "I18n", ".", "t", "(", "\"controllers.admin.setup.general.success\"", ")", "}", "else", "format", ".", "html", "{", "render", "action", ":", "\"administrator\"", "}", "end", "end", "end" ]
create a new admin user
[ "create", "a", "new", "admin", "user" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/setup_controller.rb#L50-L66
train
mrackwitz/CLIntegracon
lib/CLIntegracon/file_tree_spec.rb
CLIntegracon.FileTreeSpec.compare
def compare(&diff_block) # Get a copy of the outputs before any transformations are applied FileUtils.cp_r("#{temp_transformed_path}/.", temp_raw_path) transform_paths! glob_all(after_path).each do |relative_path| expected = after_path + relative_path next unless expected.file? next if context.ignores?(relative_path) block = context.preprocessors_for(relative_path).first diff = diff_files(expected, relative_path, &block) diff_block.call diff end end
ruby
def compare(&diff_block) # Get a copy of the outputs before any transformations are applied FileUtils.cp_r("#{temp_transformed_path}/.", temp_raw_path) transform_paths! glob_all(after_path).each do |relative_path| expected = after_path + relative_path next unless expected.file? next if context.ignores?(relative_path) block = context.preprocessors_for(relative_path).first diff = diff_files(expected, relative_path, &block) diff_block.call diff end end
[ "def", "compare", "(", "&", "diff_block", ")", "FileUtils", ".", "cp_r", "(", "\"#{temp_transformed_path}/.\"", ",", "temp_raw_path", ")", "transform_paths!", "glob_all", "(", "after_path", ")", ".", "each", "do", "|", "relative_path", "|", "expected", "=", "after_path", "+", "relative_path", "next", "unless", "expected", ".", "file?", "next", "if", "context", ".", "ignores?", "(", "relative_path", ")", "block", "=", "context", ".", "preprocessors_for", "(", "relative_path", ")", ".", "first", "diff", "=", "diff_files", "(", "expected", ",", "relative_path", ",", "&", "block", ")", "diff_block", ".", "call", "diff", "end", "end" ]
Compares the expected and produced directory by using the rules defined in the context @param [Block<(Diff)->()>] diff_block The block, where you will likely define a test for each file to compare. It will receive a Diff of each of the expected and produced files.
[ "Compares", "the", "expected", "and", "produced", "directory", "by", "using", "the", "rules", "defined", "in", "the", "context" ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/file_tree_spec.rb#L121-L138
train
mrackwitz/CLIntegracon
lib/CLIntegracon/file_tree_spec.rb
CLIntegracon.FileTreeSpec.check_unexpected_files
def check_unexpected_files(&block) expected_files = glob_all after_path produced_files = glob_all unexpected_files = produced_files - expected_files # Select only files unexpected_files.select! { |path| path.file? } # Filter ignored paths unexpected_files.reject! { |path| context.ignores?(path) } block.call unexpected_files end
ruby
def check_unexpected_files(&block) expected_files = glob_all after_path produced_files = glob_all unexpected_files = produced_files - expected_files # Select only files unexpected_files.select! { |path| path.file? } # Filter ignored paths unexpected_files.reject! { |path| context.ignores?(path) } block.call unexpected_files end
[ "def", "check_unexpected_files", "(", "&", "block", ")", "expected_files", "=", "glob_all", "after_path", "produced_files", "=", "glob_all", "unexpected_files", "=", "produced_files", "-", "expected_files", "unexpected_files", ".", "select!", "{", "|", "path", "|", "path", ".", "file?", "}", "unexpected_files", ".", "reject!", "{", "|", "path", "|", "context", ".", "ignores?", "(", "path", ")", "}", "block", ".", "call", "unexpected_files", "end" ]
Compares the expected and produced directory by using the rules defined in the context for unexpected files. This is separate because you probably don't want to define an extra test case for each file, which wasn't expected at all. So you can keep your test cases consistent. @param [Block<(Array)->()>] diff_block The block, where you will likely define a test that no unexpected files exists. It will receive an Array.
[ "Compares", "the", "expected", "and", "produced", "directory", "by", "using", "the", "rules", "defined", "in", "the", "context", "for", "unexpected", "files", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/file_tree_spec.rb#L151-L163
train
mrackwitz/CLIntegracon
lib/CLIntegracon/file_tree_spec.rb
CLIntegracon.FileTreeSpec.prepare!
def prepare! context.prepare! temp_path.rmtree if temp_path.exist? temp_path.mkdir temp_raw_path.mkdir temp_transformed_path.mkdir end
ruby
def prepare! context.prepare! temp_path.rmtree if temp_path.exist? temp_path.mkdir temp_raw_path.mkdir temp_transformed_path.mkdir end
[ "def", "prepare!", "context", ".", "prepare!", "temp_path", ".", "rmtree", "if", "temp_path", ".", "exist?", "temp_path", ".", "mkdir", "temp_raw_path", ".", "mkdir", "temp_transformed_path", ".", "mkdir", "end" ]
Prepare the temporary directory
[ "Prepare", "the", "temporary", "directory" ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/file_tree_spec.rb#L177-L184
train
mrackwitz/CLIntegracon
lib/CLIntegracon/file_tree_spec.rb
CLIntegracon.FileTreeSpec.copy_files!
def copy_files! destination = temp_transformed_path if has_base? FileUtils.cp_r("#{base_spec.temp_raw_path}/.", destination) end begin FileUtils.cp_r("#{before_path}/.", destination) rescue Errno::ENOENT => e raise e unless has_base? end end
ruby
def copy_files! destination = temp_transformed_path if has_base? FileUtils.cp_r("#{base_spec.temp_raw_path}/.", destination) end begin FileUtils.cp_r("#{before_path}/.", destination) rescue Errno::ENOENT => e raise e unless has_base? end end
[ "def", "copy_files!", "destination", "=", "temp_transformed_path", "if", "has_base?", "FileUtils", ".", "cp_r", "(", "\"#{base_spec.temp_raw_path}/.\"", ",", "destination", ")", "end", "begin", "FileUtils", ".", "cp_r", "(", "\"#{before_path}/.\"", ",", "destination", ")", "rescue", "Errno", "::", "ENOENT", "=>", "e", "raise", "e", "unless", "has_base?", "end", "end" ]
Copies the before subdirectory of the given tests folder in the raw directory.
[ "Copies", "the", "before", "subdirectory", "of", "the", "given", "tests", "folder", "in", "the", "raw", "directory", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/file_tree_spec.rb#L189-L201
train
mrackwitz/CLIntegracon
lib/CLIntegracon/file_tree_spec.rb
CLIntegracon.FileTreeSpec.transform_paths!
def transform_paths! glob_all.each do |path| context.transformers_for(path).each do |transformer| transformer.call(path) if path.exist? end path.rmtree if context.ignores?(path) && path.exist? end end
ruby
def transform_paths! glob_all.each do |path| context.transformers_for(path).each do |transformer| transformer.call(path) if path.exist? end path.rmtree if context.ignores?(path) && path.exist? end end
[ "def", "transform_paths!", "glob_all", ".", "each", "do", "|", "path", "|", "context", ".", "transformers_for", "(", "path", ")", ".", "each", "do", "|", "transformer", "|", "transformer", ".", "call", "(", "path", ")", "if", "path", ".", "exist?", "end", "path", ".", "rmtree", "if", "context", ".", "ignores?", "(", "path", ")", "&&", "path", ".", "exist?", "end", "end" ]
Applies the in the context configured transformations.
[ "Applies", "the", "in", "the", "context", "configured", "transformations", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/file_tree_spec.rb#L205-L212
train
mrackwitz/CLIntegracon
lib/CLIntegracon/file_tree_spec.rb
CLIntegracon.FileTreeSpec.glob_all
def glob_all(path=nil) Dir.chdir path || '.' do Pathname.glob("**/*", context.include_hidden_files? ? File::FNM_DOTMATCH : 0).sort.reject do |p| %w(. ..).include?(p.basename.to_s) end end end
ruby
def glob_all(path=nil) Dir.chdir path || '.' do Pathname.glob("**/*", context.include_hidden_files? ? File::FNM_DOTMATCH : 0).sort.reject do |p| %w(. ..).include?(p.basename.to_s) end end end
[ "def", "glob_all", "(", "path", "=", "nil", ")", "Dir", ".", "chdir", "path", "||", "'.'", "do", "Pathname", ".", "glob", "(", "\"**/*\"", ",", "context", ".", "include_hidden_files?", "?", "File", "::", "FNM_DOTMATCH", ":", "0", ")", ".", "sort", ".", "reject", "do", "|", "p", "|", "%w(", ".", "..", ")", ".", "include?", "(", "p", ".", "basename", ".", "to_s", ")", "end", "end", "end" ]
Searches recursively for all files and take care for including hidden files if this is configured in the context. @param [String] path The relative or absolute path to search in (optional) @return [Array<Pathname>]
[ "Searches", "recursively", "for", "all", "files", "and", "take", "care", "for", "including", "hidden", "files", "if", "this", "is", "configured", "in", "the", "context", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/file_tree_spec.rb#L222-L228
train
mrackwitz/CLIntegracon
lib/CLIntegracon/file_tree_spec.rb
CLIntegracon.FileTreeSpec.diff_files
def diff_files(expected, relative_path, &block) produced = temp_transformed_path + relative_path Diff.new(expected, produced, relative_path, &block) end
ruby
def diff_files(expected, relative_path, &block) produced = temp_transformed_path + relative_path Diff.new(expected, produced, relative_path, &block) end
[ "def", "diff_files", "(", "expected", ",", "relative_path", ",", "&", "block", ")", "produced", "=", "temp_transformed_path", "+", "relative_path", "Diff", ".", "new", "(", "expected", ",", "produced", ",", "relative_path", ",", "&", "block", ")", "end" ]
Compares two files to check if they are identical and produces a clear diff to highlight the differences. @param [Pathname] expected The file in the after directory @param [Pathname] relative_path The file in the temp directory @param [Block<(Pathname)->(to_s)>] block the block, which transforms the files in a better comparable form @return [Diff] An object holding a diff
[ "Compares", "two", "files", "to", "check", "if", "they", "are", "identical", "and", "produces", "a", "clear", "diff", "to", "highlight", "the", "differences", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/file_tree_spec.rb#L245-L248
train
ladder/ladder
lib/ladder/resource.rb
Ladder.Resource.klass_from_predicate
def klass_from_predicate(predicate) field_name = field_from_predicate(predicate) return unless field_name relation = relations[field_name] return unless relation relation.class_name.constantize end
ruby
def klass_from_predicate(predicate) field_name = field_from_predicate(predicate) return unless field_name relation = relations[field_name] return unless relation relation.class_name.constantize end
[ "def", "klass_from_predicate", "(", "predicate", ")", "field_name", "=", "field_from_predicate", "(", "predicate", ")", "return", "unless", "field_name", "relation", "=", "relations", "[", "field_name", "]", "return", "unless", "relation", "relation", ".", "class_name", ".", "constantize", "end" ]
Retrieve the class for a relation, based on its defined RDF predicate @param [RDF::URI] predicate a URI for the RDF::Term @return [Ladder::Resource, Ladder::File, nil] related class
[ "Retrieve", "the", "class", "for", "a", "relation", "based", "on", "its", "defined", "RDF", "predicate" ]
fdb17fbeb93e89c670f3ca5d431f29be0a682fd2
https://github.com/ladder/ladder/blob/fdb17fbeb93e89c670f3ca5d431f29be0a682fd2/lib/ladder/resource.rb#L63-L71
train
ladder/ladder
lib/ladder/resource.rb
Ladder.Resource.field_from_predicate
def field_from_predicate(predicate) defined_prop = resource_class.properties.find { |_field_name, term| term.predicate == predicate } return unless defined_prop defined_prop.first end
ruby
def field_from_predicate(predicate) defined_prop = resource_class.properties.find { |_field_name, term| term.predicate == predicate } return unless defined_prop defined_prop.first end
[ "def", "field_from_predicate", "(", "predicate", ")", "defined_prop", "=", "resource_class", ".", "properties", ".", "find", "{", "|", "_field_name", ",", "term", "|", "term", ".", "predicate", "==", "predicate", "}", "return", "unless", "defined_prop", "defined_prop", ".", "first", "end" ]
Retrieve the attribute name for a field or relation, based on its defined RDF predicate @param [RDF::URI] predicate a URI for the RDF::Term @return [String, nil] name for the attribute
[ "Retrieve", "the", "attribute", "name", "for", "a", "field", "or", "relation", "based", "on", "its", "defined", "RDF", "predicate" ]
fdb17fbeb93e89c670f3ca5d431f29be0a682fd2
https://github.com/ladder/ladder/blob/fdb17fbeb93e89c670f3ca5d431f29be0a682fd2/lib/ladder/resource.rb#L79-L84
train
ladder/ladder
lib/ladder/resource.rb
Ladder.Resource.update_relation
def update_relation(field_name, *obj) # Should be an Array of RDF::Term objects return unless obj obj.map! { |item| item.is_a?(RDF::URI) ? Ladder::Resource.from_uri(item) : item } relation = send(field_name) if Mongoid::Relations::Targets::Enumerable == relation.class obj.map { |item| relation.send(:push, item) unless relation.include? item } else send("#{field_name}=", obj.size > 1 ? obj : obj.first) end end
ruby
def update_relation(field_name, *obj) # Should be an Array of RDF::Term objects return unless obj obj.map! { |item| item.is_a?(RDF::URI) ? Ladder::Resource.from_uri(item) : item } relation = send(field_name) if Mongoid::Relations::Targets::Enumerable == relation.class obj.map { |item| relation.send(:push, item) unless relation.include? item } else send("#{field_name}=", obj.size > 1 ? obj : obj.first) end end
[ "def", "update_relation", "(", "field_name", ",", "*", "obj", ")", "return", "unless", "obj", "obj", ".", "map!", "{", "|", "item", "|", "item", ".", "is_a?", "(", "RDF", "::", "URI", ")", "?", "Ladder", "::", "Resource", ".", "from_uri", "(", "item", ")", ":", "item", "}", "relation", "=", "send", "(", "field_name", ")", "if", "Mongoid", "::", "Relations", "::", "Targets", "::", "Enumerable", "==", "relation", ".", "class", "obj", ".", "map", "{", "|", "item", "|", "relation", ".", "send", "(", ":push", ",", "item", ")", "unless", "relation", ".", "include?", "item", "}", "else", "send", "(", "\"#{field_name}=\"", ",", "obj", ".", "size", ">", "1", "?", "obj", ":", "obj", ".", "first", ")", "end", "end" ]
Set values on a defined relation @param [String] field_name ActiveModel attribute name for the field @param [Array<Object>] obj objects (usually Ladder::Resources) to be set @return [Ladder::Resource, nil]
[ "Set", "values", "on", "a", "defined", "relation" ]
fdb17fbeb93e89c670f3ca5d431f29be0a682fd2
https://github.com/ladder/ladder/blob/fdb17fbeb93e89c670f3ca5d431f29be0a682fd2/lib/ladder/resource.rb#L94-L106
train
ladder/ladder
lib/ladder/resource.rb
Ladder.Resource.update_field
def update_field(field_name, *obj) # Should be an Array of RDF::Term objects return unless obj if fields[field_name] && fields[field_name].localized? trans = {} obj.each do |item| lang = item.is_a?(RDF::Literal) && item.has_language? ? item.language.to_s : I18n.locale.to_s value = item.is_a?(RDF::URI) ? item.to_s : item.object # TODO: tidy this up trans[lang] = trans[lang] ? [*trans[lang]] << value : value end send("#{field_name}_translations=", trans) unless trans.empty? else objects = obj.map { |item| item.is_a?(RDF::URI) ? item.to_s : item.object } # TODO: tidy this up send("#{field_name}=", objects.size > 1 ? objects : objects.first) end end
ruby
def update_field(field_name, *obj) # Should be an Array of RDF::Term objects return unless obj if fields[field_name] && fields[field_name].localized? trans = {} obj.each do |item| lang = item.is_a?(RDF::Literal) && item.has_language? ? item.language.to_s : I18n.locale.to_s value = item.is_a?(RDF::URI) ? item.to_s : item.object # TODO: tidy this up trans[lang] = trans[lang] ? [*trans[lang]] << value : value end send("#{field_name}_translations=", trans) unless trans.empty? else objects = obj.map { |item| item.is_a?(RDF::URI) ? item.to_s : item.object } # TODO: tidy this up send("#{field_name}=", objects.size > 1 ? objects : objects.first) end end
[ "def", "update_field", "(", "field_name", ",", "*", "obj", ")", "return", "unless", "obj", "if", "fields", "[", "field_name", "]", "&&", "fields", "[", "field_name", "]", ".", "localized?", "trans", "=", "{", "}", "obj", ".", "each", "do", "|", "item", "|", "lang", "=", "item", ".", "is_a?", "(", "RDF", "::", "Literal", ")", "&&", "item", ".", "has_language?", "?", "item", ".", "language", ".", "to_s", ":", "I18n", ".", "locale", ".", "to_s", "value", "=", "item", ".", "is_a?", "(", "RDF", "::", "URI", ")", "?", "item", ".", "to_s", ":", "item", ".", "object", "trans", "[", "lang", "]", "=", "trans", "[", "lang", "]", "?", "[", "*", "trans", "[", "lang", "]", "]", "<<", "value", ":", "value", "end", "send", "(", "\"#{field_name}_translations=\"", ",", "trans", ")", "unless", "trans", ".", "empty?", "else", "objects", "=", "obj", ".", "map", "{", "|", "item", "|", "item", ".", "is_a?", "(", "RDF", "::", "URI", ")", "?", "item", ".", "to_s", ":", "item", ".", "object", "}", "send", "(", "\"#{field_name}=\"", ",", "objects", ".", "size", ">", "1", "?", "objects", ":", "objects", ".", "first", ")", "end", "end" ]
Set values on a field; this will cast values from RDF types to persistable Mongoid types @param [String] field_name ActiveModel attribute name for the field @param [Array<Object>] obj objects (usually RDF::Terms) to be set @return [Object, nil]
[ "Set", "values", "on", "a", "field", ";", "this", "will", "cast", "values", "from", "RDF", "types", "to", "persistable", "Mongoid", "types" ]
fdb17fbeb93e89c670f3ca5d431f29be0a682fd2
https://github.com/ladder/ladder/blob/fdb17fbeb93e89c670f3ca5d431f29be0a682fd2/lib/ladder/resource.rb#L115-L133
train
ladder/ladder
lib/ladder/resource.rb
Ladder.Resource.cast_value
def cast_value(value, opts = {}) case value when Array value.map { |v| cast_value(v, opts) } when String cast_uri = RDF::URI.new(value) cast_uri.valid? ? cast_uri : RDF::Literal.new(value, opts) when Time # Cast DateTimes with 00:00:00 or Date stored as Times in Mongoid to xsd:date # FIXME: this should NOT be applied for fields that are typed as Time value.midnight == value ? RDF::Literal.new(value.to_date) : RDF::Literal.new(value.to_datetime) else RDF::Literal.new(value, opts) end end
ruby
def cast_value(value, opts = {}) case value when Array value.map { |v| cast_value(v, opts) } when String cast_uri = RDF::URI.new(value) cast_uri.valid? ? cast_uri : RDF::Literal.new(value, opts) when Time # Cast DateTimes with 00:00:00 or Date stored as Times in Mongoid to xsd:date # FIXME: this should NOT be applied for fields that are typed as Time value.midnight == value ? RDF::Literal.new(value.to_date) : RDF::Literal.new(value.to_datetime) else RDF::Literal.new(value, opts) end end
[ "def", "cast_value", "(", "value", ",", "opts", "=", "{", "}", ")", "case", "value", "when", "Array", "value", ".", "map", "{", "|", "v", "|", "cast_value", "(", "v", ",", "opts", ")", "}", "when", "String", "cast_uri", "=", "RDF", "::", "URI", ".", "new", "(", "value", ")", "cast_uri", ".", "valid?", "?", "cast_uri", ":", "RDF", "::", "Literal", ".", "new", "(", "value", ",", "opts", ")", "when", "Time", "value", ".", "midnight", "==", "value", "?", "RDF", "::", "Literal", ".", "new", "(", "value", ".", "to_date", ")", ":", "RDF", "::", "Literal", ".", "new", "(", "value", ".", "to_datetime", ")", "else", "RDF", "::", "Literal", ".", "new", "(", "value", ",", "opts", ")", "end", "end" ]
Cast values from Mongoid types to RDF types @param [Object] value ActiveModel attribute to be cast @param [Hash] opts options to pass to RDF::Literal @return [RDF::Term]
[ "Cast", "values", "from", "Mongoid", "types", "to", "RDF", "types" ]
fdb17fbeb93e89c670f3ca5d431f29be0a682fd2
https://github.com/ladder/ladder/blob/fdb17fbeb93e89c670f3ca5d431f29be0a682fd2/lib/ladder/resource.rb#L141-L155
train
ladder/ladder
lib/ladder/file.rb
Ladder.File.data
def data @grid_file ||= self.class.grid.get(id) if persisted? return @grid_file.data if @grid_file file.rewind if file.respond_to? :rewind file.read end
ruby
def data @grid_file ||= self.class.grid.get(id) if persisted? return @grid_file.data if @grid_file file.rewind if file.respond_to? :rewind file.read end
[ "def", "data", "@grid_file", "||=", "self", ".", "class", ".", "grid", ".", "get", "(", "id", ")", "if", "persisted?", "return", "@grid_file", ".", "data", "if", "@grid_file", "file", ".", "rewind", "if", "file", ".", "respond_to?", ":rewind", "file", ".", "read", "end" ]
Output content of object from stored file or readable input @return [String] string-encoded copy of binary data
[ "Output", "content", "of", "object", "from", "stored", "file", "or", "readable", "input" ]
fdb17fbeb93e89c670f3ca5d431f29be0a682fd2
https://github.com/ladder/ladder/blob/fdb17fbeb93e89c670f3ca5d431f29be0a682fd2/lib/ladder/file.rb#L41-L47
train
barkerest/incline
lib/incline/extensions/numeric.rb
Incline::Extensions.Numeric.to_human
def to_human Incline::Extensions::Numeric::SHORT_SCALE.each do |(num,label)| if self >= num # Add 0.0001 to the value before rounding it off. # This way we're telling the system that we want it to round up instead of round to even. s = ('%.2f' % ((self.to_f / num) + 0.0001)).gsub(/\.?0+\z/,'') return "#{s} #{label}" end end if self.is_a?(::Rational) if self.denominator == 1 return self.numerator.to_s end return self.to_s elsif self.is_a?(::Integer) return self.to_s end # Again we want to add the 0.0001 to the value before rounding. ('%.2f' % (self.to_f + 0.0001)).gsub(/\.?0+\z/,'') end
ruby
def to_human Incline::Extensions::Numeric::SHORT_SCALE.each do |(num,label)| if self >= num # Add 0.0001 to the value before rounding it off. # This way we're telling the system that we want it to round up instead of round to even. s = ('%.2f' % ((self.to_f / num) + 0.0001)).gsub(/\.?0+\z/,'') return "#{s} #{label}" end end if self.is_a?(::Rational) if self.denominator == 1 return self.numerator.to_s end return self.to_s elsif self.is_a?(::Integer) return self.to_s end # Again we want to add the 0.0001 to the value before rounding. ('%.2f' % (self.to_f + 0.0001)).gsub(/\.?0+\z/,'') end
[ "def", "to_human", "Incline", "::", "Extensions", "::", "Numeric", "::", "SHORT_SCALE", ".", "each", "do", "|", "(", "num", ",", "label", ")", "|", "if", "self", ">=", "num", "s", "=", "(", "'%.2f'", "%", "(", "(", "self", ".", "to_f", "/", "num", ")", "+", "0.0001", ")", ")", ".", "gsub", "(", "/", "\\.", "\\z", "/", ",", "''", ")", "return", "\"#{s} #{label}\"", "end", "end", "if", "self", ".", "is_a?", "(", "::", "Rational", ")", "if", "self", ".", "denominator", "==", "1", "return", "self", ".", "numerator", ".", "to_s", "end", "return", "self", ".", "to_s", "elsif", "self", ".", "is_a?", "(", "::", "Integer", ")", "return", "self", ".", "to_s", "end", "(", "'%.2f'", "%", "(", "self", ".", "to_f", "+", "0.0001", ")", ")", ".", "gsub", "(", "/", "\\.", "\\z", "/", ",", "''", ")", "end" ]
Formats the number using the short scale for any number over 1 million.
[ "Formats", "the", "number", "using", "the", "short", "scale", "for", "any", "number", "over", "1", "million", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/numeric.rb#L29-L50
train
tbpgr/sublime_sunippetter
lib/sublime_sunippetter.rb
SublimeSunippetter.Core.generate_sunippets
def generate_sunippets sunippet_define = read_sunippetdefine dsl = Dsl.new dsl.instance_eval sunippet_define output_methods(dsl) output_requires(dsl) end
ruby
def generate_sunippets sunippet_define = read_sunippetdefine dsl = Dsl.new dsl.instance_eval sunippet_define output_methods(dsl) output_requires(dsl) end
[ "def", "generate_sunippets", "sunippet_define", "=", "read_sunippetdefine", "dsl", "=", "Dsl", ".", "new", "dsl", ".", "instance_eval", "sunippet_define", "output_methods", "(", "dsl", ")", "output_requires", "(", "dsl", ")", "end" ]
generate sublime text2 sunippets from Sunippetdefine
[ "generate", "sublime", "text2", "sunippets", "from", "Sunippetdefine" ]
a731a8a52fe457d742e78f50a4009b5b01f0640d
https://github.com/tbpgr/sublime_sunippetter/blob/a731a8a52fe457d742e78f50a4009b5b01f0640d/lib/sublime_sunippetter.rb#L21-L27
train
andreimaxim/active_metrics
lib/active_metrics/instrumentable.rb
ActiveMetrics.Instrumentable.count
def count(event, number = 1) ActiveMetrics::Collector.record(event, { metric: 'count', value: number }) end
ruby
def count(event, number = 1) ActiveMetrics::Collector.record(event, { metric: 'count', value: number }) end
[ "def", "count", "(", "event", ",", "number", "=", "1", ")", "ActiveMetrics", "::", "Collector", ".", "record", "(", "event", ",", "{", "metric", ":", "'count'", ",", "value", ":", "number", "}", ")", "end" ]
Count log lines are used to submit increments to Librato. You can submit increments as frequently as desired and every minute the current total will be flushed to Librato and reset to zero. @param event [String] The name of the event @param number [Integer] The number to increment the current count (defaults to 1)
[ "Count", "log", "lines", "are", "used", "to", "submit", "increments", "to", "Librato", "." ]
b8ee011e9dccd88bb73f6cd52625106ac8ea5ff8
https://github.com/andreimaxim/active_metrics/blob/b8ee011e9dccd88bb73f6cd52625106ac8ea5ff8/lib/active_metrics/instrumentable.rb#L13-L15
train
andreimaxim/active_metrics
lib/active_metrics/instrumentable.rb
ActiveMetrics.Instrumentable.measure
def measure(event, value = 0) if block_given? time = Time.now # Store the value returned by the block for future reference value = yield delta = Time.now - time ActiveMetrics::Collector.record(event, { metric: 'measure', value: delta }) value else ActiveMetrics::Collector.record(event, { metric: 'measure', value: value }) end end
ruby
def measure(event, value = 0) if block_given? time = Time.now # Store the value returned by the block for future reference value = yield delta = Time.now - time ActiveMetrics::Collector.record(event, { metric: 'measure', value: delta }) value else ActiveMetrics::Collector.record(event, { metric: 'measure', value: value }) end end
[ "def", "measure", "(", "event", ",", "value", "=", "0", ")", "if", "block_given?", "time", "=", "Time", ".", "now", "value", "=", "yield", "delta", "=", "Time", ".", "now", "-", "time", "ActiveMetrics", "::", "Collector", ".", "record", "(", "event", ",", "{", "metric", ":", "'measure'", ",", "value", ":", "delta", "}", ")", "value", "else", "ActiveMetrics", "::", "Collector", ".", "record", "(", "event", ",", "{", "metric", ":", "'measure'", ",", "value", ":", "value", "}", ")", "end", "end" ]
Measure log lines are used to submit individual measurements that comprise a statistical distribution. The most common use case are timings i.e. latency measurements, but it can also be used to represent non-temporal distributions such as counts. You can submit as many measures as you’d like (typically they are submitted per-request) and every minute Librato will calculate/record a complete set of summary statistics over the measures submitted in that interval. The `measure` method also accepts a block of code which will automatically measure the amount of time spent running that block: measure 'foo.bar.baz' do Foo.bar #=> 'baz' end For convenience, when `measure` is used with a block it will return the value returned by the block. @param event [String] The name of the event @param value [Integer, String] The value measured.
[ "Measure", "log", "lines", "are", "used", "to", "submit", "individual", "measurements", "that", "comprise", "a", "statistical", "distribution", ".", "The", "most", "common", "use", "case", "are", "timings", "i", ".", "e", ".", "latency", "measurements", "but", "it", "can", "also", "be", "used", "to", "represent", "non", "-", "temporal", "distributions", "such", "as", "counts", "." ]
b8ee011e9dccd88bb73f6cd52625106ac8ea5ff8
https://github.com/andreimaxim/active_metrics/blob/b8ee011e9dccd88bb73f6cd52625106ac8ea5ff8/lib/active_metrics/instrumentable.rb#L39-L52
train
robfors/ruby-sumac
lib/sumac/connection.rb
Sumac.Connection.messenger_received_message
def messenger_received_message(message_string) #puts "receive|#{message_string}" begin message = Messages.from_json(message_string) rescue ProtocolError @scheduler.receive(:invalid_message) return end case message when Messages::CallRequest then @scheduler.receive(:call_request_message, message) when Messages::CallResponse then @scheduler.receive(:call_response_message, message) when Messages::Compatibility then @scheduler.receive(:compatibility_message, message) when Messages::Forget then @scheduler.receive(:forget_message, message) when Messages::Initialization then @scheduler.receive(:initialization_message, message) when Messages::Shutdown then @scheduler.receive(:shutdown_message) end end
ruby
def messenger_received_message(message_string) #puts "receive|#{message_string}" begin message = Messages.from_json(message_string) rescue ProtocolError @scheduler.receive(:invalid_message) return end case message when Messages::CallRequest then @scheduler.receive(:call_request_message, message) when Messages::CallResponse then @scheduler.receive(:call_response_message, message) when Messages::Compatibility then @scheduler.receive(:compatibility_message, message) when Messages::Forget then @scheduler.receive(:forget_message, message) when Messages::Initialization then @scheduler.receive(:initialization_message, message) when Messages::Shutdown then @scheduler.receive(:shutdown_message) end end
[ "def", "messenger_received_message", "(", "message_string", ")", "begin", "message", "=", "Messages", ".", "from_json", "(", "message_string", ")", "rescue", "ProtocolError", "@scheduler", ".", "receive", "(", ":invalid_message", ")", "return", "end", "case", "message", "when", "Messages", "::", "CallRequest", "then", "@scheduler", ".", "receive", "(", ":call_request_message", ",", "message", ")", "when", "Messages", "::", "CallResponse", "then", "@scheduler", ".", "receive", "(", ":call_response_message", ",", "message", ")", "when", "Messages", "::", "Compatibility", "then", "@scheduler", ".", "receive", "(", ":compatibility_message", ",", "message", ")", "when", "Messages", "::", "Forget", "then", "@scheduler", ".", "receive", "(", ":forget_message", ",", "message", ")", "when", "Messages", "::", "Initialization", "then", "@scheduler", ".", "receive", "(", ":initialization_message", ",", "message", ")", "when", "Messages", "::", "Shutdown", "then", "@scheduler", ".", "receive", "(", ":shutdown_message", ")", "end", "end" ]
Submit a message from the messenger. The thread will wait its turn if another event is being processed. @param message_string [String] @return [void]
[ "Submit", "a", "message", "from", "the", "messenger", ".", "The", "thread", "will", "wait", "its", "turn", "if", "another", "event", "is", "being", "processed", "." ]
524fa68b7d1bb10a74baa69cd594ab2b8cae20a3
https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/connection.rb#L181-L197
train
MOZGIII/win-path-utils
lib/win-path-utils.rb
WinPathUtils.Path.add
def add(value, options = {}) # Set defaults options[:duplication_filter] = :do_not_add unless options.key?(:duplication_filter) # Get path path = get_array # Check duplicates if path.member?(value) case options[:duplication_filter] when :do_not_add, :deny # do nothing, we already have one in the list return when :remove_existing path.delete!(value) when :none # just pass through else raise WrongOptionError, "Unknown :duplication_filter!" end end # Change path array case options[:where] when :start, :left path.unshift value when :end, :right path.push value else raise WrongOptionError, "Unknown :where!" end # Save new array set_array(path) end
ruby
def add(value, options = {}) # Set defaults options[:duplication_filter] = :do_not_add unless options.key?(:duplication_filter) # Get path path = get_array # Check duplicates if path.member?(value) case options[:duplication_filter] when :do_not_add, :deny # do nothing, we already have one in the list return when :remove_existing path.delete!(value) when :none # just pass through else raise WrongOptionError, "Unknown :duplication_filter!" end end # Change path array case options[:where] when :start, :left path.unshift value when :end, :right path.push value else raise WrongOptionError, "Unknown :where!" end # Save new array set_array(path) end
[ "def", "add", "(", "value", ",", "options", "=", "{", "}", ")", "options", "[", ":duplication_filter", "]", "=", ":do_not_add", "unless", "options", ".", "key?", "(", ":duplication_filter", ")", "path", "=", "get_array", "if", "path", ".", "member?", "(", "value", ")", "case", "options", "[", ":duplication_filter", "]", "when", ":do_not_add", ",", ":deny", "return", "when", ":remove_existing", "path", ".", "delete!", "(", "value", ")", "when", ":none", "else", "raise", "WrongOptionError", ",", "\"Unknown :duplication_filter!\"", "end", "end", "case", "options", "[", ":where", "]", "when", ":start", ",", ":left", "path", ".", "unshift", "value", "when", ":end", ",", ":right", "path", ".", "push", "value", "else", "raise", "WrongOptionError", ",", "\"Unknown :where!\"", "end", "set_array", "(", "path", ")", "end" ]
Adds value to the path
[ "Adds", "value", "to", "the", "path" ]
7f12c8f68250bf9e09c7a826e44632fb66f43426
https://github.com/MOZGIII/win-path-utils/blob/7f12c8f68250bf9e09c7a826e44632fb66f43426/lib/win-path-utils.rb#L60-L94
train
MOZGIII/win-path-utils
lib/win-path-utils.rb
WinPathUtils.Path.with_reg
def with_reg(access_mask = Win32::Registry::Constants::KEY_ALL_ACCESS, &block) @hkey.open(@reg_path, access_mask, &block) end
ruby
def with_reg(access_mask = Win32::Registry::Constants::KEY_ALL_ACCESS, &block) @hkey.open(@reg_path, access_mask, &block) end
[ "def", "with_reg", "(", "access_mask", "=", "Win32", "::", "Registry", "::", "Constants", "::", "KEY_ALL_ACCESS", ",", "&", "block", ")", "@hkey", ".", "open", "(", "@reg_path", ",", "access_mask", ",", "&", "block", ")", "end" ]
Execute block with the current reg settings
[ "Execute", "block", "with", "the", "current", "reg", "settings" ]
7f12c8f68250bf9e09c7a826e44632fb66f43426
https://github.com/MOZGIII/win-path-utils/blob/7f12c8f68250bf9e09c7a826e44632fb66f43426/lib/win-path-utils.rb#L144-L146
train
phildionne/associates
lib/associates/validations.rb
Associates.Validations.valid_with_associates?
def valid_with_associates?(context = nil) # Model validations valid_without_associates?(context) # Associated models validations self.class.associates.each do |associate| model = send(associate.name) model.valid?(context) model.errors.each_entry do |attribute, message| # Do not include association presence validation errors if associate.dependent_names.include?(attribute.to_s) next elsif respond_to?(attribute) errors.add(attribute, message) else errors.add(:base, model.errors.full_messages_for(attribute)) end end end errors.messages.values.each(&:uniq!) errors.none? end
ruby
def valid_with_associates?(context = nil) # Model validations valid_without_associates?(context) # Associated models validations self.class.associates.each do |associate| model = send(associate.name) model.valid?(context) model.errors.each_entry do |attribute, message| # Do not include association presence validation errors if associate.dependent_names.include?(attribute.to_s) next elsif respond_to?(attribute) errors.add(attribute, message) else errors.add(:base, model.errors.full_messages_for(attribute)) end end end errors.messages.values.each(&:uniq!) errors.none? end
[ "def", "valid_with_associates?", "(", "context", "=", "nil", ")", "valid_without_associates?", "(", "context", ")", "self", ".", "class", ".", "associates", ".", "each", "do", "|", "associate", "|", "model", "=", "send", "(", "associate", ".", "name", ")", "model", ".", "valid?", "(", "context", ")", "model", ".", "errors", ".", "each_entry", "do", "|", "attribute", ",", "message", "|", "if", "associate", ".", "dependent_names", ".", "include?", "(", "attribute", ".", "to_s", ")", "next", "elsif", "respond_to?", "(", "attribute", ")", "errors", ".", "add", "(", "attribute", ",", "message", ")", "else", "errors", ".", "add", "(", ":base", ",", "model", ".", "errors", ".", "full_messages_for", "(", "attribute", ")", ")", "end", "end", "end", "errors", ".", "messages", ".", "values", ".", "each", "(", "&", ":uniq!", ")", "errors", ".", "none?", "end" ]
Runs the model validations plus the associated models validations and merges each messages in the errors hash @return [Boolean]
[ "Runs", "the", "model", "validations", "plus", "the", "associated", "models", "validations", "and", "merges", "each", "messages", "in", "the", "errors", "hash" ]
630edcc47340a73ad787feaf2cdf326b4487bb9f
https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates/validations.rb#L16-L39
train
aetherised/ark-util
lib/ark/log.rb
ARK.Log.say
def say(msg, sym='...', loud=false, indent=0) return false if Conf[:quiet] return false if loud && !Conf[:verbose] unless msg == '' time = "" if Conf[:timed] time = Timer.time.to_s.ljust(4, '0') time = time + " " end indent = " " * indent indent = " " if indent == "" puts "#{time}#{sym}#{indent}#{msg}" else puts end end
ruby
def say(msg, sym='...', loud=false, indent=0) return false if Conf[:quiet] return false if loud && !Conf[:verbose] unless msg == '' time = "" if Conf[:timed] time = Timer.time.to_s.ljust(4, '0') time = time + " " end indent = " " * indent indent = " " if indent == "" puts "#{time}#{sym}#{indent}#{msg}" else puts end end
[ "def", "say", "(", "msg", ",", "sym", "=", "'...'", ",", "loud", "=", "false", ",", "indent", "=", "0", ")", "return", "false", "if", "Conf", "[", ":quiet", "]", "return", "false", "if", "loud", "&&", "!", "Conf", "[", ":verbose", "]", "unless", "msg", "==", "''", "time", "=", "\"\"", "if", "Conf", "[", ":timed", "]", "time", "=", "Timer", ".", "time", ".", "to_s", ".", "ljust", "(", "4", ",", "'0'", ")", "time", "=", "time", "+", "\" \"", "end", "indent", "=", "\" \"", "*", "indent", "indent", "=", "\" \"", "if", "indent", "==", "\"\"", "puts", "\"#{time}#{sym}#{indent}#{msg}\"", "else", "puts", "end", "end" ]
Write +msg+ to standard output according to verbosity settings. Not meant to be used directly
[ "Write", "+", "msg", "+", "to", "standard", "output", "according", "to", "verbosity", "settings", ".", "Not", "meant", "to", "be", "used", "directly" ]
d7573ad0e44568a394808dfa895b9375de1bc3fd
https://github.com/aetherised/ark-util/blob/d7573ad0e44568a394808dfa895b9375de1bc3fd/lib/ark/log.rb#L18-L33
train
madwire/trooper
lib/trooper/configuration.rb
Trooper.Configuration.load_troopfile!
def load_troopfile!(options) if troopfile? eval troopfile.read @loaded = true load_environment! set options else raise Trooper::NoConfigurationFileError, "No Configuration file (#{self[:file_name]}) can be found!" end end
ruby
def load_troopfile!(options) if troopfile? eval troopfile.read @loaded = true load_environment! set options else raise Trooper::NoConfigurationFileError, "No Configuration file (#{self[:file_name]}) can be found!" end end
[ "def", "load_troopfile!", "(", "options", ")", "if", "troopfile?", "eval", "troopfile", ".", "read", "@loaded", "=", "true", "load_environment!", "set", "options", "else", "raise", "Trooper", "::", "NoConfigurationFileError", ",", "\"No Configuration file (#{self[:file_name]}) can be found!\"", "end", "end" ]
loads the troopfile and sets the environment up
[ "loads", "the", "troopfile", "and", "sets", "the", "environment", "up" ]
ca953f9b78adf1614f7acf82c9076055540ee04c
https://github.com/madwire/trooper/blob/ca953f9b78adf1614f7acf82c9076055540ee04c/lib/trooper/configuration.rb#L127-L137
train
cknadler/rcomp
lib/rcomp/suite.rb
RComp.Suite.load
def load(pattern=nil) tests = [] # Find all tests in the tests directory Find.find @@conf.test_root do |path| # recurse into all subdirectories next if File.directory? path # filter tests by pattern if present if pattern next unless rel_path(path).match(pattern) end # ignore dotfiles next if File.basename(path).match(/^\..*/) # ignore files in ignore filter next if ignored?(path) tests << Test.new(path) end return tests end
ruby
def load(pattern=nil) tests = [] # Find all tests in the tests directory Find.find @@conf.test_root do |path| # recurse into all subdirectories next if File.directory? path # filter tests by pattern if present if pattern next unless rel_path(path).match(pattern) end # ignore dotfiles next if File.basename(path).match(/^\..*/) # ignore files in ignore filter next if ignored?(path) tests << Test.new(path) end return tests end
[ "def", "load", "(", "pattern", "=", "nil", ")", "tests", "=", "[", "]", "Find", ".", "find", "@@conf", ".", "test_root", "do", "|", "path", "|", "next", "if", "File", ".", "directory?", "path", "if", "pattern", "next", "unless", "rel_path", "(", "path", ")", ".", "match", "(", "pattern", ")", "end", "next", "if", "File", ".", "basename", "(", "path", ")", ".", "match", "(", "/", "\\.", "/", ")", "next", "if", "ignored?", "(", "path", ")", "tests", "<<", "Test", ".", "new", "(", "path", ")", "end", "return", "tests", "end" ]
Create a test suite pattern - A pattern to filter the tests that are added to the suite Returns an Array of Test objects
[ "Create", "a", "test", "suite" ]
76fe71e1ef3b13923738ea6ab9cd502fe2f64f51
https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/suite.rb#L16-L39
train
cknadler/rcomp
lib/rcomp/suite.rb
RComp.Suite.ignored?
def ignored?(path) @@conf.ignore.each do |ignore| return true if rel_path(path).match(ignore) end return false end
ruby
def ignored?(path) @@conf.ignore.each do |ignore| return true if rel_path(path).match(ignore) end return false end
[ "def", "ignored?", "(", "path", ")", "@@conf", ".", "ignore", ".", "each", "do", "|", "ignore", "|", "return", "true", "if", "rel_path", "(", "path", ")", ".", "match", "(", "ignore", ")", "end", "return", "false", "end" ]
Checks all ignore patterns against a given relative path path - A relative path of a test Returns true if any patterns match the path, false otherwise
[ "Checks", "all", "ignore", "patterns", "against", "a", "given", "relative", "path" ]
76fe71e1ef3b13923738ea6ab9cd502fe2f64f51
https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/suite.rb#L48-L53
train
wedesoft/multiarray
lib/multiarray/malloc.rb
Hornetseye.Malloc.save
def save( value ) write value.values.pack( value.typecode.directive ) value end
ruby
def save( value ) write value.values.pack( value.typecode.directive ) value end
[ "def", "save", "(", "value", ")", "write", "value", ".", "values", ".", "pack", "(", "value", ".", "typecode", ".", "directive", ")", "value", "end" ]
Write typed value to memory @param [Node] value Value to write to memory. @return [Node] Returns +value+.
[ "Write", "typed", "value", "to", "memory" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/malloc.rb#L39-L42
train
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/themes_controller.rb
Roroacms.Admin::ThemesController.create
def create # the theme used is set in the settings area - this does the update of the current theme used Setting.where("setting_name = 'theme_folder'").update_all('setting' => params[:theme]) Setting.reload_settings respond_to do |format| format.html { redirect_to admin_themes_path, notice: I18n.t("controllers.admin.themes.create.flash.success") } end end
ruby
def create # the theme used is set in the settings area - this does the update of the current theme used Setting.where("setting_name = 'theme_folder'").update_all('setting' => params[:theme]) Setting.reload_settings respond_to do |format| format.html { redirect_to admin_themes_path, notice: I18n.t("controllers.admin.themes.create.flash.success") } end end
[ "def", "create", "Setting", ".", "where", "(", "\"setting_name = 'theme_folder'\"", ")", ".", "update_all", "(", "'setting'", "=>", "params", "[", ":theme", "]", ")", "Setting", ".", "reload_settings", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "redirect_to", "admin_themes_path", ",", "notice", ":", "I18n", ".", "t", "(", "\"controllers.admin.themes.create.flash.success\"", ")", "}", "end", "end" ]
update the currently used theme
[ "update", "the", "currently", "used", "theme" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/themes_controller.rb#L23-L30
train
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/themes_controller.rb
Roroacms.Admin::ThemesController.destroy
def destroy # remove the directory from the directory structure destory_theme params[:id] respond_to do |format| format.html { redirect_to admin_themes_path, notice: I18n.t("controllers.admin.themes.destroy.flash.success") } end end
ruby
def destroy # remove the directory from the directory structure destory_theme params[:id] respond_to do |format| format.html { redirect_to admin_themes_path, notice: I18n.t("controllers.admin.themes.destroy.flash.success") } end end
[ "def", "destroy", "destory_theme", "params", "[", ":id", "]", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "redirect_to", "admin_themes_path", ",", "notice", ":", "I18n", ".", "t", "(", "\"controllers.admin.themes.destroy.flash.success\"", ")", "}", "end", "end" ]
remove the theme from the theme folder stopping any future usage.
[ "remove", "the", "theme", "from", "the", "theme", "folder", "stopping", "any", "future", "usage", "." ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/themes_controller.rb#L35-L42
train
tomash/blasphemy
lib/blasphemy.rb
Faker.CustomIpsum.sentence
def sentence # Determine the number of comma-separated sections and number of words in # each section for this sentence. sections = [] 1.upto(rand(5)+1) do sections << (words(rand(9)+3).join(" ")) end s = sections.join(", ") return s.capitalize + ".?!".slice(rand(3),1) end
ruby
def sentence # Determine the number of comma-separated sections and number of words in # each section for this sentence. sections = [] 1.upto(rand(5)+1) do sections << (words(rand(9)+3).join(" ")) end s = sections.join(", ") return s.capitalize + ".?!".slice(rand(3),1) end
[ "def", "sentence", "sections", "=", "[", "]", "1", ".", "upto", "(", "rand", "(", "5", ")", "+", "1", ")", "do", "sections", "<<", "(", "words", "(", "rand", "(", "9", ")", "+", "3", ")", ".", "join", "(", "\" \"", ")", ")", "end", "s", "=", "sections", ".", "join", "(", "\", \"", ")", "return", "s", ".", "capitalize", "+", "\".?!\"", ".", "slice", "(", "rand", "(", "3", ")", ",", "1", ")", "end" ]
Returns a randomly generated sentence of lorem ipsum text. The first word is capitalized, and the sentence ends in either a period or question mark. Commas are added at random.
[ "Returns", "a", "randomly", "generated", "sentence", "of", "lorem", "ipsum", "text", ".", "The", "first", "word", "is", "capitalized", "and", "the", "sentence", "ends", "in", "either", "a", "period", "or", "question", "mark", ".", "Commas", "are", "added", "at", "random", "." ]
00ba52fe24ec670df3dc45aaad0f99323fa362b4
https://github.com/tomash/blasphemy/blob/00ba52fe24ec670df3dc45aaad0f99323fa362b4/lib/blasphemy.rb#L17-L26
train
codescrum/bebox
lib/bebox/wizards/project_wizard.rb
Bebox.ProjectWizard.create_new_project
def create_new_project(project_name) # Check project existence (error(_('wizard.project.name_exist')); return false) if project_exists?(Dir.pwd, project_name) # Setup the bebox boxes directory bebox_boxes_setup # Asks to choose an existing box current_box = choose_box(get_existing_boxes) vagrant_box_base = "#{BEBOX_BOXES_PATH}/#{get_valid_box_uri(current_box)}" # Asks user to choose vagrant box provider vagrant_box_provider = choose_option(%w{virtualbox vmware}, _('wizard.project.choose_box_provider')) # Set default environments default_environments = %w{vagrant staging production} # Project creation project = Bebox::Project.new(project_name, vagrant_box_base, Dir.pwd, vagrant_box_provider, default_environments) output = project.create ok _('wizard.project.creation_success')%{project_name: project_name} return output end
ruby
def create_new_project(project_name) # Check project existence (error(_('wizard.project.name_exist')); return false) if project_exists?(Dir.pwd, project_name) # Setup the bebox boxes directory bebox_boxes_setup # Asks to choose an existing box current_box = choose_box(get_existing_boxes) vagrant_box_base = "#{BEBOX_BOXES_PATH}/#{get_valid_box_uri(current_box)}" # Asks user to choose vagrant box provider vagrant_box_provider = choose_option(%w{virtualbox vmware}, _('wizard.project.choose_box_provider')) # Set default environments default_environments = %w{vagrant staging production} # Project creation project = Bebox::Project.new(project_name, vagrant_box_base, Dir.pwd, vagrant_box_provider, default_environments) output = project.create ok _('wizard.project.creation_success')%{project_name: project_name} return output end
[ "def", "create_new_project", "(", "project_name", ")", "(", "error", "(", "_", "(", "'wizard.project.name_exist'", ")", ")", ";", "return", "false", ")", "if", "project_exists?", "(", "Dir", ".", "pwd", ",", "project_name", ")", "bebox_boxes_setup", "current_box", "=", "choose_box", "(", "get_existing_boxes", ")", "vagrant_box_base", "=", "\"#{BEBOX_BOXES_PATH}/#{get_valid_box_uri(current_box)}\"", "vagrant_box_provider", "=", "choose_option", "(", "%w{", "virtualbox", "vmware", "}", ",", "_", "(", "'wizard.project.choose_box_provider'", ")", ")", "default_environments", "=", "%w{", "vagrant", "staging", "production", "}", "project", "=", "Bebox", "::", "Project", ".", "new", "(", "project_name", ",", "vagrant_box_base", ",", "Dir", ".", "pwd", ",", "vagrant_box_provider", ",", "default_environments", ")", "output", "=", "project", ".", "create", "ok", "_", "(", "'wizard.project.creation_success'", ")", "%", "{", "project_name", ":", "project_name", "}", "return", "output", "end" ]
Asks for the project parameters and create the project skeleton
[ "Asks", "for", "the", "project", "parameters", "and", "create", "the", "project", "skeleton" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/project_wizard.rb#L10-L27
train
codescrum/bebox
lib/bebox/wizards/project_wizard.rb
Bebox.ProjectWizard.uri_valid?
def uri_valid?(vbox_uri) require 'uri' uri = URI.parse(vbox_uri) %w{http https}.include?(uri.scheme) ? http_uri_valid?(uri) : file_uri_valid?(uri) end
ruby
def uri_valid?(vbox_uri) require 'uri' uri = URI.parse(vbox_uri) %w{http https}.include?(uri.scheme) ? http_uri_valid?(uri) : file_uri_valid?(uri) end
[ "def", "uri_valid?", "(", "vbox_uri", ")", "require", "'uri'", "uri", "=", "URI", ".", "parse", "(", "vbox_uri", ")", "%w{", "http", "https", "}", ".", "include?", "(", "uri", ".", "scheme", ")", "?", "http_uri_valid?", "(", "uri", ")", ":", "file_uri_valid?", "(", "uri", ")", "end" ]
Validate uri download or local box existence
[ "Validate", "uri", "download", "or", "local", "box", "existence" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/project_wizard.rb#L77-L81
train
codescrum/bebox
lib/bebox/wizards/project_wizard.rb
Bebox.ProjectWizard.get_existing_boxes
def get_existing_boxes # Converts the bebox boxes directory to an absolute pathname expanded_directory = File.expand_path("#{BEBOX_BOXES_PATH}") # Get an array of bebox boxes paths boxes = Dir["#{expanded_directory}/*"].reject {|f| File.directory? f} boxes.map{|box| box.split('/').last} end
ruby
def get_existing_boxes # Converts the bebox boxes directory to an absolute pathname expanded_directory = File.expand_path("#{BEBOX_BOXES_PATH}") # Get an array of bebox boxes paths boxes = Dir["#{expanded_directory}/*"].reject {|f| File.directory? f} boxes.map{|box| box.split('/').last} end
[ "def", "get_existing_boxes", "expanded_directory", "=", "File", ".", "expand_path", "(", "\"#{BEBOX_BOXES_PATH}\"", ")", "boxes", "=", "Dir", "[", "\"#{expanded_directory}/*\"", "]", ".", "reject", "{", "|", "f", "|", "File", ".", "directory?", "f", "}", "boxes", ".", "map", "{", "|", "box", "|", "box", ".", "split", "(", "'/'", ")", ".", "last", "}", "end" ]
Obtain the current boxes downloaded or linked in the bebox user home
[ "Obtain", "the", "current", "boxes", "downloaded", "or", "linked", "in", "the", "bebox", "user", "home" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/project_wizard.rb#L103-L109
train
codescrum/bebox
lib/bebox/wizards/project_wizard.rb
Bebox.ProjectWizard.choose_box
def choose_box(boxes) # Menu to choose vagrant box provider other_box_message = _('wizard.project.download_select_box') boxes << other_box_message current_box = choose_option(boxes, _('wizard.project.choose_box')) current_box = (current_box == other_box_message) ? nil : current_box end
ruby
def choose_box(boxes) # Menu to choose vagrant box provider other_box_message = _('wizard.project.download_select_box') boxes << other_box_message current_box = choose_option(boxes, _('wizard.project.choose_box')) current_box = (current_box == other_box_message) ? nil : current_box end
[ "def", "choose_box", "(", "boxes", ")", "other_box_message", "=", "_", "(", "'wizard.project.download_select_box'", ")", "boxes", "<<", "other_box_message", "current_box", "=", "choose_option", "(", "boxes", ",", "_", "(", "'wizard.project.choose_box'", ")", ")", "current_box", "=", "(", "current_box", "==", "other_box_message", ")", "?", "nil", ":", "current_box", "end" ]
Asks to choose an existing box in the bebox boxes directory
[ "Asks", "to", "choose", "an", "existing", "box", "in", "the", "bebox", "boxes", "directory" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/project_wizard.rb#L112-L118
train
codescrum/bebox
lib/bebox/wizards/project_wizard.rb
Bebox.ProjectWizard.download_box
def download_box(uri) require 'net/http' require 'uri' url = uri.path # Download file to bebox boxes tmp Net::HTTP.start(uri.host) do |http| response = http.request_head(URI.escape(url)) write_remote_file(uri, http, response) end end
ruby
def download_box(uri) require 'net/http' require 'uri' url = uri.path # Download file to bebox boxes tmp Net::HTTP.start(uri.host) do |http| response = http.request_head(URI.escape(url)) write_remote_file(uri, http, response) end end
[ "def", "download_box", "(", "uri", ")", "require", "'net/http'", "require", "'uri'", "url", "=", "uri", ".", "path", "Net", "::", "HTTP", ".", "start", "(", "uri", ".", "host", ")", "do", "|", "http", "|", "response", "=", "http", ".", "request_head", "(", "URI", ".", "escape", "(", "url", ")", ")", "write_remote_file", "(", "uri", ",", "http", ",", "response", ")", "end", "end" ]
Download a box by the specified uri
[ "Download", "a", "box", "by", "the", "specified", "uri" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/project_wizard.rb#L121-L130
train
riddopic/garcun
lib/garcon/task/executor.rb
Garcon.Executor.handle_fallback
def handle_fallback(*args) case @fallback_policy when :abort raise RejectedExecutionError when :discard false when :caller_runs begin yield(*args) rescue => e Chef::Log.debug "Caught exception => #{e}" end true else fail "Unknown fallback policy #{@fallback_policy}" end end
ruby
def handle_fallback(*args) case @fallback_policy when :abort raise RejectedExecutionError when :discard false when :caller_runs begin yield(*args) rescue => e Chef::Log.debug "Caught exception => #{e}" end true else fail "Unknown fallback policy #{@fallback_policy}" end end
[ "def", "handle_fallback", "(", "*", "args", ")", "case", "@fallback_policy", "when", ":abort", "raise", "RejectedExecutionError", "when", ":discard", "false", "when", ":caller_runs", "begin", "yield", "(", "*", "args", ")", "rescue", "=>", "e", "Chef", "::", "Log", ".", "debug", "\"Caught exception => #{e}\"", "end", "true", "else", "fail", "\"Unknown fallback policy #{@fallback_policy}\"", "end", "end" ]
Handler which executes the `fallback_policy` once the queue size reaches `max_queue`. @param [Array] args The arguments to the task which is being handled. @!visibility private
[ "Handler", "which", "executes", "the", "fallback_policy", "once", "the", "queue", "size", "reaches", "max_queue", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/executor.rb#L49-L65
train
riddopic/garcun
lib/garcon/task/executor.rb
Garcon.RubyExecutor.post
def post(*args, &task) raise ArgumentError.new('no block given') unless block_given? mutex.synchronize do # If the executor is shut down, reject this task return handle_fallback(*args, &task) unless running? execute(*args, &task) true end end
ruby
def post(*args, &task) raise ArgumentError.new('no block given') unless block_given? mutex.synchronize do # If the executor is shut down, reject this task return handle_fallback(*args, &task) unless running? execute(*args, &task) true end end
[ "def", "post", "(", "*", "args", ",", "&", "task", ")", "raise", "ArgumentError", ".", "new", "(", "'no block given'", ")", "unless", "block_given?", "mutex", ".", "synchronize", "do", "return", "handle_fallback", "(", "*", "args", ",", "&", "task", ")", "unless", "running?", "execute", "(", "*", "args", ",", "&", "task", ")", "true", "end", "end" ]
Submit a task to the executor for asynchronous processing. @param [Array] args Zero or more arguments to be passed to the task @yield the asynchronous task to perform @raise [ArgumentError] if no task is given @return [Boolean] True if the task is queued, false if the executor is not running.
[ "Submit", "a", "task", "to", "the", "executor", "for", "asynchronous", "processing", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/executor.rb#L155-L163
train
riddopic/garcun
lib/garcon/task/executor.rb
Garcon.RubyExecutor.kill
def kill mutex.synchronize do break if shutdown? stop_event.set kill_execution stopped_event.set end true end
ruby
def kill mutex.synchronize do break if shutdown? stop_event.set kill_execution stopped_event.set end true end
[ "def", "kill", "mutex", ".", "synchronize", "do", "break", "if", "shutdown?", "stop_event", ".", "set", "kill_execution", "stopped_event", ".", "set", "end", "true", "end" ]
Begin an immediate shutdown. In-progress tasks will be allowed to complete but enqueued tasks will be dismissed and no new tasks will be accepted. Has no additional effect if the thread pool is not running.
[ "Begin", "an", "immediate", "shutdown", ".", "In", "-", "progress", "tasks", "will", "be", "allowed", "to", "complete", "but", "enqueued", "tasks", "will", "be", "dismissed", "and", "no", "new", "tasks", "will", "be", "accepted", ".", "Has", "no", "additional", "effect", "if", "the", "thread", "pool", "is", "not", "running", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/executor.rb#L218-L226
train
GlobalNamesArchitecture/taxamatch_rb
lib/taxamatch_rb/base.rb
Taxamatch.Base.taxamatch
def taxamatch(str1, str2, return_boolean = true) preparsed_1 = @parser.parse(str1) preparsed_2 = @parser.parse(str2) match = taxamatch_preparsed(preparsed_1, preparsed_2) rescue nil return_boolean ? (!!match && match['match']) : match end
ruby
def taxamatch(str1, str2, return_boolean = true) preparsed_1 = @parser.parse(str1) preparsed_2 = @parser.parse(str2) match = taxamatch_preparsed(preparsed_1, preparsed_2) rescue nil return_boolean ? (!!match && match['match']) : match end
[ "def", "taxamatch", "(", "str1", ",", "str2", ",", "return_boolean", "=", "true", ")", "preparsed_1", "=", "@parser", ".", "parse", "(", "str1", ")", "preparsed_2", "=", "@parser", ".", "parse", "(", "str2", ")", "match", "=", "taxamatch_preparsed", "(", "preparsed_1", ",", "preparsed_2", ")", "rescue", "nil", "return_boolean", "?", "(", "!", "!", "match", "&&", "match", "[", "'match'", "]", ")", ":", "match", "end" ]
takes two scientific names and returns true if names match and false if they don't
[ "takes", "two", "scientific", "names", "and", "returns", "true", "if", "names", "match", "and", "false", "if", "they", "don", "t" ]
1feabf9a1ae78777d21005f4567d0c221c6ef2e1
https://github.com/GlobalNamesArchitecture/taxamatch_rb/blob/1feabf9a1ae78777d21005f4567d0c221c6ef2e1/lib/taxamatch_rb/base.rb#L10-L15
train
GlobalNamesArchitecture/taxamatch_rb
lib/taxamatch_rb/base.rb
Taxamatch.Base.taxamatch_preparsed
def taxamatch_preparsed(preparsed_1, preparsed_2) result = nil if preparsed_1[:uninomial] && preparsed_2[:uninomial] result = match_uninomial(preparsed_1, preparsed_2) end if preparsed_1[:genus] && preparsed_2[:genus] result = match_multinomial(preparsed_1, preparsed_2) end if result && result['match'] result['match'] = match_authors(preparsed_1, preparsed_2) == -1 ? false : true end return result end
ruby
def taxamatch_preparsed(preparsed_1, preparsed_2) result = nil if preparsed_1[:uninomial] && preparsed_2[:uninomial] result = match_uninomial(preparsed_1, preparsed_2) end if preparsed_1[:genus] && preparsed_2[:genus] result = match_multinomial(preparsed_1, preparsed_2) end if result && result['match'] result['match'] = match_authors(preparsed_1, preparsed_2) == -1 ? false : true end return result end
[ "def", "taxamatch_preparsed", "(", "preparsed_1", ",", "preparsed_2", ")", "result", "=", "nil", "if", "preparsed_1", "[", ":uninomial", "]", "&&", "preparsed_2", "[", ":uninomial", "]", "result", "=", "match_uninomial", "(", "preparsed_1", ",", "preparsed_2", ")", "end", "if", "preparsed_1", "[", ":genus", "]", "&&", "preparsed_2", "[", ":genus", "]", "result", "=", "match_multinomial", "(", "preparsed_1", ",", "preparsed_2", ")", "end", "if", "result", "&&", "result", "[", "'match'", "]", "result", "[", "'match'", "]", "=", "match_authors", "(", "preparsed_1", ",", "preparsed_2", ")", "==", "-", "1", "?", "false", ":", "true", "end", "return", "result", "end" ]
takes two hashes of parsed scientific names, analyses them and returns back this function is useful when species strings are preparsed.
[ "takes", "two", "hashes", "of", "parsed", "scientific", "names", "analyses", "them", "and", "returns", "back", "this", "function", "is", "useful", "when", "species", "strings", "are", "preparsed", "." ]
1feabf9a1ae78777d21005f4567d0c221c6ef2e1
https://github.com/GlobalNamesArchitecture/taxamatch_rb/blob/1feabf9a1ae78777d21005f4567d0c221c6ef2e1/lib/taxamatch_rb/base.rb#L19-L32
train
mrackwitz/CLIntegracon
lib/CLIntegracon/configuration.rb
CLIntegracon.Configuration.hook_into
def hook_into test_framework adapter = self.class.adapters[test_framework] raise ArgumentError.new "No adapter for test framework #{test_framework}" if adapter.nil? require adapter end
ruby
def hook_into test_framework adapter = self.class.adapters[test_framework] raise ArgumentError.new "No adapter for test framework #{test_framework}" if adapter.nil? require adapter end
[ "def", "hook_into", "test_framework", "adapter", "=", "self", ".", "class", ".", "adapters", "[", "test_framework", "]", "raise", "ArgumentError", ".", "new", "\"No adapter for test framework #{test_framework}\"", "if", "adapter", ".", "nil?", "require", "adapter", "end" ]
Hook this gem in a test framework by a supported adapter @param [Symbol] test_framework the test framework
[ "Hook", "this", "gem", "in", "a", "test", "framework", "by", "a", "supported", "adapter" ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/configuration.rb#L66-L70
train
Fluxx/gazette
lib/gazette/client.rb
Gazette.Client.parse_response_for
def parse_response_for(response) case response when Net::HTTPOK, Net::HTTPCreated then return Response::Success.new(response) when Net::HTTPForbidden then raise Response::InvalidCredentials when Net::HTTPInternalServerError then raise Response::ServerError else raise Response::UnknownError end end
ruby
def parse_response_for(response) case response when Net::HTTPOK, Net::HTTPCreated then return Response::Success.new(response) when Net::HTTPForbidden then raise Response::InvalidCredentials when Net::HTTPInternalServerError then raise Response::ServerError else raise Response::UnknownError end end
[ "def", "parse_response_for", "(", "response", ")", "case", "response", "when", "Net", "::", "HTTPOK", ",", "Net", "::", "HTTPCreated", "then", "return", "Response", "::", "Success", ".", "new", "(", "response", ")", "when", "Net", "::", "HTTPForbidden", "then", "raise", "Response", "::", "InvalidCredentials", "when", "Net", "::", "HTTPInternalServerError", "then", "raise", "Response", "::", "ServerError", "else", "raise", "Response", "::", "UnknownError", "end", "end" ]
Handles the response from Instapaper. @todo Put the raising logic in the Api class/module, then leave the response return to this method
[ "Handles", "the", "response", "from", "Instapaper", "." ]
02fa3aa46d2b39cfa4184d374842a91f7f8d9e17
https://github.com/Fluxx/gazette/blob/02fa3aa46d2b39cfa4184d374842a91f7f8d9e17/lib/gazette/client.rb#L72-L79
train
Fluxx/gazette
lib/gazette/client.rb
Gazette.Client.request
def request(method, params = {}) http = Net::HTTP.new(Api::ADDRESS, (@https ? 443 : 80)) http.use_ssl = @https http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(Api::ENDPOINT+method.to_s) request.basic_auth @username, @password request.set_form_data(params) http.start { http.request(request) } end
ruby
def request(method, params = {}) http = Net::HTTP.new(Api::ADDRESS, (@https ? 443 : 80)) http.use_ssl = @https http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(Api::ENDPOINT+method.to_s) request.basic_auth @username, @password request.set_form_data(params) http.start { http.request(request) } end
[ "def", "request", "(", "method", ",", "params", "=", "{", "}", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "Api", "::", "ADDRESS", ",", "(", "@https", "?", "443", ":", "80", ")", ")", "http", ".", "use_ssl", "=", "@https", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "Api", "::", "ENDPOINT", "+", "method", ".", "to_s", ")", "request", ".", "basic_auth", "@username", ",", "@password", "request", ".", "set_form_data", "(", "params", ")", "http", ".", "start", "{", "http", ".", "request", "(", "request", ")", "}", "end" ]
Actually heads out to the internet and performs the request @todo Perhaps put me in the Api class/module?
[ "Actually", "heads", "out", "to", "the", "internet", "and", "performs", "the", "request" ]
02fa3aa46d2b39cfa4184d374842a91f7f8d9e17
https://github.com/Fluxx/gazette/blob/02fa3aa46d2b39cfa4184d374842a91f7f8d9e17/lib/gazette/client.rb#L83-L91
train
sanichi/icu_ratings
lib/icu_ratings/tournament.rb
ICU.RatedTournament.rate!
def rate!(opt={}) # The original algorithm (version 0). max_iterations = [30, 1] phase_2_bonuses = true update_bonuses = false threshold = 0.5 # New versions of the algorithm. version = opt[:version].to_i if version >= 1 # See http://ratings.icu.ie/articles/18 (Part 1) max_iterations[1] = 30 end if version >= 2 # See http://ratings.icu.ie/articles/18 (Part 2) phase_2_bonuses = false update_bonuses = true threshold = 0.1 end if version >= 3 # See http://ratings.icu.ie/articles/18 (Part 3) max_iterations = [50, 50] end # Phase 1. players.each { |p| p.reset } @iterations1 = performance_ratings(max_iterations[0], threshold) players.each { |p| p.rate! } # Phase 2. if !no_bonuses && calculate_bonuses > 0 players.each { |p| p.rate!(update_bonuses) } @iterations2 = performance_ratings(max_iterations[1], threshold) calculate_bonuses if phase_2_bonuses else @iterations2 = 0 end end
ruby
def rate!(opt={}) # The original algorithm (version 0). max_iterations = [30, 1] phase_2_bonuses = true update_bonuses = false threshold = 0.5 # New versions of the algorithm. version = opt[:version].to_i if version >= 1 # See http://ratings.icu.ie/articles/18 (Part 1) max_iterations[1] = 30 end if version >= 2 # See http://ratings.icu.ie/articles/18 (Part 2) phase_2_bonuses = false update_bonuses = true threshold = 0.1 end if version >= 3 # See http://ratings.icu.ie/articles/18 (Part 3) max_iterations = [50, 50] end # Phase 1. players.each { |p| p.reset } @iterations1 = performance_ratings(max_iterations[0], threshold) players.each { |p| p.rate! } # Phase 2. if !no_bonuses && calculate_bonuses > 0 players.each { |p| p.rate!(update_bonuses) } @iterations2 = performance_ratings(max_iterations[1], threshold) calculate_bonuses if phase_2_bonuses else @iterations2 = 0 end end
[ "def", "rate!", "(", "opt", "=", "{", "}", ")", "max_iterations", "=", "[", "30", ",", "1", "]", "phase_2_bonuses", "=", "true", "update_bonuses", "=", "false", "threshold", "=", "0.5", "version", "=", "opt", "[", ":version", "]", ".", "to_i", "if", "version", ">=", "1", "max_iterations", "[", "1", "]", "=", "30", "end", "if", "version", ">=", "2", "phase_2_bonuses", "=", "false", "update_bonuses", "=", "true", "threshold", "=", "0.1", "end", "if", "version", ">=", "3", "max_iterations", "=", "[", "50", ",", "50", "]", "end", "players", ".", "each", "{", "|", "p", "|", "p", ".", "reset", "}", "@iterations1", "=", "performance_ratings", "(", "max_iterations", "[", "0", "]", ",", "threshold", ")", "players", ".", "each", "{", "|", "p", "|", "p", ".", "rate!", "}", "if", "!", "no_bonuses", "&&", "calculate_bonuses", ">", "0", "players", ".", "each", "{", "|", "p", "|", "p", ".", "rate!", "(", "update_bonuses", ")", "}", "@iterations2", "=", "performance_ratings", "(", "max_iterations", "[", "1", "]", ",", "threshold", ")", "calculate_bonuses", "if", "phase_2_bonuses", "else", "@iterations2", "=", "0", "end", "end" ]
Rate the tournament. Called after all players and results have been added.
[ "Rate", "the", "tournament", ".", "Called", "after", "all", "players", "and", "results", "have", "been", "added", "." ]
edcb1bb903f123101fbc25d16192c4524a7112da
https://github.com/sanichi/icu_ratings/blob/edcb1bb903f123101fbc25d16192c4524a7112da/lib/icu_ratings/tournament.rb#L108-L145
train
sanichi/icu_ratings
lib/icu_ratings/tournament.rb
ICU.RatedTournament.calculate_bonuses
def calculate_bonuses @player.values.select{ |p| p.respond_to?(:bonus) }.inject(0) { |t,p| t + (p.calculate_bonus ? 1 : 0) } end
ruby
def calculate_bonuses @player.values.select{ |p| p.respond_to?(:bonus) }.inject(0) { |t,p| t + (p.calculate_bonus ? 1 : 0) } end
[ "def", "calculate_bonuses", "@player", ".", "values", ".", "select", "{", "|", "p", "|", "p", ".", "respond_to?", "(", ":bonus", ")", "}", ".", "inject", "(", "0", ")", "{", "|", "t", ",", "p", "|", "t", "+", "(", "p", ".", "calculate_bonus", "?", "1", ":", "0", ")", "}", "end" ]
Calculate bonuses for all players and return the number who got one.
[ "Calculate", "bonuses", "for", "all", "players", "and", "return", "the", "number", "who", "got", "one", "." ]
edcb1bb903f123101fbc25d16192c4524a7112da
https://github.com/sanichi/icu_ratings/blob/edcb1bb903f123101fbc25d16192c4524a7112da/lib/icu_ratings/tournament.rb#L188-L190
train
jinx/migrate
lib/jinx/migration/migratable.rb
Jinx.Migratable.migrate_references
def migrate_references(row, migrated, target, proc_hash=nil) # migrate the owner migratable__migrate_owner(row, migrated, target, proc_hash) # migrate the remaining attributes migratable__set_nonowner_references(migratable_independent_attributes, row, migrated, proc_hash) migratable__set_nonowner_references(self.class.unidirectional_dependent_attributes, row, migrated, proc_hash) end
ruby
def migrate_references(row, migrated, target, proc_hash=nil) # migrate the owner migratable__migrate_owner(row, migrated, target, proc_hash) # migrate the remaining attributes migratable__set_nonowner_references(migratable_independent_attributes, row, migrated, proc_hash) migratable__set_nonowner_references(self.class.unidirectional_dependent_attributes, row, migrated, proc_hash) end
[ "def", "migrate_references", "(", "row", ",", "migrated", ",", "target", ",", "proc_hash", "=", "nil", ")", "migratable__migrate_owner", "(", "row", ",", "migrated", ",", "target", ",", "proc_hash", ")", "migratable__set_nonowner_references", "(", "migratable_independent_attributes", ",", "row", ",", "migrated", ",", "proc_hash", ")", "migratable__set_nonowner_references", "(", "self", ".", "class", ".", "unidirectional_dependent_attributes", ",", "row", ",", "migrated", ",", "proc_hash", ")", "end" ]
Migrates this domain object's migratable references. This method is called by the Migrator and should not be overridden by subclasses. Subclasses tailor individual reference attribute migration by defining a +migrate_+_attribute_ method for the _attribute_ to modify. The migratable reference attributes consist of the non-collection saved independent attributes and the unidirectional dependent attributes which don't already have a value. For each such migratable attribute, if there is a single instance of the attribute type in the given migrated domain objects, then the attribute is set to that migrated instance. If the attribute is associated with a method in proc_hash, then that method is called on the migrated instance and input row. The attribute is set to the method return value. proc_hash includes an entry for each +migrate_+_attribute_ method defined by this Resource's class. @param [{Symbol => Object}] row the input row field => value hash @param [<Resource>] migrated the migrated instances, including this Resource @param [Class] target the migration target class @param [{Symbol => Proc}, nil] proc_hash a hash that associates this domain object's attributes to a migration shim block
[ "Migrates", "this", "domain", "object", "s", "migratable", "references", ".", "This", "method", "is", "called", "by", "the", "Migrator", "and", "should", "not", "be", "overridden", "by", "subclasses", ".", "Subclasses", "tailor", "individual", "reference", "attribute", "migration", "by", "defining", "a", "+", "migrate_", "+", "_attribute_", "method", "for", "the", "_attribute_", "to", "modify", "." ]
309957a470d72da3bd074f8173dbbe2f12449883
https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migratable.rb#L114-L120
train
mikisvaz/progress-monitor
lib/progress-bar.rb
Progress.Progress::Bar.tick
def tick(step = nil) if step.nil? @current += 1 else @current = step end percent = @current.to_f/ @max.to_f if percent - @last_report > 1.to_f/@num_reports.to_f report @last_report=percent end nil end
ruby
def tick(step = nil) if step.nil? @current += 1 else @current = step end percent = @current.to_f/ @max.to_f if percent - @last_report > 1.to_f/@num_reports.to_f report @last_report=percent end nil end
[ "def", "tick", "(", "step", "=", "nil", ")", "if", "step", ".", "nil?", "@current", "+=", "1", "else", "@current", "=", "step", "end", "percent", "=", "@current", ".", "to_f", "/", "@max", ".", "to_f", "if", "percent", "-", "@last_report", ">", "1", ".", "to_f", "/", "@num_reports", ".", "to_f", "report", "@last_report", "=", "percent", "end", "nil", "end" ]
Creates a new instance. Max is the total number of iterations of the loop. The depth represents how many other loops are above this one, this information is used to find the place to print the progress report. Used to register a new completed loop iteration.
[ "Creates", "a", "new", "instance", ".", "Max", "is", "the", "total", "number", "of", "iterations", "of", "the", "loop", ".", "The", "depth", "represents", "how", "many", "other", "loops", "are", "above", "this", "one", "this", "information", "is", "used", "to", "find", "the", "place", "to", "print", "the", "progress", "report", "." ]
b15cfec9e98160c54586fbf96f25b4915985d4e9
https://github.com/mikisvaz/progress-monitor/blob/b15cfec9e98160c54586fbf96f25b4915985d4e9/lib/progress-bar.rb#L22-L37
train
mikisvaz/progress-monitor
lib/progress-bar.rb
Progress.Progress::Bar.report
def report percent = @current.to_f/ @max.to_f percent = 0.001 if percent < 0.001 if @desc != "" indicator = @desc + ": " else indicator = "Progress " end indicator += "[" 10.times{|i| if i < percent * 10 then indicator += "." else indicator += " " end } indicator += "] done #{(percent * 100).to_i}% " eta = (Time.now - @time)/percent * (1-percent) eta = eta.to_i eta = [eta/3600, eta/60 % 60, eta % 60].map{|t| "%02i" % t }.join(':') used = (Time.now - @time).to_i used = [used/3600, used/60 % 60, used % 60].map{|t| "%02i" % t }.join(':') indicator += " (Time left #{eta} seconds) (Started #{used} seconds ago)" STDERR.print("\033[#{@depth + 1}F\033[2K" + indicator + "\n\033[#{@depth + 2}E") end
ruby
def report percent = @current.to_f/ @max.to_f percent = 0.001 if percent < 0.001 if @desc != "" indicator = @desc + ": " else indicator = "Progress " end indicator += "[" 10.times{|i| if i < percent * 10 then indicator += "." else indicator += " " end } indicator += "] done #{(percent * 100).to_i}% " eta = (Time.now - @time)/percent * (1-percent) eta = eta.to_i eta = [eta/3600, eta/60 % 60, eta % 60].map{|t| "%02i" % t }.join(':') used = (Time.now - @time).to_i used = [used/3600, used/60 % 60, used % 60].map{|t| "%02i" % t }.join(':') indicator += " (Time left #{eta} seconds) (Started #{used} seconds ago)" STDERR.print("\033[#{@depth + 1}F\033[2K" + indicator + "\n\033[#{@depth + 2}E") end
[ "def", "report", "percent", "=", "@current", ".", "to_f", "/", "@max", ".", "to_f", "percent", "=", "0.001", "if", "percent", "<", "0.001", "if", "@desc", "!=", "\"\"", "indicator", "=", "@desc", "+", "\": \"", "else", "indicator", "=", "\"Progress \"", "end", "indicator", "+=", "\"[\"", "10", ".", "times", "{", "|", "i", "|", "if", "i", "<", "percent", "*", "10", "then", "indicator", "+=", "\".\"", "else", "indicator", "+=", "\" \"", "end", "}", "indicator", "+=", "\"] done #{(percent * 100).to_i}% \"", "eta", "=", "(", "Time", ".", "now", "-", "@time", ")", "/", "percent", "*", "(", "1", "-", "percent", ")", "eta", "=", "eta", ".", "to_i", "eta", "=", "[", "eta", "/", "3600", ",", "eta", "/", "60", "%", "60", ",", "eta", "%", "60", "]", ".", "map", "{", "|", "t", "|", "\"%02i\"", "%", "t", "}", ".", "join", "(", "':'", ")", "used", "=", "(", "Time", ".", "now", "-", "@time", ")", ".", "to_i", "used", "=", "[", "used", "/", "3600", ",", "used", "/", "60", "%", "60", ",", "used", "%", "60", "]", ".", "map", "{", "|", "t", "|", "\"%02i\"", "%", "t", "}", ".", "join", "(", "':'", ")", "indicator", "+=", "\" (Time left #{eta} seconds) (Started #{used} seconds ago)\"", "STDERR", ".", "print", "(", "\"\\033[#{@depth + 1}F\\033[2K\"", "+", "indicator", "+", "\"\\n\\033[#{@depth + 2}E\"", ")", "end" ]
Prints de progress report. It backs up as many lines as the meters depth. Prints the progress as a line of dots, a percentage, time spent, and time left. And then goes moves the cursor back to its original line. Everything is printed to stderr.
[ "Prints", "de", "progress", "report", ".", "It", "backs", "up", "as", "many", "lines", "as", "the", "meters", "depth", ".", "Prints", "the", "progress", "as", "a", "line", "of", "dots", "a", "percentage", "time", "spent", "and", "time", "left", ".", "And", "then", "goes", "moves", "the", "cursor", "back", "to", "its", "original", "line", ".", "Everything", "is", "printed", "to", "stderr", "." ]
b15cfec9e98160c54586fbf96f25b4915985d4e9
https://github.com/mikisvaz/progress-monitor/blob/b15cfec9e98160c54586fbf96f25b4915985d4e9/lib/progress-bar.rb#L44-L73
train
Lupeipei/i18n-processes
lib/i18n/processes/split_key.rb
I18n::Processes.SplitKey.key_parts
def key_parts(key, &block) return enum_for(:key_parts, key) unless block nesting = PARENS counts = PARENS_ZEROS # dup'd later if key contains parenthesis delim = '.' from = to = 0 key.each_char do |char| if char == delim && PARENS_ZEROS == counts block.yield key[from...to] from = to = (to + 1) else nest_i, nest_inc = nesting[char] if nest_i counts = counts.dup if counts.frozen? counts[nest_i] += nest_inc end to += 1 end end block.yield(key[from...to]) if from < to && to <= key.length true end
ruby
def key_parts(key, &block) return enum_for(:key_parts, key) unless block nesting = PARENS counts = PARENS_ZEROS # dup'd later if key contains parenthesis delim = '.' from = to = 0 key.each_char do |char| if char == delim && PARENS_ZEROS == counts block.yield key[from...to] from = to = (to + 1) else nest_i, nest_inc = nesting[char] if nest_i counts = counts.dup if counts.frozen? counts[nest_i] += nest_inc end to += 1 end end block.yield(key[from...to]) if from < to && to <= key.length true end
[ "def", "key_parts", "(", "key", ",", "&", "block", ")", "return", "enum_for", "(", ":key_parts", ",", "key", ")", "unless", "block", "nesting", "=", "PARENS", "counts", "=", "PARENS_ZEROS", "delim", "=", "'.'", "from", "=", "to", "=", "0", "key", ".", "each_char", "do", "|", "char", "|", "if", "char", "==", "delim", "&&", "PARENS_ZEROS", "==", "counts", "block", ".", "yield", "key", "[", "from", "...", "to", "]", "from", "=", "to", "=", "(", "to", "+", "1", ")", "else", "nest_i", ",", "nest_inc", "=", "nesting", "[", "char", "]", "if", "nest_i", "counts", "=", "counts", ".", "dup", "if", "counts", ".", "frozen?", "counts", "[", "nest_i", "]", "+=", "nest_inc", "end", "to", "+=", "1", "end", "end", "block", ".", "yield", "(", "key", "[", "from", "...", "to", "]", ")", "if", "from", "<", "to", "&&", "to", "<=", "key", ".", "length", "true", "end" ]
yield each key part dots inside braces or parenthesis are not split on
[ "yield", "each", "key", "part", "dots", "inside", "braces", "or", "parenthesis", "are", "not", "split", "on" ]
83c91517f80b82371ab19e197665e6e131024df3
https://github.com/Lupeipei/i18n-processes/blob/83c91517f80b82371ab19e197665e6e131024df3/lib/i18n/processes/split_key.rb#L36-L57
train
richard-viney/lightstreamer
lib/lightstreamer/subscription.rb
Lightstreamer.Subscription.process_stream_data
def process_stream_data(line) return true if process_update_message UpdateMessage.parse(line, id, items, fields) return true if process_overflow_message OverflowMessage.parse(line, id, items) return true if process_end_of_snapshot_message EndOfSnapshotMessage.parse(line, id, items) end
ruby
def process_stream_data(line) return true if process_update_message UpdateMessage.parse(line, id, items, fields) return true if process_overflow_message OverflowMessage.parse(line, id, items) return true if process_end_of_snapshot_message EndOfSnapshotMessage.parse(line, id, items) end
[ "def", "process_stream_data", "(", "line", ")", "return", "true", "if", "process_update_message", "UpdateMessage", ".", "parse", "(", "line", ",", "id", ",", "items", ",", "fields", ")", "return", "true", "if", "process_overflow_message", "OverflowMessage", ".", "parse", "(", "line", ",", "id", ",", "items", ")", "return", "true", "if", "process_end_of_snapshot_message", "EndOfSnapshotMessage", ".", "parse", "(", "line", ",", "id", ",", "items", ")", "end" ]
Processes a line of stream data if it is relevant to this subscription. This method is thread-safe and is intended to be called by the session's processing thread. @param [String] line The line of stream data to process. @return [Boolean] Whether the passed line of stream data was processed by this subscription. @private
[ "Processes", "a", "line", "of", "stream", "data", "if", "it", "is", "relevant", "to", "this", "subscription", ".", "This", "method", "is", "thread", "-", "safe", "and", "is", "intended", "to", "be", "called", "by", "the", "session", "s", "processing", "thread", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/subscription.rb#L208-L212
train
richard-viney/lightstreamer
lib/lightstreamer/subscription.rb
Lightstreamer.Subscription.control_request_options
def control_request_options(action, options = nil) case action.to_sym when :start start_control_request_options options when :unsilence { LS_session: @session.session_id, LS_op: :start, LS_table: id } when :stop { LS_session: @session.session_id, LS_op: :delete, LS_table: id } end end
ruby
def control_request_options(action, options = nil) case action.to_sym when :start start_control_request_options options when :unsilence { LS_session: @session.session_id, LS_op: :start, LS_table: id } when :stop { LS_session: @session.session_id, LS_op: :delete, LS_table: id } end end
[ "def", "control_request_options", "(", "action", ",", "options", "=", "nil", ")", "case", "action", ".", "to_sym", "when", ":start", "start_control_request_options", "options", "when", ":unsilence", "{", "LS_session", ":", "@session", ".", "session_id", ",", "LS_op", ":", ":start", ",", "LS_table", ":", "id", "}", "when", ":stop", "{", "LS_session", ":", "@session", ".", "session_id", ",", "LS_op", ":", ":delete", ",", "LS_table", ":", "id", "}", "end", "end" ]
Returns the control request arguments to use to perform the specified action on this subscription. @private
[ "Returns", "the", "control", "request", "arguments", "to", "use", "to", "perform", "the", "specified", "action", "on", "this", "subscription", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/subscription.rb#L217-L226
train
ziolmar/chaintown
lib/chaintown/steps.rb
Chaintown.Steps.inherited
def inherited(subclass) [:steps, :failed_steps].each do |inheritable_attribute| instance_var = "@#{inheritable_attribute}" subclass.instance_variable_set(instance_var, instance_variable_get(instance_var).dup || []) end end
ruby
def inherited(subclass) [:steps, :failed_steps].each do |inheritable_attribute| instance_var = "@#{inheritable_attribute}" subclass.instance_variable_set(instance_var, instance_variable_get(instance_var).dup || []) end end
[ "def", "inherited", "(", "subclass", ")", "[", ":steps", ",", ":failed_steps", "]", ".", "each", "do", "|", "inheritable_attribute", "|", "instance_var", "=", "\"@#{inheritable_attribute}\"", "subclass", ".", "instance_variable_set", "(", "instance_var", ",", "instance_variable_get", "(", "instance_var", ")", ".", "dup", "||", "[", "]", ")", "end", "end" ]
Callback, assure that we add steps from parent class
[ "Callback", "assure", "that", "we", "add", "steps", "from", "parent", "class" ]
ece36eb5a054f1ec66defb913f4a6d47ea5e4aac
https://github.com/ziolmar/chaintown/blob/ece36eb5a054f1ec66defb913f4a6d47ea5e4aac/lib/chaintown/steps.rb#L50-L55
train
webmonarch/movingsign_api
lib/movingsign_api/sign.rb
MovingsignApi.Sign.show_text
def show_text(text, options = {}) cmd = WriteTextCommand.new cmd.display_pause = options[:display_pause] if options[:display_pause] cmd.text = text send_command cmd end
ruby
def show_text(text, options = {}) cmd = WriteTextCommand.new cmd.display_pause = options[:display_pause] if options[:display_pause] cmd.text = text send_command cmd end
[ "def", "show_text", "(", "text", ",", "options", "=", "{", "}", ")", "cmd", "=", "WriteTextCommand", ".", "new", "cmd", ".", "display_pause", "=", "options", "[", ":display_pause", "]", "if", "options", "[", ":display_pause", "]", "cmd", ".", "text", "=", "text", "send_command", "cmd", "end" ]
Displays the given text on the board. This is short-hand for the {WriteTextCommand} @param text [String] the text to display on the sign @param options [Hash] options for {WriteTextCommand} @option options [Integer] :display_pause (2) Time to pause (in seconds) between pages of text. See {WriteTextCommand#display_pause} @return [self]
[ "Displays", "the", "given", "text", "on", "the", "board", "." ]
11c820edcb5f3a367b341257dae4f6249ae6d0a3
https://github.com/webmonarch/movingsign_api/blob/11c820edcb5f3a367b341257dae4f6249ae6d0a3/lib/movingsign_api/sign.rb#L43-L49
train
webmonarch/movingsign_api
lib/movingsign_api/sign.rb
MovingsignApi.Sign.send_command
def send_command(command) SerialPort.open(self.device_path, 9600, 8, 1) do |port| # flush anything existing on the port port.flush flush_read_buffer(port) byte_string = command.to_bytes.pack('C*') begin while byte_string && byte_string.length != 0 count = port.write_nonblock(byte_string) byte_string = byte_string[count,-1] port.flush end rescue IO::WaitWritable if IO.select([], [port], [], 5) retry else raise IOError, "Timeout writing command to #{self.device_path}" end end # wait for expected confirmation signals got_eot = false got_soh = false loop do begin c = port.read_nonblock(1) case c when "\x04" if ! got_eot got_eot = true else raise IOError, "Got EOT reply twice from #{self.device_path}" end when "\x01" if got_eot if ! got_soh got_soh = true break else raise IOError, "Got SOH twice from #{self.device_path}" end else raise IOError, "Got SOH before EOT from #{self.device_path}" end end rescue IO::WaitReadable if IO.select([port], [], [], 3) retry else raise IOError, "Timeout waiting for command reply from #{self.device_path}. EOT:#{got_eot} SOH:#{got_soh}" end end end end self end
ruby
def send_command(command) SerialPort.open(self.device_path, 9600, 8, 1) do |port| # flush anything existing on the port port.flush flush_read_buffer(port) byte_string = command.to_bytes.pack('C*') begin while byte_string && byte_string.length != 0 count = port.write_nonblock(byte_string) byte_string = byte_string[count,-1] port.flush end rescue IO::WaitWritable if IO.select([], [port], [], 5) retry else raise IOError, "Timeout writing command to #{self.device_path}" end end # wait for expected confirmation signals got_eot = false got_soh = false loop do begin c = port.read_nonblock(1) case c when "\x04" if ! got_eot got_eot = true else raise IOError, "Got EOT reply twice from #{self.device_path}" end when "\x01" if got_eot if ! got_soh got_soh = true break else raise IOError, "Got SOH twice from #{self.device_path}" end else raise IOError, "Got SOH before EOT from #{self.device_path}" end end rescue IO::WaitReadable if IO.select([port], [], [], 3) retry else raise IOError, "Timeout waiting for command reply from #{self.device_path}. EOT:#{got_eot} SOH:#{got_soh}" end end end end self end
[ "def", "send_command", "(", "command", ")", "SerialPort", ".", "open", "(", "self", ".", "device_path", ",", "9600", ",", "8", ",", "1", ")", "do", "|", "port", "|", "port", ".", "flush", "flush_read_buffer", "(", "port", ")", "byte_string", "=", "command", ".", "to_bytes", ".", "pack", "(", "'C*'", ")", "begin", "while", "byte_string", "&&", "byte_string", ".", "length", "!=", "0", "count", "=", "port", ".", "write_nonblock", "(", "byte_string", ")", "byte_string", "=", "byte_string", "[", "count", ",", "-", "1", "]", "port", ".", "flush", "end", "rescue", "IO", "::", "WaitWritable", "if", "IO", ".", "select", "(", "[", "]", ",", "[", "port", "]", ",", "[", "]", ",", "5", ")", "retry", "else", "raise", "IOError", ",", "\"Timeout writing command to #{self.device_path}\"", "end", "end", "got_eot", "=", "false", "got_soh", "=", "false", "loop", "do", "begin", "c", "=", "port", ".", "read_nonblock", "(", "1", ")", "case", "c", "when", "\"\\x04\"", "if", "!", "got_eot", "got_eot", "=", "true", "else", "raise", "IOError", ",", "\"Got EOT reply twice from #{self.device_path}\"", "end", "when", "\"\\x01\"", "if", "got_eot", "if", "!", "got_soh", "got_soh", "=", "true", "break", "else", "raise", "IOError", ",", "\"Got SOH twice from #{self.device_path}\"", "end", "else", "raise", "IOError", ",", "\"Got SOH before EOT from #{self.device_path}\"", "end", "end", "rescue", "IO", "::", "WaitReadable", "if", "IO", ".", "select", "(", "[", "port", "]", ",", "[", "]", ",", "[", "]", ",", "3", ")", "retry", "else", "raise", "IOError", ",", "\"Timeout waiting for command reply from #{self.device_path}. EOT:#{got_eot} SOH:#{got_soh}\"", "end", "end", "end", "end", "self", "end" ]
Sends the specified Movingsign command to this sign's serial port @param [MovingsignApi::Command] command subclass to send @return [self]
[ "Sends", "the", "specified", "Movingsign", "command", "to", "this", "sign", "s", "serial", "port" ]
11c820edcb5f3a367b341257dae4f6249ae6d0a3
https://github.com/webmonarch/movingsign_api/blob/11c820edcb5f3a367b341257dae4f6249ae6d0a3/lib/movingsign_api/sign.rb#L70-L131
train
jns/Aims
lib/aims/wurtzite.rb
Aims.Wurtzite.get_bulk
def get_bulk # The lattice constant a = lattice_const c = 1.63299*a # sqrt(8/3)a # The atoms on a HCP as1 = Atom.new(0,0,0,'As') as2 = as1.displace(0.5*a, 0.33333*a, 0.5*c) ga1 = Atom.new(0.0, 0.0, c*0.386, 'Ga') ga2 = ga1.displace(0.5*a,0.33333*a, 0.5*c) # The lattice Vectors v1 = Vector[1.0, 0.0, 0.0]*a v2 = Vector[0.5, 0.5*sqrt(3), 0.0]*a v3 = Vector[0.0, 0.0, 1.0]*c # The unit cell wz = Geometry.new([as1,ga1,as2,ga2], [v1, v2, v3]) # wz.set_miller_indices(millerX, millerY, millerZ) return wz end
ruby
def get_bulk # The lattice constant a = lattice_const c = 1.63299*a # sqrt(8/3)a # The atoms on a HCP as1 = Atom.new(0,0,0,'As') as2 = as1.displace(0.5*a, 0.33333*a, 0.5*c) ga1 = Atom.new(0.0, 0.0, c*0.386, 'Ga') ga2 = ga1.displace(0.5*a,0.33333*a, 0.5*c) # The lattice Vectors v1 = Vector[1.0, 0.0, 0.0]*a v2 = Vector[0.5, 0.5*sqrt(3), 0.0]*a v3 = Vector[0.0, 0.0, 1.0]*c # The unit cell wz = Geometry.new([as1,ga1,as2,ga2], [v1, v2, v3]) # wz.set_miller_indices(millerX, millerY, millerZ) return wz end
[ "def", "get_bulk", "a", "=", "lattice_const", "c", "=", "1.63299", "*", "a", "as1", "=", "Atom", ".", "new", "(", "0", ",", "0", ",", "0", ",", "'As'", ")", "as2", "=", "as1", ".", "displace", "(", "0.5", "*", "a", ",", "0.33333", "*", "a", ",", "0.5", "*", "c", ")", "ga1", "=", "Atom", ".", "new", "(", "0.0", ",", "0.0", ",", "c", "*", "0.386", ",", "'Ga'", ")", "ga2", "=", "ga1", ".", "displace", "(", "0.5", "*", "a", ",", "0.33333", "*", "a", ",", "0.5", "*", "c", ")", "v1", "=", "Vector", "[", "1.0", ",", "0.0", ",", "0.0", "]", "*", "a", "v2", "=", "Vector", "[", "0.5", ",", "0.5", "*", "sqrt", "(", "3", ")", ",", "0.0", "]", "*", "a", "v3", "=", "Vector", "[", "0.0", ",", "0.0", ",", "1.0", "]", "*", "c", "wz", "=", "Geometry", ".", "new", "(", "[", "as1", ",", "ga1", ",", "as2", ",", "ga2", "]", ",", "[", "v1", ",", "v2", ",", "v3", "]", ")", "return", "wz", "end" ]
Initialize the wurtzite Geometry cation and anion are the atomic species occupying the two different sub-lattices. lattice_const specifies the lattice constant
[ "Initialize", "the", "wurtzite", "Geometry", "cation", "and", "anion", "are", "the", "atomic", "species", "occupying", "the", "two", "different", "sub", "-", "lattices", ".", "lattice_const", "specifies", "the", "lattice", "constant" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/wurtzite.rb#L21-L43
train
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/job_messages_api.rb
TriglavClient.JobMessagesApi.fetch_job_messages
def fetch_job_messages(offset, job_id, opts = {}) data, _status_code, _headers = fetch_job_messages_with_http_info(offset, job_id, opts) return data end
ruby
def fetch_job_messages(offset, job_id, opts = {}) data, _status_code, _headers = fetch_job_messages_with_http_info(offset, job_id, opts) return data end
[ "def", "fetch_job_messages", "(", "offset", ",", "job_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "fetch_job_messages_with_http_info", "(", "offset", ",", "job_id", ",", "opts", ")", "return", "data", "end" ]
Fetch Job messages @param offset Offset (Greater than or equal to) ID for Messages to fetch from @param job_id Job ID @param [Hash] opts the optional parameters @option opts [Integer] :limit Number of limits @return [Array<JobMessageEachResponse>]
[ "Fetch", "Job", "messages" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/job_messages_api.rb#L41-L44
train
mrsimonfletcher/roroacms
app/controllers/roroacms/admin_controller.rb
Roroacms.AdminController.authorize_admin_access
def authorize_admin_access Setting.reload_settings if !check_controller_against_user(params[:controller].sub('roroacms/admin/', '')) && params[:controller] != 'roroacms/admin/dashboard' && params[:controller].include?('roroacms') redirect_to admin_path, flash: { error: I18n.t("controllers.admin.misc.authorize_admin_access_error") } end end
ruby
def authorize_admin_access Setting.reload_settings if !check_controller_against_user(params[:controller].sub('roroacms/admin/', '')) && params[:controller] != 'roroacms/admin/dashboard' && params[:controller].include?('roroacms') redirect_to admin_path, flash: { error: I18n.t("controllers.admin.misc.authorize_admin_access_error") } end end
[ "def", "authorize_admin_access", "Setting", ".", "reload_settings", "if", "!", "check_controller_against_user", "(", "params", "[", ":controller", "]", ".", "sub", "(", "'roroacms/admin/'", ",", "''", ")", ")", "&&", "params", "[", ":controller", "]", "!=", "'roroacms/admin/dashboard'", "&&", "params", "[", ":controller", "]", ".", "include?", "(", "'roroacms'", ")", "redirect_to", "admin_path", ",", "flash", ":", "{", "error", ":", "I18n", ".", "t", "(", "\"controllers.admin.misc.authorize_admin_access_error\"", ")", "}", "end", "end" ]
checks to see if the admin logged in has the necesary rights, if not it will redirect them with an error message
[ "checks", "to", "see", "if", "the", "admin", "logged", "in", "has", "the", "necesary", "rights", "if", "not", "it", "will", "redirect", "them", "with", "an", "error", "message" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin_controller.rb#L30-L35
train
jinx/core
lib/jinx/metadata/introspector.rb
Jinx.Introspector.wrap_java_property
def wrap_java_property(property) pd = property.property_descriptor if pd.property_type == Java::JavaLang::String.java_class then wrap_java_string_property(property) elsif pd.property_type == Java::JavaUtil::Date.java_class then wrap_java_date_property(property) end end
ruby
def wrap_java_property(property) pd = property.property_descriptor if pd.property_type == Java::JavaLang::String.java_class then wrap_java_string_property(property) elsif pd.property_type == Java::JavaUtil::Date.java_class then wrap_java_date_property(property) end end
[ "def", "wrap_java_property", "(", "property", ")", "pd", "=", "property", ".", "property_descriptor", "if", "pd", ".", "property_type", "==", "Java", "::", "JavaLang", "::", "String", ".", "java_class", "then", "wrap_java_string_property", "(", "property", ")", "elsif", "pd", ".", "property_type", "==", "Java", "::", "JavaUtil", "::", "Date", ".", "java_class", "then", "wrap_java_date_property", "(", "property", ")", "end", "end" ]
Adds a filter to the given property access methods if it is a String or Date.
[ "Adds", "a", "filter", "to", "the", "given", "property", "access", "methods", "if", "it", "is", "a", "String", "or", "Date", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/introspector.rb#L107-L114
train
jinx/core
lib/jinx/metadata/introspector.rb
Jinx.Introspector.wrap_java_string_property
def wrap_java_string_property(property) ra, wa = property.accessors jra, jwa = property.java_accessors # filter the attribute writer define_method(wa) do |value| stdval = Math.numeric?(value) ? value.to_s : value send(jwa, stdval) end logger.debug { "Filtered #{qp} #{wa} method with non-String -> String converter." } end
ruby
def wrap_java_string_property(property) ra, wa = property.accessors jra, jwa = property.java_accessors # filter the attribute writer define_method(wa) do |value| stdval = Math.numeric?(value) ? value.to_s : value send(jwa, stdval) end logger.debug { "Filtered #{qp} #{wa} method with non-String -> String converter." } end
[ "def", "wrap_java_string_property", "(", "property", ")", "ra", ",", "wa", "=", "property", ".", "accessors", "jra", ",", "jwa", "=", "property", ".", "java_accessors", "define_method", "(", "wa", ")", "do", "|", "value", "|", "stdval", "=", "Math", ".", "numeric?", "(", "value", ")", "?", "value", ".", "to_s", ":", "value", "send", "(", "jwa", ",", "stdval", ")", "end", "logger", ".", "debug", "{", "\"Filtered #{qp} #{wa} method with non-String -> String converter.\"", "}", "end" ]
Adds a number -> string filter to the given String property Ruby access methods.
[ "Adds", "a", "number", "-", ">", "string", "filter", "to", "the", "given", "String", "property", "Ruby", "access", "methods", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/introspector.rb#L117-L126
train
jinx/core
lib/jinx/metadata/introspector.rb
Jinx.Introspector.wrap_java_date_property
def wrap_java_date_property(property) ra, wa = property.accessors jra, jwa = property.java_accessors # filter the attribute reader define_method(ra) do value = send(jra) Java::JavaUtil::Date === value ? value.to_ruby_date : value end # filter the attribute writer define_method(wa) do |value| value = Java::JavaUtil::Date.from_ruby_date(value) if ::Date === value send(jwa, value) end logger.debug { "Filtered #{qp} #{ra} and #{wa} methods with Java Date <-> Ruby Date converter." } end
ruby
def wrap_java_date_property(property) ra, wa = property.accessors jra, jwa = property.java_accessors # filter the attribute reader define_method(ra) do value = send(jra) Java::JavaUtil::Date === value ? value.to_ruby_date : value end # filter the attribute writer define_method(wa) do |value| value = Java::JavaUtil::Date.from_ruby_date(value) if ::Date === value send(jwa, value) end logger.debug { "Filtered #{qp} #{ra} and #{wa} methods with Java Date <-> Ruby Date converter." } end
[ "def", "wrap_java_date_property", "(", "property", ")", "ra", ",", "wa", "=", "property", ".", "accessors", "jra", ",", "jwa", "=", "property", ".", "java_accessors", "define_method", "(", "ra", ")", "do", "value", "=", "send", "(", "jra", ")", "Java", "::", "JavaUtil", "::", "Date", "===", "value", "?", "value", ".", "to_ruby_date", ":", "value", "end", "define_method", "(", "wa", ")", "do", "|", "value", "|", "value", "=", "Java", "::", "JavaUtil", "::", "Date", ".", "from_ruby_date", "(", "value", ")", "if", "::", "Date", "===", "value", "send", "(", "jwa", ",", "value", ")", "end", "logger", ".", "debug", "{", "\"Filtered #{qp} #{ra} and #{wa} methods with Java Date <-> Ruby Date converter.\"", "}", "end" ]
Adds a Java-Ruby Date filter to the given Date property Ruby access methods. The reader returns a Ruby date. The writer sets a Java date.
[ "Adds", "a", "Java", "-", "Ruby", "Date", "filter", "to", "the", "given", "Date", "property", "Ruby", "access", "methods", ".", "The", "reader", "returns", "a", "Ruby", "date", ".", "The", "writer", "sets", "a", "Java", "date", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/introspector.rb#L130-L147
train
jinx/core
lib/jinx/metadata/introspector.rb
Jinx.Introspector.alias_property_accessors
def alias_property_accessors(property) # the Java reader and writer accessor method symbols jra, jwa = property.java_accessors # strip the Java reader and writer is/get/set prefix and make a symbol alias_method(property.reader, jra) alias_method(property.writer, jwa) end
ruby
def alias_property_accessors(property) # the Java reader and writer accessor method symbols jra, jwa = property.java_accessors # strip the Java reader and writer is/get/set prefix and make a symbol alias_method(property.reader, jra) alias_method(property.writer, jwa) end
[ "def", "alias_property_accessors", "(", "property", ")", "jra", ",", "jwa", "=", "property", ".", "java_accessors", "alias_method", "(", "property", ".", "reader", ",", "jra", ")", "alias_method", "(", "property", ".", "writer", ",", "jwa", ")", "end" ]
Aliases the given Ruby property reader and writer to its underlying Java property reader and writer, resp. @param [Property] property the property to alias
[ "Aliases", "the", "given", "Ruby", "property", "reader", "and", "writer", "to", "its", "underlying", "Java", "property", "reader", "and", "writer", "resp", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/introspector.rb#L152-L158
train
jinx/core
lib/jinx/metadata/introspector.rb
Jinx.Introspector.add_java_property
def add_java_property(pd) # make the attribute metadata prop = create_java_property(pd) add_property(prop) # the property name is an alias for the standard attribute pa = prop.attribute # the Java property name as an attribute symbol ja = pd.name.to_sym delegate_to_property(ja, prop) unless prop.reader == ja prop end
ruby
def add_java_property(pd) # make the attribute metadata prop = create_java_property(pd) add_property(prop) # the property name is an alias for the standard attribute pa = prop.attribute # the Java property name as an attribute symbol ja = pd.name.to_sym delegate_to_property(ja, prop) unless prop.reader == ja prop end
[ "def", "add_java_property", "(", "pd", ")", "prop", "=", "create_java_property", "(", "pd", ")", "add_property", "(", "prop", ")", "pa", "=", "prop", ".", "attribute", "ja", "=", "pd", ".", "name", ".", "to_sym", "delegate_to_property", "(", "ja", ",", "prop", ")", "unless", "prop", ".", "reader", "==", "ja", "prop", "end" ]
Makes a standard attribute for the given property descriptor. Adds a camelized Java-like alias to the standard attribute. @param (see #define_java_property) @return [Property] the new property
[ "Makes", "a", "standard", "attribute", "for", "the", "given", "property", "descriptor", ".", "Adds", "a", "camelized", "Java", "-", "like", "alias", "to", "the", "standard", "attribute", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/introspector.rb#L165-L175
train
jinx/core
lib/jinx/metadata/introspector.rb
Jinx.Introspector.delegate_to_property
def delegate_to_property(aliaz, property) ra, wa = property.accessors if aliaz == ra then raise MetadataError.new("Cannot delegate #{self} #{aliaz} to itself.") end define_method(aliaz) { send(ra) } define_method("#{aliaz}=".to_sym) { |value| send(wa, value) } register_property_alias(aliaz, property.attribute) end
ruby
def delegate_to_property(aliaz, property) ra, wa = property.accessors if aliaz == ra then raise MetadataError.new("Cannot delegate #{self} #{aliaz} to itself.") end define_method(aliaz) { send(ra) } define_method("#{aliaz}=".to_sym) { |value| send(wa, value) } register_property_alias(aliaz, property.attribute) end
[ "def", "delegate_to_property", "(", "aliaz", ",", "property", ")", "ra", ",", "wa", "=", "property", ".", "accessors", "if", "aliaz", "==", "ra", "then", "raise", "MetadataError", ".", "new", "(", "\"Cannot delegate #{self} #{aliaz} to itself.\"", ")", "end", "define_method", "(", "aliaz", ")", "{", "send", "(", "ra", ")", "}", "define_method", "(", "\"#{aliaz}=\"", ".", "to_sym", ")", "{", "|", "value", "|", "send", "(", "wa", ",", "value", ")", "}", "register_property_alias", "(", "aliaz", ",", "property", ".", "attribute", ")", "end" ]
Defines methods _aliaz_ and _aliaz=_ which calls the standard _attribute_ and _attribute=_ accessor methods, resp. Calling rather than aliasing the attribute accessor allows the aliaz accessor to reflect a change to the attribute accessor.
[ "Defines", "methods", "_aliaz_", "and", "_aliaz", "=", "_", "which", "calls", "the", "standard", "_attribute_", "and", "_attribute", "=", "_", "accessor", "methods", "resp", ".", "Calling", "rather", "than", "aliasing", "the", "attribute", "accessor", "allows", "the", "aliaz", "accessor", "to", "reflect", "a", "change", "to", "the", "attribute", "accessor", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/introspector.rb#L187-L193
train
burtcorp/tara
lib/tara/archive.rb
Tara.Archive.create
def create Dir.mktmpdir do |tmp_dir| project_dir = Pathname.new(@config[:app_dir]) package_dir = Pathname.new(tmp_dir) build_dir = Pathname.new(@config[:build_dir]) copy_source(project_dir, package_dir) copy_executables(project_dir, package_dir) create_gem_shims(package_dir) install_dependencies(package_dir, fetcher) Dir.chdir(tmp_dir) do create_archive(build_dir) end File.join(build_dir, @config[:archive_name]) end end
ruby
def create Dir.mktmpdir do |tmp_dir| project_dir = Pathname.new(@config[:app_dir]) package_dir = Pathname.new(tmp_dir) build_dir = Pathname.new(@config[:build_dir]) copy_source(project_dir, package_dir) copy_executables(project_dir, package_dir) create_gem_shims(package_dir) install_dependencies(package_dir, fetcher) Dir.chdir(tmp_dir) do create_archive(build_dir) end File.join(build_dir, @config[:archive_name]) end end
[ "def", "create", "Dir", ".", "mktmpdir", "do", "|", "tmp_dir", "|", "project_dir", "=", "Pathname", ".", "new", "(", "@config", "[", ":app_dir", "]", ")", "package_dir", "=", "Pathname", ".", "new", "(", "tmp_dir", ")", "build_dir", "=", "Pathname", ".", "new", "(", "@config", "[", ":build_dir", "]", ")", "copy_source", "(", "project_dir", ",", "package_dir", ")", "copy_executables", "(", "project_dir", ",", "package_dir", ")", "create_gem_shims", "(", "package_dir", ")", "install_dependencies", "(", "package_dir", ",", "fetcher", ")", "Dir", ".", "chdir", "(", "tmp_dir", ")", "do", "create_archive", "(", "build_dir", ")", "end", "File", ".", "join", "(", "build_dir", ",", "@config", "[", ":archive_name", "]", ")", "end", "end" ]
Create an archive using the instance's configuration. @return [String] Path to the archive
[ "Create", "an", "archive", "using", "the", "instance", "s", "configuration", "." ]
d38a07626da8842bd06a0748d97eacd7902033ee
https://github.com/burtcorp/tara/blob/d38a07626da8842bd06a0748d97eacd7902033ee/lib/tara/archive.rb#L88-L102
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.identity_parts
def identity_parts(id) @brokers.each do |b| return [b.host, b.port, b.index, priority(b.identity)] if b.identity == id || b.alias == id end [nil, nil, nil, nil] end
ruby
def identity_parts(id) @brokers.each do |b| return [b.host, b.port, b.index, priority(b.identity)] if b.identity == id || b.alias == id end [nil, nil, nil, nil] end
[ "def", "identity_parts", "(", "id", ")", "@brokers", ".", "each", "do", "|", "b", "|", "return", "[", "b", ".", "host", ",", "b", ".", "port", ",", "b", ".", "index", ",", "priority", "(", "b", ".", "identity", ")", "]", "if", "b", ".", "identity", "==", "id", "||", "b", ".", "alias", "==", "id", "end", "[", "nil", ",", "nil", ",", "nil", ",", "nil", "]", "end" ]
Break broker serialized identity down into individual parts if exists === Parameters id(Integer|String):: Broker alias or serialized identity === Return (Array):: Host, port, index, and priority, or all nil if broker not found
[ "Break", "broker", "serialized", "identity", "down", "into", "individual", "parts", "if", "exists" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L281-L286
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.get
def get(id) @brokers.each { |b| return b.identity if b.identity == id || b.alias == id } nil end
ruby
def get(id) @brokers.each { |b| return b.identity if b.identity == id || b.alias == id } nil end
[ "def", "get", "(", "id", ")", "@brokers", ".", "each", "{", "|", "b", "|", "return", "b", ".", "identity", "if", "b", ".", "identity", "==", "id", "||", "b", ".", "alias", "==", "id", "}", "nil", "end" ]
Get broker serialized identity if client exists === Parameters id(Integer|String):: Broker alias or serialized identity === Return (String|nil):: Broker serialized identity if client found, otherwise nil
[ "Get", "broker", "serialized", "identity", "if", "client", "exists" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L333-L336
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.connected
def connected @brokers.inject([]) { |c, b| if b.connected? then c << b.identity else c end } end
ruby
def connected @brokers.inject([]) { |c, b| if b.connected? then c << b.identity else c end } end
[ "def", "connected", "@brokers", ".", "inject", "(", "[", "]", ")", "{", "|", "c", ",", "b", "|", "if", "b", ".", "connected?", "then", "c", "<<", "b", ".", "identity", "else", "c", "end", "}", "end" ]
Get serialized identity of connected brokers === Return (Array):: Serialized identity of connected brokers
[ "Get", "serialized", "identity", "of", "connected", "brokers" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L353-L355
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.failed
def failed @brokers.inject([]) { |c, b| b.failed? ? c << b.identity : c } end
ruby
def failed @brokers.inject([]) { |c, b| b.failed? ? c << b.identity : c } end
[ "def", "failed", "@brokers", ".", "inject", "(", "[", "]", ")", "{", "|", "c", ",", "b", "|", "b", ".", "failed?", "?", "c", "<<", "b", ".", "identity", ":", "c", "}", "end" ]
Get serialized identity of failed broker clients, i.e., ones that were never successfully connected, not ones that are just disconnected === Return (Array):: Serialized identity of failed broker clients
[ "Get", "serialized", "identity", "of", "failed", "broker", "clients", "i", ".", "e", ".", "ones", "that", "were", "never", "successfully", "connected", "not", "ones", "that", "are", "just", "disconnected" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L386-L388
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.connect
def connect(host, port, index, priority = nil, force = false, &blk) identity = self.class.identity(host, port) existing = @brokers_hash[identity] if existing && existing.usable? && !force logger.info("Ignored request to reconnect #{identity} because already #{existing.status.to_s}") false else old_identity = identity @brokers.each do |b| if index == b.index # Changing host and/or port of existing broker client old_identity = b.identity break end end unless existing address = {:host => host, :port => port, :index => index} broker = BrokerClient.new(identity, address, @serializer, @exception_stats, @non_delivery_stats, @options, existing) p = priority(old_identity) if priority && priority < p @brokers.insert(priority, broker) elsif priority && priority > p logger.info("Reduced priority setting for broker #{identity} from #{priority} to #{p} to avoid gap in list") @brokers.insert(p, broker) else @brokers[p].close if @brokers[p] @brokers[p] = broker end @brokers_hash[identity] = broker yield broker.identity if block_given? true end end
ruby
def connect(host, port, index, priority = nil, force = false, &blk) identity = self.class.identity(host, port) existing = @brokers_hash[identity] if existing && existing.usable? && !force logger.info("Ignored request to reconnect #{identity} because already #{existing.status.to_s}") false else old_identity = identity @brokers.each do |b| if index == b.index # Changing host and/or port of existing broker client old_identity = b.identity break end end unless existing address = {:host => host, :port => port, :index => index} broker = BrokerClient.new(identity, address, @serializer, @exception_stats, @non_delivery_stats, @options, existing) p = priority(old_identity) if priority && priority < p @brokers.insert(priority, broker) elsif priority && priority > p logger.info("Reduced priority setting for broker #{identity} from #{priority} to #{p} to avoid gap in list") @brokers.insert(p, broker) else @brokers[p].close if @brokers[p] @brokers[p] = broker end @brokers_hash[identity] = broker yield broker.identity if block_given? true end end
[ "def", "connect", "(", "host", ",", "port", ",", "index", ",", "priority", "=", "nil", ",", "force", "=", "false", ",", "&", "blk", ")", "identity", "=", "self", ".", "class", ".", "identity", "(", "host", ",", "port", ")", "existing", "=", "@brokers_hash", "[", "identity", "]", "if", "existing", "&&", "existing", ".", "usable?", "&&", "!", "force", "logger", ".", "info", "(", "\"Ignored request to reconnect #{identity} because already #{existing.status.to_s}\"", ")", "false", "else", "old_identity", "=", "identity", "@brokers", ".", "each", "do", "|", "b", "|", "if", "index", "==", "b", ".", "index", "old_identity", "=", "b", ".", "identity", "break", "end", "end", "unless", "existing", "address", "=", "{", ":host", "=>", "host", ",", ":port", "=>", "port", ",", ":index", "=>", "index", "}", "broker", "=", "BrokerClient", ".", "new", "(", "identity", ",", "address", ",", "@serializer", ",", "@exception_stats", ",", "@non_delivery_stats", ",", "@options", ",", "existing", ")", "p", "=", "priority", "(", "old_identity", ")", "if", "priority", "&&", "priority", "<", "p", "@brokers", ".", "insert", "(", "priority", ",", "broker", ")", "elsif", "priority", "&&", "priority", ">", "p", "logger", ".", "info", "(", "\"Reduced priority setting for broker #{identity} from #{priority} to #{p} to avoid gap in list\"", ")", "@brokers", ".", "insert", "(", "p", ",", "broker", ")", "else", "@brokers", "[", "p", "]", ".", "close", "if", "@brokers", "[", "p", "]", "@brokers", "[", "p", "]", "=", "broker", "end", "@brokers_hash", "[", "identity", "]", "=", "broker", "yield", "broker", ".", "identity", "if", "block_given?", "true", "end", "end" ]
Make new connection to broker at specified address unless already connected or currently connecting === Parameters host{String):: IP host name or address for individual broker port(Integer):: TCP port number for individual broker index(Integer):: Unique index for broker within set for use in forming alias priority(Integer|nil):: Priority position of this broker in set for use by this agent with nil or a value that would leave a gap in the list meaning add to end of list force(Boolean):: Reconnect even if already connected === Block Optional block with following parameters to be called after initiating the connection unless already connected to this broker: identity(String):: Broker serialized identity === Return (Boolean):: true if connected, false if no connect attempt made === Raise Exception:: If host and port do not match an existing broker but index does
[ "Make", "new", "connection", "to", "broker", "at", "specified", "address", "unless", "already", "connected", "or", "currently", "connecting" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L423-L455
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.subscribe
def subscribe(queue, exchange = nil, options = {}, &blk) identities = [] brokers = options.delete(:brokers) each(:usable, brokers) { |b| identities << b.identity if b.subscribe(queue, exchange, options, &blk) } logger.info("Could not subscribe to queue #{queue.inspect} on exchange #{exchange.inspect} " + "on brokers #{each(:usable, brokers).inspect} when selected #{brokers.inspect} " + "from usable #{usable.inspect}") if identities.empty? identities end
ruby
def subscribe(queue, exchange = nil, options = {}, &blk) identities = [] brokers = options.delete(:brokers) each(:usable, brokers) { |b| identities << b.identity if b.subscribe(queue, exchange, options, &blk) } logger.info("Could not subscribe to queue #{queue.inspect} on exchange #{exchange.inspect} " + "on brokers #{each(:usable, brokers).inspect} when selected #{brokers.inspect} " + "from usable #{usable.inspect}") if identities.empty? identities end
[ "def", "subscribe", "(", "queue", ",", "exchange", "=", "nil", ",", "options", "=", "{", "}", ",", "&", "blk", ")", "identities", "=", "[", "]", "brokers", "=", "options", ".", "delete", "(", ":brokers", ")", "each", "(", ":usable", ",", "brokers", ")", "{", "|", "b", "|", "identities", "<<", "b", ".", "identity", "if", "b", ".", "subscribe", "(", "queue", ",", "exchange", ",", "options", ",", "&", "blk", ")", "}", "logger", ".", "info", "(", "\"Could not subscribe to queue #{queue.inspect} on exchange #{exchange.inspect} \"", "+", "\"on brokers #{each(:usable, brokers).inspect} when selected #{brokers.inspect} \"", "+", "\"from usable #{usable.inspect}\"", ")", "if", "identities", ".", "empty?", "identities", "end" ]
Subscribe an AMQP queue to an AMQP exchange on all broker clients that are connected or still connecting Allow connecting here because subscribing may happen before all have confirmed connected Do not wait for confirmation from broker client that subscription is complete When a message is received, acknowledge, unserialize, and log it as specified If the message is unserialized and it is not of the right type, it is dropped after logging a warning === Parameters queue(Hash):: AMQP queue being subscribed with keys :name and :options, which are the standard AMQP ones plus :no_declare(Boolean):: Whether to skip declaring this queue on the broker to cause its creation; for use when client does not have permission to create or knows the queue already exists and wants to avoid declare overhead exchange(Hash|nil):: AMQP exchange to subscribe to with keys :type, :name, and :options, nil means use empty exchange by directly subscribing to queue; the :options are the standard AMQP ones plus :no_declare(Boolean):: Whether to skip declaring this exchange on the broker to cause its creation; for use when client does not have create permission or knows the exchange already exists and wants to avoid declare overhead options(Hash):: Subscribe options: :ack(Boolean):: Whether client takes responsibility for explicitly acknowledging each message received, defaults to implicit acknowledgement in AMQP as part of message receipt :no_unserialize(Boolean):: Do not unserialize message, this is an escape for special situations like enrollment, also implicitly disables receive filtering and logging; this option is implicitly invoked if initialize without a serializer (packet class)(Array(Symbol)):: Filters to be applied in to_s when logging packet to :info, only packet classes specified are accepted, others are not processed but are logged with error :category(String):: Packet category description to be used in error messages :log_data(String):: Additional data to display at end of log entry :no_log(Boolean):: Disable receive logging unless debug level :exchange2(Hash):: Additional exchange to which same queue is to be bound :brokers(Array):: Identity of brokers for which to subscribe, defaults to all usable if nil or empty === Block Block with following parameters to be called each time exchange matches a message to the queue: identity(String):: Serialized identity of broker delivering the message message(Packet|String):: Message received, which is unserialized unless :no_unserialize was specified header(AMQP::Protocol::Header):: Message header (optional block parameter) === Return identities(Array):: Identity of brokers where successfully subscribed
[ "Subscribe", "an", "AMQP", "queue", "to", "an", "AMQP", "exchange", "on", "all", "broker", "clients", "that", "are", "connected", "or", "still", "connecting", "Allow", "connecting", "here", "because", "subscribing", "may", "happen", "before", "all", "have", "confirmed", "connected", "Do", "not", "wait", "for", "confirmation", "from", "broker", "client", "that", "subscription", "is", "complete", "When", "a", "message", "is", "received", "acknowledge", "unserialize", "and", "log", "it", "as", "specified", "If", "the", "message", "is", "unserialized", "and", "it", "is", "not", "of", "the", "right", "type", "it", "is", "dropped", "after", "logging", "a", "warning" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L497-L505
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.unsubscribe
def unsubscribe(queue_names, timeout = nil, &blk) count = each(:usable).inject(0) do |c, b| c + b.queues.inject(0) { |c, q| c + (queue_names.include?(q.name) ? 1 : 0) } end if count == 0 blk.call if blk else handler = CountedDeferrable.new(count, timeout) handler.callback { blk.call if blk } each(:usable) { |b| b.unsubscribe(queue_names) { handler.completed_one } } end true end
ruby
def unsubscribe(queue_names, timeout = nil, &blk) count = each(:usable).inject(0) do |c, b| c + b.queues.inject(0) { |c, q| c + (queue_names.include?(q.name) ? 1 : 0) } end if count == 0 blk.call if blk else handler = CountedDeferrable.new(count, timeout) handler.callback { blk.call if blk } each(:usable) { |b| b.unsubscribe(queue_names) { handler.completed_one } } end true end
[ "def", "unsubscribe", "(", "queue_names", ",", "timeout", "=", "nil", ",", "&", "blk", ")", "count", "=", "each", "(", ":usable", ")", ".", "inject", "(", "0", ")", "do", "|", "c", ",", "b", "|", "c", "+", "b", ".", "queues", ".", "inject", "(", "0", ")", "{", "|", "c", ",", "q", "|", "c", "+", "(", "queue_names", ".", "include?", "(", "q", ".", "name", ")", "?", "1", ":", "0", ")", "}", "end", "if", "count", "==", "0", "blk", ".", "call", "if", "blk", "else", "handler", "=", "CountedDeferrable", ".", "new", "(", "count", ",", "timeout", ")", "handler", ".", "callback", "{", "blk", ".", "call", "if", "blk", "}", "each", "(", ":usable", ")", "{", "|", "b", "|", "b", ".", "unsubscribe", "(", "queue_names", ")", "{", "handler", ".", "completed_one", "}", "}", "end", "true", "end" ]
Unsubscribe from the specified queues on usable broker clients Silently ignore unknown queues === Parameters queue_names(Array):: Names of queues previously subscribed to timeout(Integer):: Number of seconds to wait for all confirmations, defaults to no timeout === Block Optional block with no parameters to be called after all queues are unsubscribed === Return true:: Always return true
[ "Unsubscribe", "from", "the", "specified", "queues", "on", "usable", "broker", "clients", "Silently", "ignore", "unknown", "queues" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L519-L531
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.queue_status
def queue_status(queue_names, timeout = nil, &blk) count = 0 status = {} each(:connected) { |b| b.queues.each { |q| count += 1 if queue_names.include?(q.name) } } if count == 0 blk.call(status) if blk else handler = CountedDeferrable.new(count, timeout) handler.callback { blk.call(status) if blk } each(:connected) do |b| if b.queue_status(queue_names) do |name, messages, consumers| (status[name] ||= {})[b.identity] = {:messages => messages, :consumers => consumers} handler.completed_one end else b.queues.each { |q| handler.completed_one if queue_names.include?(q.name) } end end end true end
ruby
def queue_status(queue_names, timeout = nil, &blk) count = 0 status = {} each(:connected) { |b| b.queues.each { |q| count += 1 if queue_names.include?(q.name) } } if count == 0 blk.call(status) if blk else handler = CountedDeferrable.new(count, timeout) handler.callback { blk.call(status) if blk } each(:connected) do |b| if b.queue_status(queue_names) do |name, messages, consumers| (status[name] ||= {})[b.identity] = {:messages => messages, :consumers => consumers} handler.completed_one end else b.queues.each { |q| handler.completed_one if queue_names.include?(q.name) } end end end true end
[ "def", "queue_status", "(", "queue_names", ",", "timeout", "=", "nil", ",", "&", "blk", ")", "count", "=", "0", "status", "=", "{", "}", "each", "(", ":connected", ")", "{", "|", "b", "|", "b", ".", "queues", ".", "each", "{", "|", "q", "|", "count", "+=", "1", "if", "queue_names", ".", "include?", "(", "q", ".", "name", ")", "}", "}", "if", "count", "==", "0", "blk", ".", "call", "(", "status", ")", "if", "blk", "else", "handler", "=", "CountedDeferrable", ".", "new", "(", "count", ",", "timeout", ")", "handler", ".", "callback", "{", "blk", ".", "call", "(", "status", ")", "if", "blk", "}", "each", "(", ":connected", ")", "do", "|", "b", "|", "if", "b", ".", "queue_status", "(", "queue_names", ")", "do", "|", "name", ",", "messages", ",", "consumers", "|", "(", "status", "[", "name", "]", "||=", "{", "}", ")", "[", "b", ".", "identity", "]", "=", "{", ":messages", "=>", "messages", ",", ":consumers", "=>", "consumers", "}", "handler", ".", "completed_one", "end", "else", "b", ".", "queues", ".", "each", "{", "|", "q", "|", "handler", ".", "completed_one", "if", "queue_names", ".", "include?", "(", "q", ".", "name", ")", "}", "end", "end", "end", "true", "end" ]
Check status of specified queues for connected brokers Silently ignore unknown queues If a queue whose status is being checked does not exist, the associated broker connection will fail and be unusable === Parameters queue_names(Array):: Names of queues previously subscribed to that are to be checked timeout(Integer):: Number of seconds to wait for all status checks, defaults to no timeout === Block Optional block to be called after all queue statuses are obtained with hash parameter containing statuses with queue name as key and value that is a hash with broker identity as key and hash of :messages and :consumers as value; the :messages and :consumers values are nil if there is a failure retrieving them for the given queue === Return true:: Always return true
[ "Check", "status", "of", "specified", "queues", "for", "connected", "brokers", "Silently", "ignore", "unknown", "queues", "If", "a", "queue", "whose", "status", "is", "being", "checked", "does", "not", "exist", "the", "associated", "broker", "connection", "will", "fail", "and", "be", "unusable" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L569-L589
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.publish
def publish(exchange, packet, options = {}) identities = [] no_serialize = options[:no_serialize] || @serializer.nil? message = if no_serialize then packet else @serializer.dump(packet) end brokers = use(options) brokers.each do |b| if b.publish(exchange, packet, message, options.merge(:no_serialize => no_serialize)) identities << b.identity if options[:mandatory] && !no_serialize context = Context.new(packet, options, brokers.map { |b| b.identity }) @published.store(message, context) end break unless options[:fanout] end end if identities.empty? selected = "selected " if options[:brokers] list = aliases(brokers.map { |b| b.identity }).join(", ") raise NoConnectedBrokers, "None of #{selected}brokers [#{list}] are usable for publishing" end identities end
ruby
def publish(exchange, packet, options = {}) identities = [] no_serialize = options[:no_serialize] || @serializer.nil? message = if no_serialize then packet else @serializer.dump(packet) end brokers = use(options) brokers.each do |b| if b.publish(exchange, packet, message, options.merge(:no_serialize => no_serialize)) identities << b.identity if options[:mandatory] && !no_serialize context = Context.new(packet, options, brokers.map { |b| b.identity }) @published.store(message, context) end break unless options[:fanout] end end if identities.empty? selected = "selected " if options[:brokers] list = aliases(brokers.map { |b| b.identity }).join(", ") raise NoConnectedBrokers, "None of #{selected}brokers [#{list}] are usable for publishing" end identities end
[ "def", "publish", "(", "exchange", ",", "packet", ",", "options", "=", "{", "}", ")", "identities", "=", "[", "]", "no_serialize", "=", "options", "[", ":no_serialize", "]", "||", "@serializer", ".", "nil?", "message", "=", "if", "no_serialize", "then", "packet", "else", "@serializer", ".", "dump", "(", "packet", ")", "end", "brokers", "=", "use", "(", "options", ")", "brokers", ".", "each", "do", "|", "b", "|", "if", "b", ".", "publish", "(", "exchange", ",", "packet", ",", "message", ",", "options", ".", "merge", "(", ":no_serialize", "=>", "no_serialize", ")", ")", "identities", "<<", "b", ".", "identity", "if", "options", "[", ":mandatory", "]", "&&", "!", "no_serialize", "context", "=", "Context", ".", "new", "(", "packet", ",", "options", ",", "brokers", ".", "map", "{", "|", "b", "|", "b", ".", "identity", "}", ")", "@published", ".", "store", "(", "message", ",", "context", ")", "end", "break", "unless", "options", "[", ":fanout", "]", "end", "end", "if", "identities", ".", "empty?", "selected", "=", "\"selected \"", "if", "options", "[", ":brokers", "]", "list", "=", "aliases", "(", "brokers", ".", "map", "{", "|", "b", "|", "b", ".", "identity", "}", ")", ".", "join", "(", "\", \"", ")", "raise", "NoConnectedBrokers", ",", "\"None of #{selected}brokers [#{list}] are usable for publishing\"", "end", "identities", "end" ]
Publish message to AMQP exchange of first connected broker === Parameters exchange(Hash):: AMQP exchange to subscribe to with keys :type, :name, and :options, which are the standard AMQP ones plus :no_declare(Boolean):: Whether to skip declaring this exchange or queue on the broker to cause its creation; for use when client does not have create permission or knows the object already exists and wants to avoid declare overhead :declare(Boolean):: Whether to delete this exchange or queue from the AMQP cache to force it to be declared on the broker and thus be created if it does not exist packet(Packet):: Message to serialize and publish options(Hash):: Publish options -- standard AMQP ones plus :mandatory(Boolean):: Return message if the exchange does not have any associated queues or if all the associated queues do not have any consumers :immediate(Boolean):: Return message for the same reasons as :mandatory plus if all of the queues associated with the exchange are not immediately ready to consume the message :fanout(Boolean):: true means publish to all connected brokers :brokers(Array):: Identity of brokers selected for use, defaults to all brokers if nil or empty :order(Symbol):: Broker selection order: :random or :priority, defaults to @select if :brokers is nil, otherwise defaults to :priority :no_serialize(Boolean):: Do not serialize packet because it is already serialized, this is an escape for special situations like enrollment, also implicitly disables publish logging; this option is implicitly invoked if initialize without a serializer :log_filter(Array(Symbol)):: Filters to be applied in to_s when logging packet to :info :log_data(String):: Additional data to display at end of log entry :no_log(Boolean):: Disable publish logging unless debug level === Return identities(Array):: Identity of brokers where packet was successfully published === Raise NoConnectedBrokers:: If cannot find a connected broker
[ "Publish", "message", "to", "AMQP", "exchange", "of", "first", "connected", "broker" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L624-L645
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.delete
def delete(name, options = {}) identities = [] u = usable brokers = options.delete(:brokers) ((brokers || u) & u).each { |i| identities << i if (b = @brokers_hash[i]) && b.delete(name, options) } identities end
ruby
def delete(name, options = {}) identities = [] u = usable brokers = options.delete(:brokers) ((brokers || u) & u).each { |i| identities << i if (b = @brokers_hash[i]) && b.delete(name, options) } identities end
[ "def", "delete", "(", "name", ",", "options", "=", "{", "}", ")", "identities", "=", "[", "]", "u", "=", "usable", "brokers", "=", "options", ".", "delete", "(", ":brokers", ")", "(", "(", "brokers", "||", "u", ")", "&", "u", ")", ".", "each", "{", "|", "i", "|", "identities", "<<", "i", "if", "(", "b", "=", "@brokers_hash", "[", "i", "]", ")", "&&", "b", ".", "delete", "(", "name", ",", "options", ")", "}", "identities", "end" ]
Delete queue in all usable brokers or all selected brokers that are usable === Parameters name(String):: Queue name options(Hash):: Queue declare options plus :brokers(Array):: Identity of brokers in which queue is to be deleted === Return identities(Array):: Identity of brokers where queue was deleted
[ "Delete", "queue", "in", "all", "usable", "brokers", "or", "all", "selected", "brokers", "that", "are", "usable" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L677-L683
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.delete_amqp_resources
def delete_amqp_resources(name, options = {}) identities = [] u = usable ((options[:brokers] || u) & u).each { |i| identities << i if (b = @brokers_hash[i]) && b.delete_amqp_resources(:queue, name) } identities end
ruby
def delete_amqp_resources(name, options = {}) identities = [] u = usable ((options[:brokers] || u) & u).each { |i| identities << i if (b = @brokers_hash[i]) && b.delete_amqp_resources(:queue, name) } identities end
[ "def", "delete_amqp_resources", "(", "name", ",", "options", "=", "{", "}", ")", "identities", "=", "[", "]", "u", "=", "usable", "(", "(", "options", "[", ":brokers", "]", "||", "u", ")", "&", "u", ")", ".", "each", "{", "|", "i", "|", "identities", "<<", "i", "if", "(", "b", "=", "@brokers_hash", "[", "i", "]", ")", "&&", "b", ".", "delete_amqp_resources", "(", ":queue", ",", "name", ")", "}", "identities", "end" ]
Delete queue resources from AMQP in all usable brokers === Parameters name(String):: Queue name options(Hash):: Queue declare options plus :brokers(Array):: Identity of brokers in which queue is to be deleted === Return identities(Array):: Identity of brokers where queue was deleted
[ "Delete", "queue", "resources", "from", "AMQP", "in", "all", "usable", "brokers" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L694-L699
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.remove
def remove(host, port, &blk) identity = self.class.identity(host, port) if broker = @brokers_hash[identity] logger.info("Removing #{identity}, alias #{broker.alias} from broker list") broker.close(propagate = true, normal = true, log = false) @brokers_hash.delete(identity) @brokers.reject! { |b| b.identity == identity } yield identity if block_given? else logger.info("Ignored request to remove #{identity} from broker list because unknown") identity = nil end identity end
ruby
def remove(host, port, &blk) identity = self.class.identity(host, port) if broker = @brokers_hash[identity] logger.info("Removing #{identity}, alias #{broker.alias} from broker list") broker.close(propagate = true, normal = true, log = false) @brokers_hash.delete(identity) @brokers.reject! { |b| b.identity == identity } yield identity if block_given? else logger.info("Ignored request to remove #{identity} from broker list because unknown") identity = nil end identity end
[ "def", "remove", "(", "host", ",", "port", ",", "&", "blk", ")", "identity", "=", "self", ".", "class", ".", "identity", "(", "host", ",", "port", ")", "if", "broker", "=", "@brokers_hash", "[", "identity", "]", "logger", ".", "info", "(", "\"Removing #{identity}, alias #{broker.alias} from broker list\"", ")", "broker", ".", "close", "(", "propagate", "=", "true", ",", "normal", "=", "true", ",", "log", "=", "false", ")", "@brokers_hash", ".", "delete", "(", "identity", ")", "@brokers", ".", "reject!", "{", "|", "b", "|", "b", ".", "identity", "==", "identity", "}", "yield", "identity", "if", "block_given?", "else", "logger", ".", "info", "(", "\"Ignored request to remove #{identity} from broker list because unknown\"", ")", "identity", "=", "nil", "end", "identity", "end" ]
Remove a broker client from the configuration Invoke connection status callbacks only if connection is not already disabled There is no check whether this is the last usable broker client === Parameters host{String):: IP host name or address for individual broker port(Integer):: TCP port number for individual broker === Block Optional block with following parameters to be called after removing the connection unless broker is not configured identity(String):: Broker serialized identity === Return identity(String|nil):: Serialized identity of broker removed, or nil if unknown
[ "Remove", "a", "broker", "client", "from", "the", "configuration", "Invoke", "connection", "status", "callbacks", "only", "if", "connection", "is", "not", "already", "disabled", "There", "is", "no", "check", "whether", "this", "is", "the", "last", "usable", "broker", "client" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L716-L729
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.declare_unusable
def declare_unusable(identities) identities.each do |id| broker = @brokers_hash[id] raise Exception, "Cannot mark unknown broker #{id} unusable" unless broker broker.close(propagate = true, normal = false, log = false) end end
ruby
def declare_unusable(identities) identities.each do |id| broker = @brokers_hash[id] raise Exception, "Cannot mark unknown broker #{id} unusable" unless broker broker.close(propagate = true, normal = false, log = false) end end
[ "def", "declare_unusable", "(", "identities", ")", "identities", ".", "each", "do", "|", "id", "|", "broker", "=", "@brokers_hash", "[", "id", "]", "raise", "Exception", ",", "\"Cannot mark unknown broker #{id} unusable\"", "unless", "broker", "broker", ".", "close", "(", "propagate", "=", "true", ",", "normal", "=", "false", ",", "log", "=", "false", ")", "end", "end" ]
Declare a broker client as unusable === Parameters identities(Array):: Identity of brokers === Return true:: Always return true === Raises Exception:: If identified broker is unknown
[ "Declare", "a", "broker", "client", "as", "unusable" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L741-L747
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.close
def close(&blk) if @closed blk.call if blk else @closed = true @connection_status = {} handler = CountedDeferrable.new(@brokers.size) handler.callback { blk.call if blk } @brokers.each do |b| begin b.close(propagate = false) { handler.completed_one } rescue StandardError => e handler.completed_one logger.exception("Failed to close broker #{b.alias}", e, :trace) @exception_stats.track("close", e) end end end true end
ruby
def close(&blk) if @closed blk.call if blk else @closed = true @connection_status = {} handler = CountedDeferrable.new(@brokers.size) handler.callback { blk.call if blk } @brokers.each do |b| begin b.close(propagate = false) { handler.completed_one } rescue StandardError => e handler.completed_one logger.exception("Failed to close broker #{b.alias}", e, :trace) @exception_stats.track("close", e) end end end true end
[ "def", "close", "(", "&", "blk", ")", "if", "@closed", "blk", ".", "call", "if", "blk", "else", "@closed", "=", "true", "@connection_status", "=", "{", "}", "handler", "=", "CountedDeferrable", ".", "new", "(", "@brokers", ".", "size", ")", "handler", ".", "callback", "{", "blk", ".", "call", "if", "blk", "}", "@brokers", ".", "each", "do", "|", "b", "|", "begin", "b", ".", "close", "(", "propagate", "=", "false", ")", "{", "handler", ".", "completed_one", "}", "rescue", "StandardError", "=>", "e", "handler", ".", "completed_one", "logger", ".", "exception", "(", "\"Failed to close broker #{b.alias}\"", ",", "e", ",", ":trace", ")", "@exception_stats", ".", "track", "(", "\"close\"", ",", "e", ")", "end", "end", "end", "true", "end" ]
Close all broker client connections === Block Optional block with no parameters to be called after all connections are closed === Return true:: Always return true
[ "Close", "all", "broker", "client", "connections" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L756-L775
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.close_one
def close_one(identity, propagate = true, &blk) broker = @brokers_hash[identity] raise Exception, "Cannot close unknown broker #{identity}" unless broker broker.close(propagate, &blk) true end
ruby
def close_one(identity, propagate = true, &blk) broker = @brokers_hash[identity] raise Exception, "Cannot close unknown broker #{identity}" unless broker broker.close(propagate, &blk) true end
[ "def", "close_one", "(", "identity", ",", "propagate", "=", "true", ",", "&", "blk", ")", "broker", "=", "@brokers_hash", "[", "identity", "]", "raise", "Exception", ",", "\"Cannot close unknown broker #{identity}\"", "unless", "broker", "broker", ".", "close", "(", "propagate", ",", "&", "blk", ")", "true", "end" ]
Close an individual broker client connection === Parameters identity(String):: Broker serialized identity propagate(Boolean):: Whether to propagate connection status updates === Block Optional block with no parameters to be called after connection closed === Return true:: Always return true === Raise Exception:: If broker unknown
[ "Close", "an", "individual", "broker", "client", "connection" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L791-L796
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.connection_status
def connection_status(options = {}, &callback) id = generate_id @connection_status[id] = {:boundary => options[:boundary], :brokers => options[:brokers], :callback => callback} if timeout = options[:one_off] @connection_status[id][:timer] = EM::Timer.new(timeout) do if @connection_status[id] if @connection_status[id][:callback].arity == 2 @connection_status[id][:callback].call(:timeout, nil) else @connection_status[id][:callback].call(:timeout) end @connection_status.delete(id) end end end id end
ruby
def connection_status(options = {}, &callback) id = generate_id @connection_status[id] = {:boundary => options[:boundary], :brokers => options[:brokers], :callback => callback} if timeout = options[:one_off] @connection_status[id][:timer] = EM::Timer.new(timeout) do if @connection_status[id] if @connection_status[id][:callback].arity == 2 @connection_status[id][:callback].call(:timeout, nil) else @connection_status[id][:callback].call(:timeout) end @connection_status.delete(id) end end end id end
[ "def", "connection_status", "(", "options", "=", "{", "}", ",", "&", "callback", ")", "id", "=", "generate_id", "@connection_status", "[", "id", "]", "=", "{", ":boundary", "=>", "options", "[", ":boundary", "]", ",", ":brokers", "=>", "options", "[", ":brokers", "]", ",", ":callback", "=>", "callback", "}", "if", "timeout", "=", "options", "[", ":one_off", "]", "@connection_status", "[", "id", "]", "[", ":timer", "]", "=", "EM", "::", "Timer", ".", "new", "(", "timeout", ")", "do", "if", "@connection_status", "[", "id", "]", "if", "@connection_status", "[", "id", "]", "[", ":callback", "]", ".", "arity", "==", "2", "@connection_status", "[", "id", "]", "[", ":callback", "]", ".", "call", "(", ":timeout", ",", "nil", ")", "else", "@connection_status", "[", "id", "]", "[", ":callback", "]", ".", "call", "(", ":timeout", ")", "end", "@connection_status", ".", "delete", "(", "id", ")", "end", "end", "end", "id", "end" ]
Register callback to be activated when there is a change in connection status Can be called more than once without affecting previous callbacks === Parameters options(Hash):: Connection status monitoring options :one_off(Integer):: Seconds to wait for status change; only send update once; if timeout, report :timeout as the status :boundary(Symbol):: :any if only report change on any (0/1) boundary, :all if only report change on all (n-1/n) boundary, defaults to :any :brokers(Array):: Only report a status change for these identified brokers === Block Required block activated when connected count crosses a status boundary with following parameters status(Symbol):: Status of connection: :connected, :disconnected, or :failed, with :failed indicating that all selected brokers or all brokers have failed === Return id(String):: Identifier associated with connection status request
[ "Register", "callback", "to", "be", "activated", "when", "there", "is", "a", "change", "in", "connection", "status", "Can", "be", "called", "more", "than", "once", "without", "affecting", "previous", "callbacks" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L816-L832
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.reset_stats
def reset_stats @return_stats = RightSupport::Stats::Activity.new @non_delivery_stats = RightSupport::Stats::Activity.new @exception_stats = @options[:exception_stats] || RightSupport::Stats::Exceptions.new(self, @options[:exception_callback]) true end
ruby
def reset_stats @return_stats = RightSupport::Stats::Activity.new @non_delivery_stats = RightSupport::Stats::Activity.new @exception_stats = @options[:exception_stats] || RightSupport::Stats::Exceptions.new(self, @options[:exception_callback]) true end
[ "def", "reset_stats", "@return_stats", "=", "RightSupport", "::", "Stats", "::", "Activity", ".", "new", "@non_delivery_stats", "=", "RightSupport", "::", "Stats", "::", "Activity", ".", "new", "@exception_stats", "=", "@options", "[", ":exception_stats", "]", "||", "RightSupport", "::", "Stats", "::", "Exceptions", ".", "new", "(", "self", ",", "@options", "[", ":exception_callback", "]", ")", "true", "end" ]
Reset broker client statistics Do not reset disconnect and failure stats because they might then be inconsistent with underlying connection status === Return true:: Always return true
[ "Reset", "broker", "client", "statistics", "Do", "not", "reset", "disconnect", "and", "failure", "stats", "because", "they", "might", "then", "be", "inconsistent", "with", "underlying", "connection", "status" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L882-L887
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.connect_all
def connect_all self.class.addresses(@options[:host], @options[:port]).map do |a| identity = self.class.identity(a[:host], a[:port]) BrokerClient.new(identity, a, @serializer, @exception_stats, @non_delivery_stats, @options, nil) end end
ruby
def connect_all self.class.addresses(@options[:host], @options[:port]).map do |a| identity = self.class.identity(a[:host], a[:port]) BrokerClient.new(identity, a, @serializer, @exception_stats, @non_delivery_stats, @options, nil) end end
[ "def", "connect_all", "self", ".", "class", ".", "addresses", "(", "@options", "[", ":host", "]", ",", "@options", "[", ":port", "]", ")", ".", "map", "do", "|", "a", "|", "identity", "=", "self", ".", "class", ".", "identity", "(", "a", "[", ":host", "]", ",", "a", "[", ":port", "]", ")", "BrokerClient", ".", "new", "(", "identity", ",", "a", ",", "@serializer", ",", "@exception_stats", ",", "@non_delivery_stats", ",", "@options", ",", "nil", ")", "end", "end" ]
Connect to all configured brokers === Return (Array):: Broker clients created
[ "Connect", "to", "all", "configured", "brokers" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L895-L900
train
rightscale/right_amqp
lib/right_amqp/ha_client/ha_broker_client.rb
RightAMQP.HABrokerClient.priority
def priority(identity) priority = 0 @brokers.each do |b| break if b.identity == identity priority += 1 end priority end
ruby
def priority(identity) priority = 0 @brokers.each do |b| break if b.identity == identity priority += 1 end priority end
[ "def", "priority", "(", "identity", ")", "priority", "=", "0", "@brokers", ".", "each", "do", "|", "b", "|", "break", "if", "b", ".", "identity", "==", "identity", "priority", "+=", "1", "end", "priority", "end" ]
Determine priority of broker If broker not found, assign next available priority === Parameters identity(String):: Broker identity === Return (Integer):: Priority position of broker
[ "Determine", "priority", "of", "broker", "If", "broker", "not", "found", "assign", "next", "available", "priority" ]
248de38141b228bdb437757155d7fd7dd6e50733
https://github.com/rightscale/right_amqp/blob/248de38141b228bdb437757155d7fd7dd6e50733/lib/right_amqp/ha_client/ha_broker_client.rb#L910-L917
train