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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
ruby-processing/JRubyArt
lib/jruby_art/helper_methods.rb
Processing.HelperMethods.proxy_java_fields
def proxy_java_fields fields = %w(key frameRate mousePressed keyPressed) methods = fields.map { |field| java_class.declared_field(field) } @declared_fields = Hash[fields.zip(methods)] end
ruby
def proxy_java_fields fields = %w(key frameRate mousePressed keyPressed) methods = fields.map { |field| java_class.declared_field(field) } @declared_fields = Hash[fields.zip(methods)] end
[ "def", "proxy_java_fields", "fields", "=", "%w(", "key", "frameRate", "mousePressed", "keyPressed", ")", "methods", "=", "fields", ".", "map", "{", "|", "field", "|", "java_class", ".", "declared_field", "(", "field", ")", "}", "@declared_fields", "=", "Hash", "[", "fields", ".", "zip", "(", "methods", ")", "]", "end" ]
Proxy over a list of Java declared fields that have the same name as some methods. Add to this list as needed.
[ "Proxy", "over", "a", "list", "of", "Java", "declared", "fields", "that", "have", "the", "same", "name", "as", "some", "methods", ".", "Add", "to", "this", "list", "as", "needed", "." ]
3bd44d4e762d0184c714c4641a5cc3a6891aecf7
https://github.com/ruby-processing/JRubyArt/blob/3bd44d4e762d0184c714c4641a5cc3a6891aecf7/lib/jruby_art/helper_methods.rb#L125-L129
train
ruby-processing/JRubyArt
lib/jruby_art/runner.rb
Processing.Runner.execute!
def execute! show_help if options.empty? show_version if options[:version] run_sketch if options[:run] watch_sketch if options[:watch] live if options[:live] create if options[:create] check if options[:check] install if options[:install] end
ruby
def execute! show_help if options.empty? show_version if options[:version] run_sketch if options[:run] watch_sketch if options[:watch] live if options[:live] create if options[:create] check if options[:check] install if options[:install] end
[ "def", "execute!", "show_help", "if", "options", ".", "empty?", "show_version", "if", "options", "[", ":version", "]", "run_sketch", "if", "options", "[", ":run", "]", "watch_sketch", "if", "options", "[", ":watch", "]", "live", "if", "options", "[", ":live", "]", "create", "if", "options", "[", ":create", "]", "check", "if", "options", "[", ":check", "]", "install", "if", "options", "[", ":install", "]", "end" ]
Dispatch central.
[ "Dispatch", "central", "." ]
3bd44d4e762d0184c714c4641a5cc3a6891aecf7
https://github.com/ruby-processing/JRubyArt/blob/3bd44d4e762d0184c714c4641a5cc3a6891aecf7/lib/jruby_art/runner.rb#L38-L47
train
ruby-processing/JRubyArt
lib/jruby_art/runner.rb
Processing.Runner.parse_options
def parse_options(args) opt_parser = OptionParser.new do |opts| # Set a banner, displayed at the top # of the help screen. opts.banner = 'Usage: k9 [options] [<filename.rb>]' # Define the options, and what they do options[:version] = false opts.on('-v', '--version', 'JRubyArt Version') do options[:version] = true end options[:install] = false opts.on('-i', '--install', 'Installs jruby-complete and examples') do options[:install] = true end options[:check] = false opts.on('-?', '--check', 'Prints configuration') do options[:check] = true end options[:app] = false opts.on('-a', '--app', 'Export as app NOT IMPLEMENTED YET') do options[:export] = true end options[:watch] = false opts.on('-w', '--watch', 'Watch/run the sketch') do options[:watch] = true end options[:run] = false opts.on('-r', '--run', 'Run the sketch') do options[:run] = true end options[:live] = false opts.on('-l', '--live', 'As above, with pry console bound to Processing.app') do options[:live] = true end options[:create] = false opts.on('-c', '--create', 'Create new outline sketch') do options[:create] = true end # This displays the help screen, all programs are # assumed to have this option. opts.on('-h', '--help', 'Display this screen') do puts opts exit end end @argc = opt_parser.parse(args) @filename = argc.shift end
ruby
def parse_options(args) opt_parser = OptionParser.new do |opts| # Set a banner, displayed at the top # of the help screen. opts.banner = 'Usage: k9 [options] [<filename.rb>]' # Define the options, and what they do options[:version] = false opts.on('-v', '--version', 'JRubyArt Version') do options[:version] = true end options[:install] = false opts.on('-i', '--install', 'Installs jruby-complete and examples') do options[:install] = true end options[:check] = false opts.on('-?', '--check', 'Prints configuration') do options[:check] = true end options[:app] = false opts.on('-a', '--app', 'Export as app NOT IMPLEMENTED YET') do options[:export] = true end options[:watch] = false opts.on('-w', '--watch', 'Watch/run the sketch') do options[:watch] = true end options[:run] = false opts.on('-r', '--run', 'Run the sketch') do options[:run] = true end options[:live] = false opts.on('-l', '--live', 'As above, with pry console bound to Processing.app') do options[:live] = true end options[:create] = false opts.on('-c', '--create', 'Create new outline sketch') do options[:create] = true end # This displays the help screen, all programs are # assumed to have this option. opts.on('-h', '--help', 'Display this screen') do puts opts exit end end @argc = opt_parser.parse(args) @filename = argc.shift end
[ "def", "parse_options", "(", "args", ")", "opt_parser", "=", "OptionParser", ".", "new", "do", "|", "opts", "|", "opts", ".", "banner", "=", "'Usage: k9 [options] [<filename.rb>]'", "options", "[", ":version", "]", "=", "false", "opts", ".", "on", "(", "'-v'", ",", "'--version'", ",", "'JRubyArt Version'", ")", "do", "options", "[", ":version", "]", "=", "true", "end", "options", "[", ":install", "]", "=", "false", "opts", ".", "on", "(", "'-i'", ",", "'--install'", ",", "'Installs jruby-complete and examples'", ")", "do", "options", "[", ":install", "]", "=", "true", "end", "options", "[", ":check", "]", "=", "false", "opts", ".", "on", "(", "'-?'", ",", "'--check'", ",", "'Prints configuration'", ")", "do", "options", "[", ":check", "]", "=", "true", "end", "options", "[", ":app", "]", "=", "false", "opts", ".", "on", "(", "'-a'", ",", "'--app'", ",", "'Export as app NOT IMPLEMENTED YET'", ")", "do", "options", "[", ":export", "]", "=", "true", "end", "options", "[", ":watch", "]", "=", "false", "opts", ".", "on", "(", "'-w'", ",", "'--watch'", ",", "'Watch/run the sketch'", ")", "do", "options", "[", ":watch", "]", "=", "true", "end", "options", "[", ":run", "]", "=", "false", "opts", ".", "on", "(", "'-r'", ",", "'--run'", ",", "'Run the sketch'", ")", "do", "options", "[", ":run", "]", "=", "true", "end", "options", "[", ":live", "]", "=", "false", "opts", ".", "on", "(", "'-l'", ",", "'--live'", ",", "'As above, with pry console bound to Processing.app'", ")", "do", "options", "[", ":live", "]", "=", "true", "end", "options", "[", ":create", "]", "=", "false", "opts", ".", "on", "(", "'-c'", ",", "'--create'", ",", "'Create new outline sketch'", ")", "do", "options", "[", ":create", "]", "=", "true", "end", "opts", ".", "on", "(", "'-h'", ",", "'--help'", ",", "'Display this screen'", ")", "do", "puts", "opts", "exit", "end", "end", "@argc", "=", "opt_parser", ".", "parse", "(", "args", ")", "@filename", "=", "argc", ".", "shift", "end" ]
Parse the command-line options.
[ "Parse", "the", "command", "-", "line", "options", "." ]
3bd44d4e762d0184c714c4641a5cc3a6891aecf7
https://github.com/ruby-processing/JRubyArt/blob/3bd44d4e762d0184c714c4641a5cc3a6891aecf7/lib/jruby_art/runner.rb#L50-L105
train
berk/will_filter
app/models/will_filter/filter.rb
WillFilter.Filter.model_class
def model_class if WillFilter::Config.require_filter_extensions? raise WillFilter::FilterException.new("model_class method must be overloaded in the extending class.") end if model_class_name.blank? raise WillFilter::FilterException.new("model_class_name was not specified.") end @model_class ||= model_class_name.constantize end
ruby
def model_class if WillFilter::Config.require_filter_extensions? raise WillFilter::FilterException.new("model_class method must be overloaded in the extending class.") end if model_class_name.blank? raise WillFilter::FilterException.new("model_class_name was not specified.") end @model_class ||= model_class_name.constantize end
[ "def", "model_class", "if", "WillFilter", "::", "Config", ".", "require_filter_extensions?", "raise", "WillFilter", "::", "FilterException", ".", "new", "(", "\"model_class method must be overloaded in the extending class.\"", ")", "end", "if", "model_class_name", ".", "blank?", "raise", "WillFilter", "::", "FilterException", ".", "new", "(", "\"model_class_name was not specified.\"", ")", "end", "@model_class", "||=", "model_class_name", ".", "constantize", "end" ]
For extra security, this method must be overloaded by the extending class.
[ "For", "extra", "security", "this", "method", "must", "be", "overloaded", "by", "the", "extending", "class", "." ]
53ff0c925f55c60b879aea8b3c323655dad7ea07
https://github.com/berk/will_filter/blob/53ff0c925f55c60b879aea8b3c323655dad7ea07/app/models/will_filter/filter.rb#L134-L144
train
berk/will_filter
app/models/will_filter/filter.rb
WillFilter.Filter.condition_title_for
def condition_title_for(key) title_parts = key.to_s.split('.') title = key.to_s.gsub(".", ": ").gsub("_", " ") title = title.split(" ").collect{|part| part.split("/").last.capitalize}.join(" ") if title_parts.size > 1 "#{JOIN_NAME_INDICATOR} #{title}" else title end end
ruby
def condition_title_for(key) title_parts = key.to_s.split('.') title = key.to_s.gsub(".", ": ").gsub("_", " ") title = title.split(" ").collect{|part| part.split("/").last.capitalize}.join(" ") if title_parts.size > 1 "#{JOIN_NAME_INDICATOR} #{title}" else title end end
[ "def", "condition_title_for", "(", "key", ")", "title_parts", "=", "key", ".", "to_s", ".", "split", "(", "'.'", ")", "title", "=", "key", ".", "to_s", ".", "gsub", "(", "\".\"", ",", "\": \"", ")", ".", "gsub", "(", "\"_\"", ",", "\" \"", ")", "title", "=", "title", ".", "split", "(", "\" \"", ")", ".", "collect", "{", "|", "part", "|", "part", ".", "split", "(", "\"/\"", ")", ".", "last", ".", "capitalize", "}", ".", "join", "(", "\" \"", ")", "if", "title_parts", ".", "size", ">", "1", "\"#{JOIN_NAME_INDICATOR} #{title}\"", "else", "title", "end", "end" ]
Can be overloaded for custom titles
[ "Can", "be", "overloaded", "for", "custom", "titles" ]
53ff0c925f55c60b879aea8b3c323655dad7ea07
https://github.com/berk/will_filter/blob/53ff0c925f55c60b879aea8b3c323655dad7ea07/app/models/will_filter/filter.rb#L338-L347
train
berk/will_filter
app/models/will_filter/filter.rb
WillFilter.Filter.export_formats
def export_formats formats = [] formats << ["-- Generic Formats --", -1] WillFilter::Config.default_export_formats.each do |frmt| formats << [frmt, frmt] end if custom_formats.size > 0 formats << ["-- Custom Formats --", -2] custom_formats.each do |frmt| formats << frmt end end formats end
ruby
def export_formats formats = [] formats << ["-- Generic Formats --", -1] WillFilter::Config.default_export_formats.each do |frmt| formats << [frmt, frmt] end if custom_formats.size > 0 formats << ["-- Custom Formats --", -2] custom_formats.each do |frmt| formats << frmt end end formats end
[ "def", "export_formats", "formats", "=", "[", "]", "formats", "<<", "[", "\"-- Generic Formats --\"", ",", "-", "1", "]", "WillFilter", "::", "Config", ".", "default_export_formats", ".", "each", "do", "|", "frmt", "|", "formats", "<<", "[", "frmt", ",", "frmt", "]", "end", "if", "custom_formats", ".", "size", ">", "0", "formats", "<<", "[", "\"-- Custom Formats --\"", ",", "-", "2", "]", "custom_formats", ".", "each", "do", "|", "frmt", "|", "formats", "<<", "frmt", "end", "end", "formats", "end" ]
Export Filter Data
[ "Export", "Filter", "Data" ]
53ff0c925f55c60b879aea8b3c323655dad7ea07
https://github.com/berk/will_filter/blob/53ff0c925f55c60b879aea8b3c323655dad7ea07/app/models/will_filter/filter.rb#L832-L845
train
berk/will_filter
app/models/will_filter/filter.rb
WillFilter.Filter.joins
def joins return nil if inner_joins.empty? inner_joins.collect do |inner_join| join_table_name = association_class(inner_join).table_name join_on_field = inner_join.last.to_s "INNER JOIN #{join_table_name} ON #{join_table_name}.id = #{table_name}.#{join_on_field}" end end
ruby
def joins return nil if inner_joins.empty? inner_joins.collect do |inner_join| join_table_name = association_class(inner_join).table_name join_on_field = inner_join.last.to_s "INNER JOIN #{join_table_name} ON #{join_table_name}.id = #{table_name}.#{join_on_field}" end end
[ "def", "joins", "return", "nil", "if", "inner_joins", ".", "empty?", "inner_joins", ".", "collect", "do", "|", "inner_join", "|", "join_table_name", "=", "association_class", "(", "inner_join", ")", ".", "table_name", "join_on_field", "=", "inner_join", ".", "last", ".", "to_s", "\"INNER JOIN #{join_table_name} ON #{join_table_name}.id = #{table_name}.#{join_on_field}\"", "end", "end" ]
deprecated for Rails 3.0 and up
[ "deprecated", "for", "Rails", "3", ".", "0", "and", "up" ]
53ff0c925f55c60b879aea8b3c323655dad7ea07
https://github.com/berk/will_filter/blob/53ff0c925f55c60b879aea8b3c323655dad7ea07/app/models/will_filter/filter.rb#L871-L878
train
Bandwidth/ruby-bandwidth
lib/bandwidth/client.rb
Bandwidth.Client.make_request
def make_request(method, path, data = {}, api_version = 'v1', api_endpoint = '') d = camelcase(data) build_path = lambda {|path| "/#{api_version}" + (if path[0] == "/" then path else "/#{path}" end) } # A somewhat less ideal solution to the V1/V2 endpoint split # If no endpoint is defined, use default connection if api_endpoint.length == 0 create_connection = @create_connection # Otherwise retrieve (or create if needed) the connection based on the given api_endpoint else if not @created_connections.key?(api_endpoint) new_connection = lambda{|| Faraday.new(api_endpoint) { |faraday| faraday.basic_auth(@api_token, @api_secret) faraday.headers['Accept'] = 'application/json' faraday.headers['User-Agent'] = "ruby-bandwidth/v#{Bandwidth::VERSION}" @set_adapter.call(faraday) @configure_connection.call(faraday) if @configure_connection } } @created_connections[api_endpoint] = new_connection end create_connection = @created_connections[api_endpoint] end connection = create_connection.call() response = if method == :get || method == :delete connection.run_request(method, build_path.call(path), nil, nil) do |req| req.params = d unless d == nil || d.empty? end else connection.run_request(method, build_path.call(path), d.to_json(), {'Content-Type' => 'application/json'}) end check_response(response) r = if response.body.strip().size > 0 then symbolize(JSON.parse(response.body)) else {} end [r, symbolize(response.headers || {})] end
ruby
def make_request(method, path, data = {}, api_version = 'v1', api_endpoint = '') d = camelcase(data) build_path = lambda {|path| "/#{api_version}" + (if path[0] == "/" then path else "/#{path}" end) } # A somewhat less ideal solution to the V1/V2 endpoint split # If no endpoint is defined, use default connection if api_endpoint.length == 0 create_connection = @create_connection # Otherwise retrieve (or create if needed) the connection based on the given api_endpoint else if not @created_connections.key?(api_endpoint) new_connection = lambda{|| Faraday.new(api_endpoint) { |faraday| faraday.basic_auth(@api_token, @api_secret) faraday.headers['Accept'] = 'application/json' faraday.headers['User-Agent'] = "ruby-bandwidth/v#{Bandwidth::VERSION}" @set_adapter.call(faraday) @configure_connection.call(faraday) if @configure_connection } } @created_connections[api_endpoint] = new_connection end create_connection = @created_connections[api_endpoint] end connection = create_connection.call() response = if method == :get || method == :delete connection.run_request(method, build_path.call(path), nil, nil) do |req| req.params = d unless d == nil || d.empty? end else connection.run_request(method, build_path.call(path), d.to_json(), {'Content-Type' => 'application/json'}) end check_response(response) r = if response.body.strip().size > 0 then symbolize(JSON.parse(response.body)) else {} end [r, symbolize(response.headers || {})] end
[ "def", "make_request", "(", "method", ",", "path", ",", "data", "=", "{", "}", ",", "api_version", "=", "'v1'", ",", "api_endpoint", "=", "''", ")", "d", "=", "camelcase", "(", "data", ")", "build_path", "=", "lambda", "{", "|", "path", "|", "\"/#{api_version}\"", "+", "(", "if", "path", "[", "0", "]", "==", "\"/\"", "then", "path", "else", "\"/#{path}\"", "end", ")", "}", "if", "api_endpoint", ".", "length", "==", "0", "create_connection", "=", "@create_connection", "else", "if", "not", "@created_connections", ".", "key?", "(", "api_endpoint", ")", "new_connection", "=", "lambda", "{", "|", "|", "Faraday", ".", "new", "(", "api_endpoint", ")", "{", "|", "faraday", "|", "faraday", ".", "basic_auth", "(", "@api_token", ",", "@api_secret", ")", "faraday", ".", "headers", "[", "'Accept'", "]", "=", "'application/json'", "faraday", ".", "headers", "[", "'User-Agent'", "]", "=", "\"ruby-bandwidth/v#{Bandwidth::VERSION}\"", "@set_adapter", ".", "call", "(", "faraday", ")", "@configure_connection", ".", "call", "(", "faraday", ")", "if", "@configure_connection", "}", "}", "@created_connections", "[", "api_endpoint", "]", "=", "new_connection", "end", "create_connection", "=", "@created_connections", "[", "api_endpoint", "]", "end", "connection", "=", "create_connection", ".", "call", "(", ")", "response", "=", "if", "method", "==", ":get", "||", "method", "==", ":delete", "connection", ".", "run_request", "(", "method", ",", "build_path", ".", "call", "(", "path", ")", ",", "nil", ",", "nil", ")", "do", "|", "req", "|", "req", ".", "params", "=", "d", "unless", "d", "==", "nil", "||", "d", ".", "empty?", "end", "else", "connection", ".", "run_request", "(", "method", ",", "build_path", ".", "call", "(", "path", ")", ",", "d", ".", "to_json", "(", ")", ",", "{", "'Content-Type'", "=>", "'application/json'", "}", ")", "end", "check_response", "(", "response", ")", "r", "=", "if", "response", ".", "body", ".", "strip", "(", ")", ".", "size", ">", "0", "then", "symbolize", "(", "JSON", ".", "parse", "(", "response", ".", "body", ")", ")", "else", "{", "}", "end", "[", "r", ",", "symbolize", "(", "response", ".", "headers", "||", "{", "}", ")", "]", "end" ]
Make HTTP request to Catapult API @param method [Symbol] http method to make @param path [String] path of url (exclude api verion and endpoint) to make call @param data [Hash] data which will be sent with request (for :get and :delete request they will be sent with query in url) @return [Array] array with 2 elements: parsed json data of response and response headers
[ "Make", "HTTP", "request", "to", "Catapult", "API" ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/client.rb#L89-L125
train
Bandwidth/ruby-bandwidth
lib/bandwidth/client.rb
Bandwidth.Client.check_response
def check_response(response) if response.status >= 400 parsed_body = JSON.parse(response.body) raise Errors::GenericError.new(parsed_body['code'], parsed_body['message']) end end
ruby
def check_response(response) if response.status >= 400 parsed_body = JSON.parse(response.body) raise Errors::GenericError.new(parsed_body['code'], parsed_body['message']) end end
[ "def", "check_response", "(", "response", ")", "if", "response", ".", "status", ">=", "400", "parsed_body", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "raise", "Errors", "::", "GenericError", ".", "new", "(", "parsed_body", "[", "'code'", "]", ",", "parsed_body", "[", "'message'", "]", ")", "end", "end" ]
Check response object and raise error if status code >= 400 @param response response object
[ "Check", "response", "object", "and", "raise", "error", "if", "status", "code", ">", "=", "400" ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/client.rb#L129-L134
train
Bandwidth/ruby-bandwidth
lib/bandwidth/client.rb
Bandwidth.Client.camelcase
def camelcase v case when v.is_a?(Array) v.map {|i| camelcase(i)} when v.is_a?(Hash) result = {} v.each do |k, val| result[k.to_s().camelcase(:lower)] = camelcase(val) end result else v end end
ruby
def camelcase v case when v.is_a?(Array) v.map {|i| camelcase(i)} when v.is_a?(Hash) result = {} v.each do |k, val| result[k.to_s().camelcase(:lower)] = camelcase(val) end result else v end end
[ "def", "camelcase", "v", "case", "when", "v", ".", "is_a?", "(", "Array", ")", "v", ".", "map", "{", "|", "i", "|", "camelcase", "(", "i", ")", "}", "when", "v", ".", "is_a?", "(", "Hash", ")", "result", "=", "{", "}", "v", ".", "each", "do", "|", "k", ",", "val", "|", "result", "[", "k", ".", "to_s", "(", ")", ".", "camelcase", "(", ":lower", ")", "]", "=", "camelcase", "(", "val", ")", "end", "result", "else", "v", "end", "end" ]
Convert all keys of a hash to camel cased strings
[ "Convert", "all", "keys", "of", "a", "hash", "to", "camel", "cased", "strings" ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/client.rb#L150-L163
train
Bandwidth/ruby-bandwidth
lib/bandwidth/client.rb
Bandwidth.Client.symbolize
def symbolize v case when v.is_a?(Array) v.map {|i| symbolize(i)} when v.is_a?(Hash) result = {} v.each do |k, val| result[k.underscore().to_sym()] = symbolize(val) end result else v end end
ruby
def symbolize v case when v.is_a?(Array) v.map {|i| symbolize(i)} when v.is_a?(Hash) result = {} v.each do |k, val| result[k.underscore().to_sym()] = symbolize(val) end result else v end end
[ "def", "symbolize", "v", "case", "when", "v", ".", "is_a?", "(", "Array", ")", "v", ".", "map", "{", "|", "i", "|", "symbolize", "(", "i", ")", "}", "when", "v", ".", "is_a?", "(", "Hash", ")", "result", "=", "{", "}", "v", ".", "each", "do", "|", "k", ",", "val", "|", "result", "[", "k", ".", "underscore", "(", ")", ".", "to_sym", "(", ")", "]", "=", "symbolize", "(", "val", ")", "end", "result", "else", "v", "end", "end" ]
Convert all keys of hash to underscored symbols
[ "Convert", "all", "keys", "of", "hash", "to", "underscored", "symbols" ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/client.rb#L166-L179
train
superp/rails-uploader
lib/uploader/asset.rb
Uploader.Asset.to_fileupload
def to_fileupload { id: id, name: filename, content_type: content_type, size: size, url: url, thumb_url: thumb_url } end
ruby
def to_fileupload { id: id, name: filename, content_type: content_type, size: size, url: url, thumb_url: thumb_url } end
[ "def", "to_fileupload", "{", "id", ":", "id", ",", "name", ":", "filename", ",", "content_type", ":", "content_type", ",", "size", ":", "size", ",", "url", ":", "url", ",", "thumb_url", ":", "thumb_url", "}", "end" ]
Serialize asset to fileupload JSON format
[ "Serialize", "asset", "to", "fileupload", "JSON", "format" ]
5a37278ce77292d65b790995d2b4613688b8d7f1
https://github.com/superp/rails-uploader/blob/5a37278ce77292d65b790995d2b4613688b8d7f1/lib/uploader/asset.rb#L79-L88
train
Bandwidth/ruby-bandwidth
lib/bandwidth/recording.rb
Bandwidth.Recording.create_transcription
def create_transcription() headers = @client.make_request(:post, @client.concat_user_path("#{RECORDING_PATH}/#{id}/transcriptions"), {})[1] id = Client.get_id_from_location_header(headers[:location]) get_transcription(id) end
ruby
def create_transcription() headers = @client.make_request(:post, @client.concat_user_path("#{RECORDING_PATH}/#{id}/transcriptions"), {})[1] id = Client.get_id_from_location_header(headers[:location]) get_transcription(id) end
[ "def", "create_transcription", "(", ")", "headers", "=", "@client", ".", "make_request", "(", ":post", ",", "@client", ".", "concat_user_path", "(", "\"#{RECORDING_PATH}/#{id}/transcriptions\"", ")", ",", "{", "}", ")", "[", "1", "]", "id", "=", "Client", ".", "get_id_from_location_header", "(", "headers", "[", ":location", "]", ")", "get_transcription", "(", "id", ")", "end" ]
Request the transcription process to be started for the given recording id. @return [Hash] created transcription @example transcription = recording.create_transcription()
[ "Request", "the", "transcription", "process", "to", "be", "started", "for", "the", "given", "recording", "id", "." ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/recording.rb#L38-L42
train
superp/rails-uploader
lib/uploader/authorization.rb
Uploader.Authorization.uploader_authorization_adapter
def uploader_authorization_adapter adapter = Uploader.authorization_adapter if adapter.is_a? String ActiveSupport::Dependencies.constantize(adapter) else adapter end end
ruby
def uploader_authorization_adapter adapter = Uploader.authorization_adapter if adapter.is_a? String ActiveSupport::Dependencies.constantize(adapter) else adapter end end
[ "def", "uploader_authorization_adapter", "adapter", "=", "Uploader", ".", "authorization_adapter", "if", "adapter", ".", "is_a?", "String", "ActiveSupport", "::", "Dependencies", ".", "constantize", "(", "adapter", ")", "else", "adapter", "end", "end" ]
Returns the class to be used as the authorization adapter
[ "Returns", "the", "class", "to", "be", "used", "as", "the", "authorization", "adapter" ]
5a37278ce77292d65b790995d2b4613688b8d7f1
https://github.com/superp/rails-uploader/blob/5a37278ce77292d65b790995d2b4613688b8d7f1/lib/uploader/authorization.rb#L36-L44
train
superp/rails-uploader
lib/uploader/fileupload_glue.rb
Uploader.FileuploadGlue.multiple?
def multiple?(method_name) return false if association(method_name).nil? name = association(method_name).respond_to?(:many?) ? :many? : :collection? association(method_name).send(name) end
ruby
def multiple?(method_name) return false if association(method_name).nil? name = association(method_name).respond_to?(:many?) ? :many? : :collection? association(method_name).send(name) end
[ "def", "multiple?", "(", "method_name", ")", "return", "false", "if", "association", "(", "method_name", ")", ".", "nil?", "name", "=", "association", "(", "method_name", ")", ".", "respond_to?", "(", ":many?", ")", "?", ":many?", ":", ":collection?", "association", "(", "method_name", ")", ".", "send", "(", "name", ")", "end" ]
many? for Mongoid and collection? for AR
[ "many?", "for", "Mongoid", "and", "collection?", "for", "AR" ]
5a37278ce77292d65b790995d2b4613688b8d7f1
https://github.com/superp/rails-uploader/blob/5a37278ce77292d65b790995d2b4613688b8d7f1/lib/uploader/fileupload_glue.rb#L58-L63
train
Bandwidth/ruby-bandwidth
lib/bandwidth/conference.rb
Bandwidth.Conference.create_member
def create_member(data) headers = @client.make_request(:post, @client.concat_user_path("#{CONFERENCE_PATH}/#{id}/members"), data)[1] id = Client.get_id_from_location_header(headers[:location]) get_member(id) end
ruby
def create_member(data) headers = @client.make_request(:post, @client.concat_user_path("#{CONFERENCE_PATH}/#{id}/members"), data)[1] id = Client.get_id_from_location_header(headers[:location]) get_member(id) end
[ "def", "create_member", "(", "data", ")", "headers", "=", "@client", ".", "make_request", "(", ":post", ",", "@client", ".", "concat_user_path", "(", "\"#{CONFERENCE_PATH}/#{id}/members\"", ")", ",", "data", ")", "[", "1", "]", "id", "=", "Client", ".", "get_id_from_location_header", "(", "headers", "[", ":location", "]", ")", "get_member", "(", "id", ")", "end" ]
Add a member to a conference. @param data [Hash] data to add member to a conference @return [ConferenceMember] created member @example member = conference.create_member(:call_id=>"id")
[ "Add", "a", "member", "to", "a", "conference", "." ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/conference.rb#L65-L69
train
Bandwidth/ruby-bandwidth
lib/bandwidth/conference.rb
Bandwidth.Conference.get_member
def get_member(member_id) member = ConferenceMember.new(@client.make_request(:get, @client.concat_user_path("#{CONFERENCE_PATH}/#{id}/members/#{member_id}"))[0], @client) member.conference_id = id member end
ruby
def get_member(member_id) member = ConferenceMember.new(@client.make_request(:get, @client.concat_user_path("#{CONFERENCE_PATH}/#{id}/members/#{member_id}"))[0], @client) member.conference_id = id member end
[ "def", "get_member", "(", "member_id", ")", "member", "=", "ConferenceMember", ".", "new", "(", "@client", ".", "make_request", "(", ":get", ",", "@client", ".", "concat_user_path", "(", "\"#{CONFERENCE_PATH}/#{id}/members/#{member_id}\"", ")", ")", "[", "0", "]", ",", "@client", ")", "member", ".", "conference_id", "=", "id", "member", "end" ]
Retrieve information about a particular conference member @param member_id [String] id of member @return [ConferenceMember] member information @example member = conference.get_member("id")
[ "Retrieve", "information", "about", "a", "particular", "conference", "member" ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/conference.rb#L76-L81
train
Bandwidth/ruby-bandwidth
lib/bandwidth/conference.rb
Bandwidth.Conference.get_members
def get_members() @client.make_request(:get, @client.concat_user_path("#{CONFERENCE_PATH}/#{id}/members"))[0].map do |i| member = ConferenceMember.new(i, @client) member.conference_id = id member end end
ruby
def get_members() @client.make_request(:get, @client.concat_user_path("#{CONFERENCE_PATH}/#{id}/members"))[0].map do |i| member = ConferenceMember.new(i, @client) member.conference_id = id member end end
[ "def", "get_members", "(", ")", "@client", ".", "make_request", "(", ":get", ",", "@client", ".", "concat_user_path", "(", "\"#{CONFERENCE_PATH}/#{id}/members\"", ")", ")", "[", "0", "]", ".", "map", "do", "|", "i", "|", "member", "=", "ConferenceMember", ".", "new", "(", "i", ",", "@client", ")", "member", ".", "conference_id", "=", "id", "member", "end", "end" ]
List all members from a conference @return [Array] array of ConferenceMember instances @example members = conference.get_members()
[ "List", "all", "members", "from", "a", "conference" ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/conference.rb#L87-L93
train
jabbrwcky/prawn-qrcode
lib/prawn/qrcode.rb
Prawn.QRCode.print_qr_code
def print_qr_code(content, level: :m, dot: DEFAULT_DOTSIZE, pos: [0,cursor], stroke: true, margin: 4, **options) qr_version = 0 dot_size = dot begin qr_version += 1 qr_code = RQRCode::QRCode.new(content, size: qr_version, level: level) dot = options[:extent] / (2*margin + qr_code.modules.length) if options[:extent] render_qr_code(qr_code, dot: dot, pos: pos, stroke: stroke, margin: margin, **options) rescue RQRCode::QRCodeRunTimeError if qr_version < 40 retry else raise end end end
ruby
def print_qr_code(content, level: :m, dot: DEFAULT_DOTSIZE, pos: [0,cursor], stroke: true, margin: 4, **options) qr_version = 0 dot_size = dot begin qr_version += 1 qr_code = RQRCode::QRCode.new(content, size: qr_version, level: level) dot = options[:extent] / (2*margin + qr_code.modules.length) if options[:extent] render_qr_code(qr_code, dot: dot, pos: pos, stroke: stroke, margin: margin, **options) rescue RQRCode::QRCodeRunTimeError if qr_version < 40 retry else raise end end end
[ "def", "print_qr_code", "(", "content", ",", "level", ":", ":m", ",", "dot", ":", "DEFAULT_DOTSIZE", ",", "pos", ":", "[", "0", ",", "cursor", "]", ",", "stroke", ":", "true", ",", "margin", ":", "4", ",", "**", "options", ")", "qr_version", "=", "0", "dot_size", "=", "dot", "begin", "qr_version", "+=", "1", "qr_code", "=", "RQRCode", "::", "QRCode", ".", "new", "(", "content", ",", "size", ":", "qr_version", ",", "level", ":", "level", ")", "dot", "=", "options", "[", ":extent", "]", "/", "(", "2", "*", "margin", "+", "qr_code", ".", "modules", ".", "length", ")", "if", "options", "[", ":extent", "]", "render_qr_code", "(", "qr_code", ",", "dot", ":", "dot", ",", "pos", ":", "pos", ",", "stroke", ":", "stroke", ",", "margin", ":", "margin", ",", "**", "options", ")", "rescue", "RQRCode", "::", "QRCodeRunTimeError", "if", "qr_version", "<", "40", "retry", "else", "raise", "end", "end", "end" ]
Prints a QR Code to the PDF document. The QR Code creation happens on the fly. content:: The string to render as content of the QR Code *options:: Named optional parameters +:level+:: Error correction level to use. One of: (:l,:m,:h,:q), Defaults to :m +:extent+:: Size of QR Code given in pt (1 pt == 1/72 in) +:pos+:: Two-element array containing the position at which the QR-Code should be rendered. Defaults to [0,cursor] +:dot+:: Size of QR Code module/dot. Calculated from extent or defaulting to 1pt +:stroke+:: boolean value whether to draw bounds around the QR Code. Defaults to true. +:margin+:: Size of margin around code in QR-Code modules/dots, Default to 4 +:align+:: Optional alignment within the current bounding box. Valid values are :left, :right, and :center. If set This option overrides the horizontal positioning specified in :pos. Defaults to nil. +:debug+:: Optional boolean, renders a coordinate grid around the QRCode if true (uses Prawn#stroke_axis)
[ "Prints", "a", "QR", "Code", "to", "the", "PDF", "document", ".", "The", "QR", "Code", "creation", "happens", "on", "the", "fly", "." ]
8616dda00cd1f4ef296e283e53793edb3f56bb1f
https://github.com/jabbrwcky/prawn-qrcode/blob/8616dda00cd1f4ef296e283e53793edb3f56bb1f/lib/prawn/qrcode.rb#L50-L67
train
Bandwidth/ruby-bandwidth
lib/bandwidth/domain.rb
Bandwidth.Domain.create_endpoint
def create_endpoint(data) headers = @client.make_request(:post, @client.concat_user_path("#{DOMAIN_PATH}/#{id}/endpoints"), data)[1] id = Client.get_id_from_location_header(headers[:location]) get_endpoint(id) end
ruby
def create_endpoint(data) headers = @client.make_request(:post, @client.concat_user_path("#{DOMAIN_PATH}/#{id}/endpoints"), data)[1] id = Client.get_id_from_location_header(headers[:location]) get_endpoint(id) end
[ "def", "create_endpoint", "(", "data", ")", "headers", "=", "@client", ".", "make_request", "(", ":post", ",", "@client", ".", "concat_user_path", "(", "\"#{DOMAIN_PATH}/#{id}/endpoints\"", ")", ",", "data", ")", "[", "1", "]", "id", "=", "Client", ".", "get_id_from_location_header", "(", "headers", "[", ":location", "]", ")", "get_endpoint", "(", "id", ")", "end" ]
Add a endpoint to a domain. @param data [Hash] data to add endpoint to a domain @return [EndPoint] created endpoint @example endpoint = domain.create_endpoint(:name=>"name", :application_id => "id")
[ "Add", "a", "endpoint", "to", "a", "domain", "." ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/domain.rb#L47-L51
train
Bandwidth/ruby-bandwidth
lib/bandwidth/domain.rb
Bandwidth.Domain.get_endpoint
def get_endpoint(endpoint_id) endpoint = EndPoint.new(@client.make_request(:get, @client.concat_user_path("#{DOMAIN_PATH}/#{id}/endpoints/#{endpoint_id}"))[0], @client) endpoint.domain_id = id endpoint end
ruby
def get_endpoint(endpoint_id) endpoint = EndPoint.new(@client.make_request(:get, @client.concat_user_path("#{DOMAIN_PATH}/#{id}/endpoints/#{endpoint_id}"))[0], @client) endpoint.domain_id = id endpoint end
[ "def", "get_endpoint", "(", "endpoint_id", ")", "endpoint", "=", "EndPoint", ".", "new", "(", "@client", ".", "make_request", "(", ":get", ",", "@client", ".", "concat_user_path", "(", "\"#{DOMAIN_PATH}/#{id}/endpoints/#{endpoint_id}\"", ")", ")", "[", "0", "]", ",", "@client", ")", "endpoint", ".", "domain_id", "=", "id", "endpoint", "end" ]
Retrieve information about an endpoint @param endpoint_id [String] id of endpoint @return [EndPoint] endpoint information @example endpoint = domain.get_endpoint("id")
[ "Retrieve", "information", "about", "an", "endpoint" ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/domain.rb#L58-L63
train
Bandwidth/ruby-bandwidth
lib/bandwidth/domain.rb
Bandwidth.Domain.get_endpoints
def get_endpoints(query = nil) @client.make_request(:get, @client.concat_user_path("#{DOMAIN_PATH}/#{id}/endpoints"), query)[0].map do |i| endpoint = EndPoint.new(i, @client) endpoint.domain_id = id endpoint end end
ruby
def get_endpoints(query = nil) @client.make_request(:get, @client.concat_user_path("#{DOMAIN_PATH}/#{id}/endpoints"), query)[0].map do |i| endpoint = EndPoint.new(i, @client) endpoint.domain_id = id endpoint end end
[ "def", "get_endpoints", "(", "query", "=", "nil", ")", "@client", ".", "make_request", "(", ":get", ",", "@client", ".", "concat_user_path", "(", "\"#{DOMAIN_PATH}/#{id}/endpoints\"", ")", ",", "query", ")", "[", "0", "]", ".", "map", "do", "|", "i", "|", "endpoint", "=", "EndPoint", ".", "new", "(", "i", ",", "@client", ")", "endpoint", ".", "domain_id", "=", "id", "endpoint", "end", "end" ]
List all endpoints from a domain @return [Array] array of EndPoint instances @example endpoints = domain.get_endpoints()
[ "List", "all", "endpoints", "from", "a", "domain" ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/domain.rb#L69-L75
train
Bandwidth/ruby-bandwidth
lib/bandwidth/domain.rb
Bandwidth.Domain.delete_endpoint
def delete_endpoint(endpoint_id) endpoint = EndPoint.new({:id => endpoint_id}, @client) endpoint.domain_id = id endpoint.delete() end
ruby
def delete_endpoint(endpoint_id) endpoint = EndPoint.new({:id => endpoint_id}, @client) endpoint.domain_id = id endpoint.delete() end
[ "def", "delete_endpoint", "(", "endpoint_id", ")", "endpoint", "=", "EndPoint", ".", "new", "(", "{", ":id", "=>", "endpoint_id", "}", ",", "@client", ")", "endpoint", ".", "domain_id", "=", "id", "endpoint", ".", "delete", "(", ")", "end" ]
Delete an endpoint @example domain.delete_endpoint("id")
[ "Delete", "an", "endpoint" ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/domain.rb#L80-L84
train
Bandwidth/ruby-bandwidth
lib/bandwidth/call.rb
Bandwidth.Call.create_gather
def create_gather(data) d = if data.is_a?(String) { :tag => id, :max_digits => 1, :prompt => {:locale => 'en_US', :gender => 'female', :sentence => data, :voice => 'kate', :bargeable => true } } else data end headers = @client.make_request(:post, @client.concat_user_path("#{CALL_PATH}/#{id}/gather"), d)[1] id = Client.get_id_from_location_header(headers[:location]) get_gather(id) end
ruby
def create_gather(data) d = if data.is_a?(String) { :tag => id, :max_digits => 1, :prompt => {:locale => 'en_US', :gender => 'female', :sentence => data, :voice => 'kate', :bargeable => true } } else data end headers = @client.make_request(:post, @client.concat_user_path("#{CALL_PATH}/#{id}/gather"), d)[1] id = Client.get_id_from_location_header(headers[:location]) get_gather(id) end
[ "def", "create_gather", "(", "data", ")", "d", "=", "if", "data", ".", "is_a?", "(", "String", ")", "{", ":tag", "=>", "id", ",", ":max_digits", "=>", "1", ",", ":prompt", "=>", "{", ":locale", "=>", "'en_US'", ",", ":gender", "=>", "'female'", ",", ":sentence", "=>", "data", ",", ":voice", "=>", "'kate'", ",", ":bargeable", "=>", "true", "}", "}", "else", "data", "end", "headers", "=", "@client", ".", "make_request", "(", ":post", ",", "@client", ".", "concat_user_path", "(", "\"#{CALL_PATH}/#{id}/gather\"", ")", ",", "d", ")", "[", "1", "]", "id", "=", "Client", ".", "get_id_from_location_header", "(", "headers", "[", ":location", "]", ")", "get_gather", "(", "id", ")", "end" ]
Gather the DTMF digits pressed @param data [String|Hash] sentence to speak on creating cather if string, otherwise it is hash with gather options @return [Hash] created gather @example gather = call.create_gather("Press a digit") gather = call.create_gather(:max_digits => 1, :prompt => {:sentence => "Press a digit", :bargeable => true })
[ "Gather", "the", "DTMF", "digits", "pressed" ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/call.rb#L81-L93
train
Bandwidth/ruby-bandwidth
lib/bandwidth/play_audio_extensions.rb
Bandwidth.PlayAudioExtensions.speak_sentence
def speak_sentence(sentence, tag = nil, gender = "female", voice = "kate") play_audio({:gender => gender || "female", :locale => "en_US", :voice => voice || "kate", :sentence => sentence, :tag => tag}) end
ruby
def speak_sentence(sentence, tag = nil, gender = "female", voice = "kate") play_audio({:gender => gender || "female", :locale => "en_US", :voice => voice || "kate", :sentence => sentence, :tag => tag}) end
[ "def", "speak_sentence", "(", "sentence", ",", "tag", "=", "nil", ",", "gender", "=", "\"female\"", ",", "voice", "=", "\"kate\"", ")", "play_audio", "(", "{", ":gender", "=>", "gender", "||", "\"female\"", ",", ":locale", "=>", "\"en_US\"", ",", ":voice", "=>", "voice", "||", "\"kate\"", ",", ":sentence", "=>", "sentence", ",", ":tag", "=>", "tag", "}", ")", "end" ]
Speak a sentence @param sentence [String[ sentence to speak @param tag [String] optional tag value @param gender [String] optional gender of voice @param voice [String] optional voice name
[ "Speak", "a", "sentence" ]
896df7a12e2992b5558514db943997d930ef416f
https://github.com/Bandwidth/ruby-bandwidth/blob/896df7a12e2992b5558514db943997d930ef416f/lib/bandwidth/play_audio_extensions.rb#L9-L12
train
projecttacoma/cqm-parsers
lib/hqmf-parser/cql/document.rb
HQMF2CQL.Document.extract_criteria
def extract_criteria # Grab each data criteria entry from the HQMF extracted_data_criteria = [] @doc.xpath('cda:QualityMeasureDocument/cda:component/cda:dataCriteriaSection/cda:entry', NAMESPACES).each do |entry| extracted_data_criteria << entry dc = HQMF2CQL::DataCriteria.new(entry) # Create new data criteria sdc = dc.clone # Clone data criteria sdc.id += '_source' # Make it a source @data_criteria << dc @source_data_criteria << sdc end make_positive_entry end
ruby
def extract_criteria # Grab each data criteria entry from the HQMF extracted_data_criteria = [] @doc.xpath('cda:QualityMeasureDocument/cda:component/cda:dataCriteriaSection/cda:entry', NAMESPACES).each do |entry| extracted_data_criteria << entry dc = HQMF2CQL::DataCriteria.new(entry) # Create new data criteria sdc = dc.clone # Clone data criteria sdc.id += '_source' # Make it a source @data_criteria << dc @source_data_criteria << sdc end make_positive_entry end
[ "def", "extract_criteria", "extracted_data_criteria", "=", "[", "]", "@doc", ".", "xpath", "(", "'cda:QualityMeasureDocument/cda:component/cda:dataCriteriaSection/cda:entry'", ",", "NAMESPACES", ")", ".", "each", "do", "|", "entry", "|", "extracted_data_criteria", "<<", "entry", "dc", "=", "HQMF2CQL", "::", "DataCriteria", ".", "new", "(", "entry", ")", "sdc", "=", "dc", ".", "clone", "sdc", ".", "id", "+=", "'_source'", "@data_criteria", "<<", "dc", "@source_data_criteria", "<<", "sdc", "end", "make_positive_entry", "end" ]
Extracts data criteria from the HQMF document.
[ "Extracts", "data", "criteria", "from", "the", "HQMF", "document", "." ]
8ac8a7afcf299def0e652286dce06a7bd8c1de94
https://github.com/projecttacoma/cqm-parsers/blob/8ac8a7afcf299def0e652286dce06a7bd8c1de94/lib/hqmf-parser/cql/document.rb#L33-L46
train
projecttacoma/cqm-parsers
lib/hqmf-parser/cql/document.rb
HQMF2CQL.Document.make_positive_entry
def make_positive_entry negated_criteria = [] data_criteria_index_lookup = [] # Find the criteria that are negated # At the same time build a hash of all criteria and their code_list_id, definition, status, and negation status @data_criteria.each_with_index do |criterion, source_index| negated_criteria << criterion if criterion.negation data_criteria_index_lookup << [criterion.code_list_id, criterion.definition, criterion.status, criterion.negation] end negated_criteria.each do |criterion| # Check if there is a criterion with the same OID, definition and status BUT that isn't negated unless data_criteria_index_lookup.include?([criterion.code_list_id, criterion.definition, criterion.status, false]) spoofed_positive_instance = criterion.clone spoofed_positive_instance.make_criterion_positive @data_criteria << spoofed_positive_instance sdc = spoofed_positive_instance.clone sdc.id += '_source' @source_data_criteria << sdc end end end
ruby
def make_positive_entry negated_criteria = [] data_criteria_index_lookup = [] # Find the criteria that are negated # At the same time build a hash of all criteria and their code_list_id, definition, status, and negation status @data_criteria.each_with_index do |criterion, source_index| negated_criteria << criterion if criterion.negation data_criteria_index_lookup << [criterion.code_list_id, criterion.definition, criterion.status, criterion.negation] end negated_criteria.each do |criterion| # Check if there is a criterion with the same OID, definition and status BUT that isn't negated unless data_criteria_index_lookup.include?([criterion.code_list_id, criterion.definition, criterion.status, false]) spoofed_positive_instance = criterion.clone spoofed_positive_instance.make_criterion_positive @data_criteria << spoofed_positive_instance sdc = spoofed_positive_instance.clone sdc.id += '_source' @source_data_criteria << sdc end end end
[ "def", "make_positive_entry", "negated_criteria", "=", "[", "]", "data_criteria_index_lookup", "=", "[", "]", "@data_criteria", ".", "each_with_index", "do", "|", "criterion", ",", "source_index", "|", "negated_criteria", "<<", "criterion", "if", "criterion", ".", "negation", "data_criteria_index_lookup", "<<", "[", "criterion", ".", "code_list_id", ",", "criterion", ".", "definition", ",", "criterion", ".", "status", ",", "criterion", ".", "negation", "]", "end", "negated_criteria", ".", "each", "do", "|", "criterion", "|", "unless", "data_criteria_index_lookup", ".", "include?", "(", "[", "criterion", ".", "code_list_id", ",", "criterion", ".", "definition", ",", "criterion", ".", "status", ",", "false", "]", ")", "spoofed_positive_instance", "=", "criterion", ".", "clone", "spoofed_positive_instance", ".", "make_criterion_positive", "@data_criteria", "<<", "spoofed_positive_instance", "sdc", "=", "spoofed_positive_instance", ".", "clone", "sdc", ".", "id", "+=", "'_source'", "@source_data_criteria", "<<", "sdc", "end", "end", "end" ]
This method is needed for situations when there is a only a negated version of a data criteria. Bonnie will only show the affirmative version of data criteria. This method will create an affirmative version of a data criteria when there is only the negative one in the HQMF.
[ "This", "method", "is", "needed", "for", "situations", "when", "there", "is", "a", "only", "a", "negated", "version", "of", "a", "data", "criteria", ".", "Bonnie", "will", "only", "show", "the", "affirmative", "version", "of", "data", "criteria", ".", "This", "method", "will", "create", "an", "affirmative", "version", "of", "a", "data", "criteria", "when", "there", "is", "only", "the", "negative", "one", "in", "the", "HQMF", "." ]
8ac8a7afcf299def0e652286dce06a7bd8c1de94
https://github.com/projecttacoma/cqm-parsers/blob/8ac8a7afcf299def0e652286dce06a7bd8c1de94/lib/hqmf-parser/cql/document.rb#L53-L75
train
projecttacoma/cqm-parsers
lib/measure-loader/cql_loader.rb
Measures.CqlLoader.extract_measures
def extract_measures measure_files = MATMeasureFiles.create_from_zip_file(@measure_zip) measures = [] if measure_files.components.present? measure, component_measures = create_measure_and_components(measure_files) measures.push(*component_measures) else measure = create_measure(measure_files) end measure.package = CQM::MeasurePackage.new(file: BSON::Binary.new(@measure_zip.read)) measures << measure measures.each { |m| CqlLoader.update_population_set_and_strat_titles(m, @measure_details[:population_titles]) } return measures end
ruby
def extract_measures measure_files = MATMeasureFiles.create_from_zip_file(@measure_zip) measures = [] if measure_files.components.present? measure, component_measures = create_measure_and_components(measure_files) measures.push(*component_measures) else measure = create_measure(measure_files) end measure.package = CQM::MeasurePackage.new(file: BSON::Binary.new(@measure_zip.read)) measures << measure measures.each { |m| CqlLoader.update_population_set_and_strat_titles(m, @measure_details[:population_titles]) } return measures end
[ "def", "extract_measures", "measure_files", "=", "MATMeasureFiles", ".", "create_from_zip_file", "(", "@measure_zip", ")", "measures", "=", "[", "]", "if", "measure_files", ".", "components", ".", "present?", "measure", ",", "component_measures", "=", "create_measure_and_components", "(", "measure_files", ")", "measures", ".", "push", "(", "*", "component_measures", ")", "else", "measure", "=", "create_measure", "(", "measure_files", ")", "end", "measure", ".", "package", "=", "CQM", "::", "MeasurePackage", ".", "new", "(", "file", ":", "BSON", "::", "Binary", ".", "new", "(", "@measure_zip", ".", "read", ")", ")", "measures", "<<", "measure", "measures", ".", "each", "{", "|", "m", "|", "CqlLoader", ".", "update_population_set_and_strat_titles", "(", "m", ",", "@measure_details", "[", ":population_titles", "]", ")", "}", "return", "measures", "end" ]
Returns an array of measures, will contain a single measure if it is a non-composite measure
[ "Returns", "an", "array", "of", "measures", "will", "contain", "a", "single", "measure", "if", "it", "is", "a", "non", "-", "composite", "measure" ]
8ac8a7afcf299def0e652286dce06a7bd8c1de94
https://github.com/projecttacoma/cqm-parsers/blob/8ac8a7afcf299def0e652286dce06a7bd8c1de94/lib/measure-loader/cql_loader.rb#L13-L28
train
projecttacoma/cqm-parsers
lib/measure-loader/cql_loader.rb
Measures.CqlLoader.create_measure
def create_measure(measure_files) hqmf_xml = measure_files.hqmf_xml # update the valueset info in each elm (update version and remove urn:oid) measure_files.cql_libraries.each { |cql_lib_files| modify_elm_valueset_information(cql_lib_files.elm) } measure = CQM::Measure.new(HQMFMeasureLoader.extract_fields(hqmf_xml)) measure.cql_libraries = create_cql_libraries(measure_files.cql_libraries, measure.main_cql_library) measure.composite = measure_files.components.present? measure.calculation_method = @measure_details[:episode_of_care] ? 'EPISODE_OF_CARE' : 'PATIENT' measure.calculate_sdes = @measure_details[:calculate_sdes] hqmf_model = HQMF::Parser::V2CQLParser.new.parse(hqmf_xml) # TODO: move away from using V2CQLParser elms = measure.cql_libraries.map(&:elm) elm_valuesets = ValueSetHelpers.unique_list_of_valuesets_referenced_by_elms(elms) verify_hqmf_valuesets_match_elm_valuesets(elm_valuesets, hqmf_model) value_sets_from_single_code_references = ValueSetHelpers.make_fake_valuesets_from_single_code_references(elms, @vs_model_cache) measure.source_data_criteria = SourceDataCriteriaLoader.new(hqmf_xml, value_sets_from_single_code_references).extract_data_criteria measure.value_sets = value_sets_from_single_code_references measure.value_sets.concat(@value_set_loader.retrieve_and_modelize_value_sets_from_vsac(elm_valuesets)) if @value_set_loader.present? ## this to_json is needed, it doesn't actually produce json, it just makes a hash that is better ## suited for our uses (e.g. source_data_criteria goes from an array to a hash keyed by id) hqmf_model_hash = hqmf_model.to_json.deep_symbolize_keys! HQMFMeasureLoader.add_fields_from_hqmf_model_hash(measure, hqmf_model_hash) return measure end
ruby
def create_measure(measure_files) hqmf_xml = measure_files.hqmf_xml # update the valueset info in each elm (update version and remove urn:oid) measure_files.cql_libraries.each { |cql_lib_files| modify_elm_valueset_information(cql_lib_files.elm) } measure = CQM::Measure.new(HQMFMeasureLoader.extract_fields(hqmf_xml)) measure.cql_libraries = create_cql_libraries(measure_files.cql_libraries, measure.main_cql_library) measure.composite = measure_files.components.present? measure.calculation_method = @measure_details[:episode_of_care] ? 'EPISODE_OF_CARE' : 'PATIENT' measure.calculate_sdes = @measure_details[:calculate_sdes] hqmf_model = HQMF::Parser::V2CQLParser.new.parse(hqmf_xml) # TODO: move away from using V2CQLParser elms = measure.cql_libraries.map(&:elm) elm_valuesets = ValueSetHelpers.unique_list_of_valuesets_referenced_by_elms(elms) verify_hqmf_valuesets_match_elm_valuesets(elm_valuesets, hqmf_model) value_sets_from_single_code_references = ValueSetHelpers.make_fake_valuesets_from_single_code_references(elms, @vs_model_cache) measure.source_data_criteria = SourceDataCriteriaLoader.new(hqmf_xml, value_sets_from_single_code_references).extract_data_criteria measure.value_sets = value_sets_from_single_code_references measure.value_sets.concat(@value_set_loader.retrieve_and_modelize_value_sets_from_vsac(elm_valuesets)) if @value_set_loader.present? ## this to_json is needed, it doesn't actually produce json, it just makes a hash that is better ## suited for our uses (e.g. source_data_criteria goes from an array to a hash keyed by id) hqmf_model_hash = hqmf_model.to_json.deep_symbolize_keys! HQMFMeasureLoader.add_fields_from_hqmf_model_hash(measure, hqmf_model_hash) return measure end
[ "def", "create_measure", "(", "measure_files", ")", "hqmf_xml", "=", "measure_files", ".", "hqmf_xml", "measure_files", ".", "cql_libraries", ".", "each", "{", "|", "cql_lib_files", "|", "modify_elm_valueset_information", "(", "cql_lib_files", ".", "elm", ")", "}", "measure", "=", "CQM", "::", "Measure", ".", "new", "(", "HQMFMeasureLoader", ".", "extract_fields", "(", "hqmf_xml", ")", ")", "measure", ".", "cql_libraries", "=", "create_cql_libraries", "(", "measure_files", ".", "cql_libraries", ",", "measure", ".", "main_cql_library", ")", "measure", ".", "composite", "=", "measure_files", ".", "components", ".", "present?", "measure", ".", "calculation_method", "=", "@measure_details", "[", ":episode_of_care", "]", "?", "'EPISODE_OF_CARE'", ":", "'PATIENT'", "measure", ".", "calculate_sdes", "=", "@measure_details", "[", ":calculate_sdes", "]", "hqmf_model", "=", "HQMF", "::", "Parser", "::", "V2CQLParser", ".", "new", ".", "parse", "(", "hqmf_xml", ")", "elms", "=", "measure", ".", "cql_libraries", ".", "map", "(", "&", ":elm", ")", "elm_valuesets", "=", "ValueSetHelpers", ".", "unique_list_of_valuesets_referenced_by_elms", "(", "elms", ")", "verify_hqmf_valuesets_match_elm_valuesets", "(", "elm_valuesets", ",", "hqmf_model", ")", "value_sets_from_single_code_references", "=", "ValueSetHelpers", ".", "make_fake_valuesets_from_single_code_references", "(", "elms", ",", "@vs_model_cache", ")", "measure", ".", "source_data_criteria", "=", "SourceDataCriteriaLoader", ".", "new", "(", "hqmf_xml", ",", "value_sets_from_single_code_references", ")", ".", "extract_data_criteria", "measure", ".", "value_sets", "=", "value_sets_from_single_code_references", "measure", ".", "value_sets", ".", "concat", "(", "@value_set_loader", ".", "retrieve_and_modelize_value_sets_from_vsac", "(", "elm_valuesets", ")", ")", "if", "@value_set_loader", ".", "present?", "hqmf_model_hash", "=", "hqmf_model", ".", "to_json", ".", "deep_symbolize_keys!", "HQMFMeasureLoader", ".", "add_fields_from_hqmf_model_hash", "(", "measure", ",", "hqmf_model_hash", ")", "return", "measure", "end" ]
Creates and returns a measure
[ "Creates", "and", "returns", "a", "measure" ]
8ac8a7afcf299def0e652286dce06a7bd8c1de94
https://github.com/projecttacoma/cqm-parsers/blob/8ac8a7afcf299def0e652286dce06a7bd8c1de94/lib/measure-loader/cql_loader.rb#L91-L119
train
projecttacoma/cqm-parsers
lib/hqmf-parser/2.0/data_criteria.rb
HQMF2.DataCriteria.retrieve_code_system_for_model
def retrieve_code_system_for_model code_system = attr_val("#{@code_list_xpath}/@codeSystem") if code_system code_system_name = HQMF::Util::CodeSystemHelper.code_system_for(code_system) else code_system_name = attr_val("#{@code_list_xpath}/@codeSystemName") end code_value = attr_val("#{@code_list_xpath}/@code") { code_system_name => [code_value] } if code_system_name && code_value end
ruby
def retrieve_code_system_for_model code_system = attr_val("#{@code_list_xpath}/@codeSystem") if code_system code_system_name = HQMF::Util::CodeSystemHelper.code_system_for(code_system) else code_system_name = attr_val("#{@code_list_xpath}/@codeSystemName") end code_value = attr_val("#{@code_list_xpath}/@code") { code_system_name => [code_value] } if code_system_name && code_value end
[ "def", "retrieve_code_system_for_model", "code_system", "=", "attr_val", "(", "\"#{@code_list_xpath}/@codeSystem\"", ")", "if", "code_system", "code_system_name", "=", "HQMF", "::", "Util", "::", "CodeSystemHelper", ".", "code_system_for", "(", "code_system", ")", "else", "code_system_name", "=", "attr_val", "(", "\"#{@code_list_xpath}/@codeSystemName\"", ")", "end", "code_value", "=", "attr_val", "(", "\"#{@code_list_xpath}/@code\"", ")", "{", "code_system_name", "=>", "[", "code_value", "]", "}", "if", "code_system_name", "&&", "code_value", "end" ]
Extract the code system from the xml taht the document should use
[ "Extract", "the", "code", "system", "from", "the", "xml", "taht", "the", "document", "should", "use" ]
8ac8a7afcf299def0e652286dce06a7bd8c1de94
https://github.com/projecttacoma/cqm-parsers/blob/8ac8a7afcf299def0e652286dce06a7bd8c1de94/lib/hqmf-parser/2.0/data_criteria.rb#L223-L232
train
projecttacoma/cqm-parsers
lib/hqmf-parser/2.0/document.rb
HQMF2.Document.read_attribute
def read_attribute(attribute) id = attribute.at_xpath('./cda:id/@root', NAMESPACES).try(:value) code = attribute.at_xpath('./cda:code/@code', NAMESPACES).try(:value) name = attribute.at_xpath('./cda:code/cda:displayName/@value', NAMESPACES).try(:value) value = attribute.at_xpath('./cda:value/@value', NAMESPACES).try(:value) id_obj = nil if attribute.at_xpath('./cda:id', NAMESPACES) id_obj = HQMF::Identifier.new(attribute.at_xpath('./cda:id/@xsi:type', NAMESPACES).try(:value), id, attribute.at_xpath('./cda:id/@extension', NAMESPACES).try(:value)) end code_obj = nil if attribute.at_xpath('./cda:code', NAMESPACES) code_obj, null_flavor, o_text = handle_attribute_code(attribute, code, name) # Mapping for nil values to align with 1.0 parsing code = null_flavor if code.nil? name = o_text if name.nil? end value_obj = nil value_obj = handle_attribute_value(attribute, value) if attribute.at_xpath('./cda:value', NAMESPACES) # Handle the cms_id - changed to eCQM in MAT 5.4 (QDM 5.3) @cms_id = "CMS#{value}v#{@hqmf_version_number.to_i}" if name&.start_with?('eMeasure Identifier', 'eCQM Identifier') HQMF::Attribute.new(id, code, value, nil, name, id_obj, code_obj, value_obj) end
ruby
def read_attribute(attribute) id = attribute.at_xpath('./cda:id/@root', NAMESPACES).try(:value) code = attribute.at_xpath('./cda:code/@code', NAMESPACES).try(:value) name = attribute.at_xpath('./cda:code/cda:displayName/@value', NAMESPACES).try(:value) value = attribute.at_xpath('./cda:value/@value', NAMESPACES).try(:value) id_obj = nil if attribute.at_xpath('./cda:id', NAMESPACES) id_obj = HQMF::Identifier.new(attribute.at_xpath('./cda:id/@xsi:type', NAMESPACES).try(:value), id, attribute.at_xpath('./cda:id/@extension', NAMESPACES).try(:value)) end code_obj = nil if attribute.at_xpath('./cda:code', NAMESPACES) code_obj, null_flavor, o_text = handle_attribute_code(attribute, code, name) # Mapping for nil values to align with 1.0 parsing code = null_flavor if code.nil? name = o_text if name.nil? end value_obj = nil value_obj = handle_attribute_value(attribute, value) if attribute.at_xpath('./cda:value', NAMESPACES) # Handle the cms_id - changed to eCQM in MAT 5.4 (QDM 5.3) @cms_id = "CMS#{value}v#{@hqmf_version_number.to_i}" if name&.start_with?('eMeasure Identifier', 'eCQM Identifier') HQMF::Attribute.new(id, code, value, nil, name, id_obj, code_obj, value_obj) end
[ "def", "read_attribute", "(", "attribute", ")", "id", "=", "attribute", ".", "at_xpath", "(", "'./cda:id/@root'", ",", "NAMESPACES", ")", ".", "try", "(", ":value", ")", "code", "=", "attribute", ".", "at_xpath", "(", "'./cda:code/@code'", ",", "NAMESPACES", ")", ".", "try", "(", ":value", ")", "name", "=", "attribute", ".", "at_xpath", "(", "'./cda:code/cda:displayName/@value'", ",", "NAMESPACES", ")", ".", "try", "(", ":value", ")", "value", "=", "attribute", ".", "at_xpath", "(", "'./cda:value/@value'", ",", "NAMESPACES", ")", ".", "try", "(", ":value", ")", "id_obj", "=", "nil", "if", "attribute", ".", "at_xpath", "(", "'./cda:id'", ",", "NAMESPACES", ")", "id_obj", "=", "HQMF", "::", "Identifier", ".", "new", "(", "attribute", ".", "at_xpath", "(", "'./cda:id/@xsi:type'", ",", "NAMESPACES", ")", ".", "try", "(", ":value", ")", ",", "id", ",", "attribute", ".", "at_xpath", "(", "'./cda:id/@extension'", ",", "NAMESPACES", ")", ".", "try", "(", ":value", ")", ")", "end", "code_obj", "=", "nil", "if", "attribute", ".", "at_xpath", "(", "'./cda:code'", ",", "NAMESPACES", ")", "code_obj", ",", "null_flavor", ",", "o_text", "=", "handle_attribute_code", "(", "attribute", ",", "code", ",", "name", ")", "code", "=", "null_flavor", "if", "code", ".", "nil?", "name", "=", "o_text", "if", "name", ".", "nil?", "end", "value_obj", "=", "nil", "value_obj", "=", "handle_attribute_value", "(", "attribute", ",", "value", ")", "if", "attribute", ".", "at_xpath", "(", "'./cda:value'", ",", "NAMESPACES", ")", "@cms_id", "=", "\"CMS#{value}v#{@hqmf_version_number.to_i}\"", "if", "name", "&.", "start_with?", "(", "'eMeasure Identifier'", ",", "'eCQM Identifier'", ")", "HQMF", "::", "Attribute", ".", "new", "(", "id", ",", "code", ",", "value", ",", "nil", ",", "name", ",", "id_obj", ",", "code_obj", ",", "value_obj", ")", "end" ]
Handles parsing the attributes of the document
[ "Handles", "parsing", "the", "attributes", "of", "the", "document" ]
8ac8a7afcf299def0e652286dce06a7bd8c1de94
https://github.com/projecttacoma/cqm-parsers/blob/8ac8a7afcf299def0e652286dce06a7bd8c1de94/lib/hqmf-parser/2.0/document.rb#L168-L198
train
projecttacoma/cqm-parsers
lib/hqmf-parser/cql/document_helpers/doc_population_helper.rb
HQMF2CQL.DocumentPopulationHelper.extract_populations_cql_map
def extract_populations_cql_map populations_cql_map = {} @doc.xpath("//cda:populationCriteriaSection/cda:component[@typeCode='COMP']", HQMF2::Document::NAMESPACES).each do |population_def| { HQMF::PopulationCriteria::IPP => 'initialPopulationCriteria', HQMF::PopulationCriteria::DENOM => 'denominatorCriteria', HQMF::PopulationCriteria::NUMER => 'numeratorCriteria', HQMF::PopulationCriteria::NUMEX => 'numeratorExclusionCriteria', HQMF::PopulationCriteria::DENEXCEP => 'denominatorExceptionCriteria', HQMF::PopulationCriteria::DENEX => 'denominatorExclusionCriteria', HQMF::PopulationCriteria::MSRPOPL => 'measurePopulationCriteria', HQMF::PopulationCriteria::MSRPOPLEX => 'measurePopulationExclusionCriteria', HQMF::PopulationCriteria::STRAT => 'stratifierCriteria' }.each_pair do |criteria_id, criteria_element_name| criteria_def = population_def.at_xpath("cda:#{criteria_element_name}", HQMF2::Document::NAMESPACES) if criteria_def # Ignore Supplemental Data Elements next if HQMF::PopulationCriteria::STRAT == criteria_id && !criteria_def.xpath("cda:component[@typeCode='COMP']/cda:measureAttribute/cda:code[@code='SDE']").empty? cql_statement = criteria_def.at_xpath("*/*/cda:id", HQMF2::Document::NAMESPACES).attribute('extension').to_s.match(/"([^"]*)"/) if populations_cql_map[criteria_id].nil? populations_cql_map[criteria_id] = [] end cql_statement = cql_statement.to_s.delete('\\"') populations_cql_map[criteria_id].push cql_statement end end end populations_cql_map end
ruby
def extract_populations_cql_map populations_cql_map = {} @doc.xpath("//cda:populationCriteriaSection/cda:component[@typeCode='COMP']", HQMF2::Document::NAMESPACES).each do |population_def| { HQMF::PopulationCriteria::IPP => 'initialPopulationCriteria', HQMF::PopulationCriteria::DENOM => 'denominatorCriteria', HQMF::PopulationCriteria::NUMER => 'numeratorCriteria', HQMF::PopulationCriteria::NUMEX => 'numeratorExclusionCriteria', HQMF::PopulationCriteria::DENEXCEP => 'denominatorExceptionCriteria', HQMF::PopulationCriteria::DENEX => 'denominatorExclusionCriteria', HQMF::PopulationCriteria::MSRPOPL => 'measurePopulationCriteria', HQMF::PopulationCriteria::MSRPOPLEX => 'measurePopulationExclusionCriteria', HQMF::PopulationCriteria::STRAT => 'stratifierCriteria' }.each_pair do |criteria_id, criteria_element_name| criteria_def = population_def.at_xpath("cda:#{criteria_element_name}", HQMF2::Document::NAMESPACES) if criteria_def # Ignore Supplemental Data Elements next if HQMF::PopulationCriteria::STRAT == criteria_id && !criteria_def.xpath("cda:component[@typeCode='COMP']/cda:measureAttribute/cda:code[@code='SDE']").empty? cql_statement = criteria_def.at_xpath("*/*/cda:id", HQMF2::Document::NAMESPACES).attribute('extension').to_s.match(/"([^"]*)"/) if populations_cql_map[criteria_id].nil? populations_cql_map[criteria_id] = [] end cql_statement = cql_statement.to_s.delete('\\"') populations_cql_map[criteria_id].push cql_statement end end end populations_cql_map end
[ "def", "extract_populations_cql_map", "populations_cql_map", "=", "{", "}", "@doc", ".", "xpath", "(", "\"//cda:populationCriteriaSection/cda:component[@typeCode='COMP']\"", ",", "HQMF2", "::", "Document", "::", "NAMESPACES", ")", ".", "each", "do", "|", "population_def", "|", "{", "HQMF", "::", "PopulationCriteria", "::", "IPP", "=>", "'initialPopulationCriteria'", ",", "HQMF", "::", "PopulationCriteria", "::", "DENOM", "=>", "'denominatorCriteria'", ",", "HQMF", "::", "PopulationCriteria", "::", "NUMER", "=>", "'numeratorCriteria'", ",", "HQMF", "::", "PopulationCriteria", "::", "NUMEX", "=>", "'numeratorExclusionCriteria'", ",", "HQMF", "::", "PopulationCriteria", "::", "DENEXCEP", "=>", "'denominatorExceptionCriteria'", ",", "HQMF", "::", "PopulationCriteria", "::", "DENEX", "=>", "'denominatorExclusionCriteria'", ",", "HQMF", "::", "PopulationCriteria", "::", "MSRPOPL", "=>", "'measurePopulationCriteria'", ",", "HQMF", "::", "PopulationCriteria", "::", "MSRPOPLEX", "=>", "'measurePopulationExclusionCriteria'", ",", "HQMF", "::", "PopulationCriteria", "::", "STRAT", "=>", "'stratifierCriteria'", "}", ".", "each_pair", "do", "|", "criteria_id", ",", "criteria_element_name", "|", "criteria_def", "=", "population_def", ".", "at_xpath", "(", "\"cda:#{criteria_element_name}\"", ",", "HQMF2", "::", "Document", "::", "NAMESPACES", ")", "if", "criteria_def", "next", "if", "HQMF", "::", "PopulationCriteria", "::", "STRAT", "==", "criteria_id", "&&", "!", "criteria_def", ".", "xpath", "(", "\"cda:component[@typeCode='COMP']/cda:measureAttribute/cda:code[@code='SDE']\"", ")", ".", "empty?", "cql_statement", "=", "criteria_def", ".", "at_xpath", "(", "\"*/*/cda:id\"", ",", "HQMF2", "::", "Document", "::", "NAMESPACES", ")", ".", "attribute", "(", "'extension'", ")", ".", "to_s", ".", "match", "(", "/", "/", ")", "if", "populations_cql_map", "[", "criteria_id", "]", ".", "nil?", "populations_cql_map", "[", "criteria_id", "]", "=", "[", "]", "end", "cql_statement", "=", "cql_statement", ".", "to_s", ".", "delete", "(", "'\\\\\"'", ")", "populations_cql_map", "[", "criteria_id", "]", ".", "push", "cql_statement", "end", "end", "end", "populations_cql_map", "end" ]
Extracts the mappings between actual HQMF populations and their corresponding CQL define statements.
[ "Extracts", "the", "mappings", "between", "actual", "HQMF", "populations", "and", "their", "corresponding", "CQL", "define", "statements", "." ]
8ac8a7afcf299def0e652286dce06a7bd8c1de94
https://github.com/projecttacoma/cqm-parsers/blob/8ac8a7afcf299def0e652286dce06a7bd8c1de94/lib/hqmf-parser/cql/document_helpers/doc_population_helper.rb#L89-L118
train
projecttacoma/cqm-parsers
lib/hqmf-parser/cql/document_helpers/doc_population_helper.rb
HQMF2CQL.DocumentPopulationHelper.extract_main_library
def extract_main_library population_criteria_sections = @doc.xpath("//cda:populationCriteriaSection/cda:component[@typeCode='COMP']", HQMF2::Document::NAMESPACES) criteria_section = population_criteria_sections.at_xpath("cda:initialPopulationCriteria", HQMF2::Document::NAMESPACES) if criteria_section # Example: the full name for the population criteria section is "BonnieNesting01.\"Initial Population\"" # The regex returns everything before the "." (BonnieNesting01), which is the file name of the cql measure cql_main_library_name = criteria_section.at_xpath("*/*/cda:id", HQMF2::Document::NAMESPACES).attribute('extension').to_s.match(/[^.]*/).to_s else nil end end
ruby
def extract_main_library population_criteria_sections = @doc.xpath("//cda:populationCriteriaSection/cda:component[@typeCode='COMP']", HQMF2::Document::NAMESPACES) criteria_section = population_criteria_sections.at_xpath("cda:initialPopulationCriteria", HQMF2::Document::NAMESPACES) if criteria_section # Example: the full name for the population criteria section is "BonnieNesting01.\"Initial Population\"" # The regex returns everything before the "." (BonnieNesting01), which is the file name of the cql measure cql_main_library_name = criteria_section.at_xpath("*/*/cda:id", HQMF2::Document::NAMESPACES).attribute('extension').to_s.match(/[^.]*/).to_s else nil end end
[ "def", "extract_main_library", "population_criteria_sections", "=", "@doc", ".", "xpath", "(", "\"//cda:populationCriteriaSection/cda:component[@typeCode='COMP']\"", ",", "HQMF2", "::", "Document", "::", "NAMESPACES", ")", "criteria_section", "=", "population_criteria_sections", ".", "at_xpath", "(", "\"cda:initialPopulationCriteria\"", ",", "HQMF2", "::", "Document", "::", "NAMESPACES", ")", "if", "criteria_section", "cql_main_library_name", "=", "criteria_section", ".", "at_xpath", "(", "\"*/*/cda:id\"", ",", "HQMF2", "::", "Document", "::", "NAMESPACES", ")", ".", "attribute", "(", "'extension'", ")", ".", "to_s", ".", "match", "(", "/", "/", ")", ".", "to_s", "else", "nil", "end", "end" ]
Extracts the name of the main cql library from the Population Criteria Section.
[ "Extracts", "the", "name", "of", "the", "main", "cql", "library", "from", "the", "Population", "Criteria", "Section", "." ]
8ac8a7afcf299def0e652286dce06a7bd8c1de94
https://github.com/projecttacoma/cqm-parsers/blob/8ac8a7afcf299def0e652286dce06a7bd8c1de94/lib/hqmf-parser/cql/document_helpers/doc_population_helper.rb#L121-L131
train
projecttacoma/cqm-parsers
lib/hqmf-parser/cql/data_criteria.rb
HQMF2CQL.DataCriteria.title
def title disp_value = attr_val("#{@code_list_xpath}/cda:displayName/@value") # Attempt to pull display value from the localVariableName for # MAT 5.3+ exports that appear to no longer include displayName for # code entries. # NOTE: A long term replacement for this and for other portions of the # parsing process should involve reaching out to VSAC for oid information # pulled from the CQL, and then to use that information while parsing. unless disp_value.present? # Grab the localVariableName from the XML disp_value = attr_val('./cda:localVariableName/@value') # Grab everything before the first underscore disp_value = disp_value.partition('_').first unless disp_value.nil? end @title || disp_value || @description || id # allow defined titles to take precedence end
ruby
def title disp_value = attr_val("#{@code_list_xpath}/cda:displayName/@value") # Attempt to pull display value from the localVariableName for # MAT 5.3+ exports that appear to no longer include displayName for # code entries. # NOTE: A long term replacement for this and for other portions of the # parsing process should involve reaching out to VSAC for oid information # pulled from the CQL, and then to use that information while parsing. unless disp_value.present? # Grab the localVariableName from the XML disp_value = attr_val('./cda:localVariableName/@value') # Grab everything before the first underscore disp_value = disp_value.partition('_').first unless disp_value.nil? end @title || disp_value || @description || id # allow defined titles to take precedence end
[ "def", "title", "disp_value", "=", "attr_val", "(", "\"#{@code_list_xpath}/cda:displayName/@value\"", ")", "unless", "disp_value", ".", "present?", "disp_value", "=", "attr_val", "(", "'./cda:localVariableName/@value'", ")", "disp_value", "=", "disp_value", ".", "partition", "(", "'_'", ")", ".", "first", "unless", "disp_value", ".", "nil?", "end", "@title", "||", "disp_value", "||", "@description", "||", "id", "end" ]
Get the title of the criteria, provides a human readable description @return [String] the title of this data criteria
[ "Get", "the", "title", "of", "the", "criteria", "provides", "a", "human", "readable", "description" ]
8ac8a7afcf299def0e652286dce06a7bd8c1de94
https://github.com/projecttacoma/cqm-parsers/blob/8ac8a7afcf299def0e652286dce06a7bd8c1de94/lib/hqmf-parser/cql/data_criteria.rb#L8-L23
train
lanrion/weixin_rails_middleware
lib/weixin_rails_middleware/adapter/weixin_adapter.rb
WeixinRailsMiddleware.WexinAdapter.render_authorize_result
def render_authorize_result(status=401, text=nil, valid=false) text = text || error_msg Rails.logger.error(text) if status != 200 {plain: text, status: status, valid: valid} end
ruby
def render_authorize_result(status=401, text=nil, valid=false) text = text || error_msg Rails.logger.error(text) if status != 200 {plain: text, status: status, valid: valid} end
[ "def", "render_authorize_result", "(", "status", "=", "401", ",", "text", "=", "nil", ",", "valid", "=", "false", ")", "text", "=", "text", "||", "error_msg", "Rails", ".", "logger", ".", "error", "(", "text", ")", "if", "status", "!=", "200", "{", "plain", ":", "text", ",", "status", ":", "status", ",", "valid", ":", "valid", "}", "end" ]
render weixin server authorize results
[ "render", "weixin", "server", "authorize", "results" ]
50bff55b9ef9405594a5aacf99661eed583c95ce
https://github.com/lanrion/weixin_rails_middleware/blob/50bff55b9ef9405594a5aacf99661eed583c95ce/lib/weixin_rails_middleware/adapter/weixin_adapter.rb#L70-L74
train
lanrion/weixin_rails_middleware
lib/weixin_rails_middleware/helpers/reply_weixin_message_helper.rb
WeixinRailsMiddleware.ReplyWeixinMessageHelper.reply_music_message
def reply_music_message(from=nil, to=nil, music) message = MusicReplyMessage.new message.FromUserName = from || @weixin_message.ToUserName message.ToUserName = to || @weixin_message.FromUserName message.Music = music encrypt_message message.to_xml end
ruby
def reply_music_message(from=nil, to=nil, music) message = MusicReplyMessage.new message.FromUserName = from || @weixin_message.ToUserName message.ToUserName = to || @weixin_message.FromUserName message.Music = music encrypt_message message.to_xml end
[ "def", "reply_music_message", "(", "from", "=", "nil", ",", "to", "=", "nil", ",", "music", ")", "message", "=", "MusicReplyMessage", ".", "new", "message", ".", "FromUserName", "=", "from", "||", "@weixin_message", ".", "ToUserName", "message", ".", "ToUserName", "=", "to", "||", "@weixin_message", ".", "FromUserName", "message", ".", "Music", "=", "music", "encrypt_message", "message", ".", "to_xml", "end" ]
music = generate_music
[ "music", "=", "generate_music" ]
50bff55b9ef9405594a5aacf99661eed583c95ce
https://github.com/lanrion/weixin_rails_middleware/blob/50bff55b9ef9405594a5aacf99661eed583c95ce/lib/weixin_rails_middleware/helpers/reply_weixin_message_helper.rb#L25-L31
train
Trevoke/SGFParser
lib/sgf/writer.rb
SGF.Writer.save
def save(root_node, filename) # TODO: - accept any I/O object? stringify_tree_from root_node File.open(filename, 'w') {|f| f << @sgf} end
ruby
def save(root_node, filename) # TODO: - accept any I/O object? stringify_tree_from root_node File.open(filename, 'w') {|f| f << @sgf} end
[ "def", "save", "(", "root_node", ",", "filename", ")", "stringify_tree_from", "root_node", "File", ".", "open", "(", "filename", ",", "'w'", ")", "{", "|", "f", "|", "f", "<<", "@sgf", "}", "end" ]
Takes a node and a filename as arguments
[ "Takes", "a", "node", "and", "a", "filename", "as", "arguments" ]
492c1ac958672f95a39f720d5adddaf0e4db048c
https://github.com/Trevoke/SGFParser/blob/492c1ac958672f95a39f720d5adddaf0e4db048c/lib/sgf/writer.rb#L6-L10
train
Trevoke/SGFParser
lib/sgf/node.rb
SGF.Node.add_children
def add_children(*nodes) new_children = nodes.flatten new_children.each do |node| node.set_parent self node.add_observer(self) end changed notify_observers :new_children, new_children end
ruby
def add_children(*nodes) new_children = nodes.flatten new_children.each do |node| node.set_parent self node.add_observer(self) end changed notify_observers :new_children, new_children end
[ "def", "add_children", "(", "*", "nodes", ")", "new_children", "=", "nodes", ".", "flatten", "new_children", ".", "each", "do", "|", "node", "|", "node", ".", "set_parent", "self", "node", ".", "add_observer", "(", "self", ")", "end", "changed", "notify_observers", ":new_children", ",", "new_children", "end" ]
Takes an arbitrary number of child nodes, adds them to the list of children, and make this node their parent.
[ "Takes", "an", "arbitrary", "number", "of", "child", "nodes", "adds", "them", "to", "the", "list", "of", "children", "and", "make", "this", "node", "their", "parent", "." ]
492c1ac958672f95a39f720d5adddaf0e4db048c
https://github.com/Trevoke/SGFParser/blob/492c1ac958672f95a39f720d5adddaf0e4db048c/lib/sgf/node.rb#L57-L65
train
contentful/rich-text-renderer.rb
lib/rich_text_renderer/text_renderers/text_renderer.rb
RichTextRenderer.TextRenderer.render
def render(node) node = Marshal.load(Marshal.dump(node)) # Clone the node node.fetch('marks', []).each do |mark| renderer = mappings[mark['type']] return mappings[nil].new(mappings).render(mark) if renderer.nil? && mappings.key?(nil) node['value'] = renderer.new(mappings).render(node) unless renderer.nil? end node['value'] end
ruby
def render(node) node = Marshal.load(Marshal.dump(node)) # Clone the node node.fetch('marks', []).each do |mark| renderer = mappings[mark['type']] return mappings[nil].new(mappings).render(mark) if renderer.nil? && mappings.key?(nil) node['value'] = renderer.new(mappings).render(node) unless renderer.nil? end node['value'] end
[ "def", "render", "(", "node", ")", "node", "=", "Marshal", ".", "load", "(", "Marshal", ".", "dump", "(", "node", ")", ")", "node", ".", "fetch", "(", "'marks'", ",", "[", "]", ")", ".", "each", "do", "|", "mark", "|", "renderer", "=", "mappings", "[", "mark", "[", "'type'", "]", "]", "return", "mappings", "[", "nil", "]", ".", "new", "(", "mappings", ")", ".", "render", "(", "mark", ")", "if", "renderer", ".", "nil?", "&&", "mappings", ".", "key?", "(", "nil", ")", "node", "[", "'value'", "]", "=", "renderer", ".", "new", "(", "mappings", ")", ".", "render", "(", "node", ")", "unless", "renderer", ".", "nil?", "end", "node", "[", "'value'", "]", "end" ]
Renders text nodes with all markings.
[ "Renders", "text", "nodes", "with", "all", "markings", "." ]
31fdff5eacf97d8d1185c6f5907b0c7b2f0a3263
https://github.com/contentful/rich-text-renderer.rb/blob/31fdff5eacf97d8d1185c6f5907b0c7b2f0a3263/lib/rich_text_renderer/text_renderers/text_renderer.rb#L7-L17
train
contentful/rich-text-renderer.rb
lib/rich_text_renderer/renderer.rb
RichTextRenderer.Renderer.render
def render(document) renderer = find_renderer(document) renderer.render(document) unless renderer.nil? end
ruby
def render(document) renderer = find_renderer(document) renderer.render(document) unless renderer.nil? end
[ "def", "render", "(", "document", ")", "renderer", "=", "find_renderer", "(", "document", ")", "renderer", ".", "render", "(", "document", ")", "unless", "renderer", ".", "nil?", "end" ]
Returns a rendered RichText document
[ "Returns", "a", "rendered", "RichText", "document" ]
31fdff5eacf97d8d1185c6f5907b0c7b2f0a3263
https://github.com/contentful/rich-text-renderer.rb/blob/31fdff5eacf97d8d1185c6f5907b0c7b2f0a3263/lib/rich_text_renderer/renderer.rb#L43-L46
train
contentful/rich-text-renderer.rb
lib/rich_text_renderer/block_renderers/asset_hyperlink_renderer.rb
RichTextRenderer.AssetHyperlinkRenderer.render
def render(node) asset = nil begin asset = node['data']['target'] rescue fail "Node target is not an asset - Node: #{node}" end # Check by class name instead of instance type to # avoid dependending on the Contentful SDK. return render_asset(asset, node) if asset.class.ancestors.map(&:to_s).any? { |name| name.include?('Asset') } if asset.is_a?(::Hash) unless asset.key?('fields') && asset['fields'].key?('file') fail "Node target is not an asset - Node: #{node}" end return render_hash(asset, node) end fail "Node target is not an asset - Node: #{node}" end
ruby
def render(node) asset = nil begin asset = node['data']['target'] rescue fail "Node target is not an asset - Node: #{node}" end # Check by class name instead of instance type to # avoid dependending on the Contentful SDK. return render_asset(asset, node) if asset.class.ancestors.map(&:to_s).any? { |name| name.include?('Asset') } if asset.is_a?(::Hash) unless asset.key?('fields') && asset['fields'].key?('file') fail "Node target is not an asset - Node: #{node}" end return render_hash(asset, node) end fail "Node target is not an asset - Node: #{node}" end
[ "def", "render", "(", "node", ")", "asset", "=", "nil", "begin", "asset", "=", "node", "[", "'data'", "]", "[", "'target'", "]", "rescue", "fail", "\"Node target is not an asset - Node: #{node}\"", "end", "return", "render_asset", "(", "asset", ",", "node", ")", "if", "asset", ".", "class", ".", "ancestors", ".", "map", "(", "&", ":to_s", ")", ".", "any?", "{", "|", "name", "|", "name", ".", "include?", "(", "'Asset'", ")", "}", "if", "asset", ".", "is_a?", "(", "::", "Hash", ")", "unless", "asset", ".", "key?", "(", "'fields'", ")", "&&", "asset", "[", "'fields'", "]", ".", "key?", "(", "'file'", ")", "fail", "\"Node target is not an asset - Node: #{node}\"", "end", "return", "render_hash", "(", "asset", ",", "node", ")", "end", "fail", "\"Node target is not an asset - Node: #{node}\"", "end" ]
Renders asset nodes
[ "Renders", "asset", "nodes" ]
31fdff5eacf97d8d1185c6f5907b0c7b2f0a3263
https://github.com/contentful/rich-text-renderer.rb/blob/31fdff5eacf97d8d1185c6f5907b0c7b2f0a3263/lib/rich_text_renderer/block_renderers/asset_hyperlink_renderer.rb#L10-L31
train
contentful/rich-text-renderer.rb
lib/rich_text_renderer/document_renderers/document_renderer.rb
RichTextRenderer.DocumentRenderer.render
def render(document) document['content'].each_with_object([]) do |node, result| result << find_renderer(node).render(node) end.join("\n") end
ruby
def render(document) document['content'].each_with_object([]) do |node, result| result << find_renderer(node).render(node) end.join("\n") end
[ "def", "render", "(", "document", ")", "document", "[", "'content'", "]", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "node", ",", "result", "|", "result", "<<", "find_renderer", "(", "node", ")", ".", "render", "(", "node", ")", "end", ".", "join", "(", "\"\\n\"", ")", "end" ]
Renders all nodes in the document.
[ "Renders", "all", "nodes", "in", "the", "document", "." ]
31fdff5eacf97d8d1185c6f5907b0c7b2f0a3263
https://github.com/contentful/rich-text-renderer.rb/blob/31fdff5eacf97d8d1185c6f5907b0c7b2f0a3263/lib/rich_text_renderer/document_renderers/document_renderer.rb#L7-L11
train
paulsamuels/SBConstants
lib/sbconstants/cli.rb
SBConstants.CLI.parse_xibs
def parse_xibs Dir["#{options.source_dir}/**/*.{storyboard,xib}"].each_with_index do |xib, xib_index| filename = File.basename(xib, '.*') next if options.ignored.include? filename xibs << filename group_name = "#{xib.split(".").last}Names" constants[filename] << Location.new(group_name, nil, xib, filename, xib_index + 1) File.readlines(xib, encoding: 'UTF-8').each_with_index do |line, index| options.queries.each do |query| next unless value = line[query.regex, 1] next if value.strip.empty? next unless value.start_with?(options.prefix) if options.prefix constants[value] << Location.new(query.node, query.attribute, line.strip, filename, index + 1) end end end end
ruby
def parse_xibs Dir["#{options.source_dir}/**/*.{storyboard,xib}"].each_with_index do |xib, xib_index| filename = File.basename(xib, '.*') next if options.ignored.include? filename xibs << filename group_name = "#{xib.split(".").last}Names" constants[filename] << Location.new(group_name, nil, xib, filename, xib_index + 1) File.readlines(xib, encoding: 'UTF-8').each_with_index do |line, index| options.queries.each do |query| next unless value = line[query.regex, 1] next if value.strip.empty? next unless value.start_with?(options.prefix) if options.prefix constants[value] << Location.new(query.node, query.attribute, line.strip, filename, index + 1) end end end end
[ "def", "parse_xibs", "Dir", "[", "\"#{options.source_dir}/**/*.{storyboard,xib}\"", "]", ".", "each_with_index", "do", "|", "xib", ",", "xib_index", "|", "filename", "=", "File", ".", "basename", "(", "xib", ",", "'.*'", ")", "next", "if", "options", ".", "ignored", ".", "include?", "filename", "xibs", "<<", "filename", "group_name", "=", "\"#{xib.split(\".\").last}Names\"", "constants", "[", "filename", "]", "<<", "Location", ".", "new", "(", "group_name", ",", "nil", ",", "xib", ",", "filename", ",", "xib_index", "+", "1", ")", "File", ".", "readlines", "(", "xib", ",", "encoding", ":", "'UTF-8'", ")", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "options", ".", "queries", ".", "each", "do", "|", "query", "|", "next", "unless", "value", "=", "line", "[", "query", ".", "regex", ",", "1", "]", "next", "if", "value", ".", "strip", ".", "empty?", "next", "unless", "value", ".", "start_with?", "(", "options", ".", "prefix", ")", "if", "options", ".", "prefix", "constants", "[", "value", "]", "<<", "Location", ".", "new", "(", "query", ".", "node", ",", "query", ".", "attribute", ",", "line", ".", "strip", ",", "filename", ",", "index", "+", "1", ")", "end", "end", "end", "end" ]
Parse all found storyboards and build a dictionary of constant => locations A constant key can potentially exist in many files so locations is a collection
[ "Parse", "all", "found", "storyboards", "and", "build", "a", "dictionary", "of", "constant", "=", ">", "locations" ]
3a10637c9da87322bfdaed3eb450d3899ae948fb
https://github.com/paulsamuels/SBConstants/blob/3a10637c9da87322bfdaed3eb450d3899ae948fb/lib/sbconstants/cli.rb#L68-L91
train
jekyll/jekyll-textile-converter
lib/jekyll-textile-converter/filters.rb
Jekyll.Filters.textilize
def textilize(input) site = @context.registers[:site] converter = if site.respond_to?(:find_converter_instance) site.find_converter_instance(Jekyll::Converters::Textile) else site.getConverterImpl(Jekyll::Converters::Textile) end converter.convert(input) end
ruby
def textilize(input) site = @context.registers[:site] converter = if site.respond_to?(:find_converter_instance) site.find_converter_instance(Jekyll::Converters::Textile) else site.getConverterImpl(Jekyll::Converters::Textile) end converter.convert(input) end
[ "def", "textilize", "(", "input", ")", "site", "=", "@context", ".", "registers", "[", ":site", "]", "converter", "=", "if", "site", ".", "respond_to?", "(", ":find_converter_instance", ")", "site", ".", "find_converter_instance", "(", "Jekyll", "::", "Converters", "::", "Textile", ")", "else", "site", ".", "getConverterImpl", "(", "Jekyll", "::", "Converters", "::", "Textile", ")", "end", "converter", ".", "convert", "(", "input", ")", "end" ]
Convert a Textile string into HTML output. input - The Textile String to convert. Returns the HTML formatted String.
[ "Convert", "a", "Textile", "string", "into", "HTML", "output", "." ]
cf4dd3e34609b2f266c6743abcdf4c62fa5a98b5
https://github.com/jekyll/jekyll-textile-converter/blob/cf4dd3e34609b2f266c6743abcdf4c62fa5a98b5/lib/jekyll-textile-converter/filters.rb#L8-L16
train
tulibraries/alma_rb
lib/alma/availability_response.rb
Alma.AvailabilityResponse.parse_bibs_data
def parse_bibs_data(bibs) bibs.reduce(Hash.new) { |acc, bib| acc.merge({"#{bib.id}" => {holdings: build_holdings_for(bib)}}) } end
ruby
def parse_bibs_data(bibs) bibs.reduce(Hash.new) { |acc, bib| acc.merge({"#{bib.id}" => {holdings: build_holdings_for(bib)}}) } end
[ "def", "parse_bibs_data", "(", "bibs", ")", "bibs", ".", "reduce", "(", "Hash", ".", "new", ")", "{", "|", "acc", ",", "bib", "|", "acc", ".", "merge", "(", "{", "\"#{bib.id}\"", "=>", "{", "holdings", ":", "build_holdings_for", "(", "bib", ")", "}", "}", ")", "}", "end" ]
Data structure for holdings information of bib records. A hash with mms ids as keys, with values of an array of one or more hashes of holdings info
[ "Data", "structure", "for", "holdings", "information", "of", "bib", "records", ".", "A", "hash", "with", "mms", "ids", "as", "keys", "with", "values", "of", "an", "array", "of", "one", "or", "more", "hashes", "of", "holdings", "info" ]
b38c64cde562b4784690e45df8a241389d363364
https://github.com/tulibraries/alma_rb/blob/b38c64cde562b4784690e45df8a241389d363364/lib/alma/availability_response.rb#L16-L20
train
tulibraries/alma_rb
lib/alma/user.rb
Alma.User.method_missing
def method_missing(name) return response[name.to_s] if has_key?(name.to_s) super.method_missing name end
ruby
def method_missing(name) return response[name.to_s] if has_key?(name.to_s) super.method_missing name end
[ "def", "method_missing", "(", "name", ")", "return", "response", "[", "name", ".", "to_s", "]", "if", "has_key?", "(", "name", ".", "to_s", ")", "super", ".", "method_missing", "name", "end" ]
Access the top level JSON attributes as object methods
[ "Access", "the", "top", "level", "JSON", "attributes", "as", "object", "methods" ]
b38c64cde562b4784690e45df8a241389d363364
https://github.com/tulibraries/alma_rb/blob/b38c64cde562b4784690e45df8a241389d363364/lib/alma/user.rb#L72-L75
train
tulibraries/alma_rb
lib/alma/user.rb
Alma.User.save!
def save! response = HTTParty.put("#{users_base_path}/#{id}", timeout: timeout, headers: headers, body: to_json) get_body_from(response) end
ruby
def save! response = HTTParty.put("#{users_base_path}/#{id}", timeout: timeout, headers: headers, body: to_json) get_body_from(response) end
[ "def", "save!", "response", "=", "HTTParty", ".", "put", "(", "\"#{users_base_path}/#{id}\"", ",", "timeout", ":", "timeout", ",", "headers", ":", "headers", ",", "body", ":", "to_json", ")", "get_body_from", "(", "response", ")", "end" ]
Persist the user in it's current state back to Alma
[ "Persist", "the", "user", "in", "it", "s", "current", "state", "back", "to", "Alma" ]
b38c64cde562b4784690e45df8a241389d363364
https://github.com/tulibraries/alma_rb/blob/b38c64cde562b4784690e45df8a241389d363364/lib/alma/user.rb#L83-L86
train
cortex-cms/cortex
app/controllers/cortex/graphql_controller.rb
Cortex.GraphqlController.ensure_hash
def ensure_hash(ambiguous_param) case ambiguous_param when String if ambiguous_param.present? ensure_hash(JSON.parse(ambiguous_param)) else {} end when Hash, ActionController::Parameters ambiguous_param when nil {} else raise ArgumentError, "Unexpected parameter: #{ambiguous_param}" end end
ruby
def ensure_hash(ambiguous_param) case ambiguous_param when String if ambiguous_param.present? ensure_hash(JSON.parse(ambiguous_param)) else {} end when Hash, ActionController::Parameters ambiguous_param when nil {} else raise ArgumentError, "Unexpected parameter: #{ambiguous_param}" end end
[ "def", "ensure_hash", "(", "ambiguous_param", ")", "case", "ambiguous_param", "when", "String", "if", "ambiguous_param", ".", "present?", "ensure_hash", "(", "JSON", ".", "parse", "(", "ambiguous_param", ")", ")", "else", "{", "}", "end", "when", "Hash", ",", "ActionController", "::", "Parameters", "ambiguous_param", "when", "nil", "{", "}", "else", "raise", "ArgumentError", ",", "\"Unexpected parameter: #{ambiguous_param}\"", "end", "end" ]
Handle form data, JSON body, or a blank value
[ "Handle", "form", "data", "JSON", "body", "or", "a", "blank", "value" ]
a49945bc4f9156161dd9d716d696fcbb863db15b
https://github.com/cortex-cms/cortex/blob/a49945bc4f9156161dd9d716d696fcbb863db15b/app/controllers/cortex/graphql_controller.rb#L23-L38
train
Apipie/apipie-bindings
lib/apipie_bindings/resource.rb
ApipieBindings.Resource.call
def call(action, params={}, headers={}, options={}) @api.call(@name, action, params, headers, options) end
ruby
def call(action, params={}, headers={}, options={}) @api.call(@name, action, params, headers, options) end
[ "def", "call", "(", "action", ",", "params", "=", "{", "}", ",", "headers", "=", "{", "}", ",", "options", "=", "{", "}", ")", "@api", ".", "call", "(", "@name", ",", "action", ",", "params", ",", "headers", ",", "options", ")", "end" ]
Execute an action on a resource @param action [Symbol] @param params [Hash] @param headers [Hash] @param options [Hash] @return [Hash]
[ "Execute", "an", "action", "on", "a", "resource" ]
d68d1554b477cbb541651394cfb7eb93c6f2858e
https://github.com/Apipie/apipie-bindings/blob/d68d1554b477cbb541651394cfb7eb93c6f2858e/lib/apipie_bindings/resource.rb#L20-L22
train
maccman/nestful
lib/nestful/connection.rb
Nestful.Connection.request
def request(method, path, *arguments) response = http.send(method, path, *arguments) response.uri = URI.join(endpoint, path) handle_response(response) rescue Timeout::Error, Net::OpenTimeout => e raise TimeoutError.new(@request, e.message) rescue OpenSSL::SSL::SSLError => e raise SSLError.new(@request, e.message) rescue SocketError, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::HTTPServerException, Net::ProtocolError, Errno::ECONNABORTED, Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ETIMEDOUT, Errno::ENETUNREACH, Errno::EHOSTUNREACH, Errno::EINVAL, Errno::ENOPROTOOPT => e raise ErrnoError.new(@request, e.message) rescue Zlib::DataError, Zlib::BufError => e raise ZlibError.new(@request, e.message) end
ruby
def request(method, path, *arguments) response = http.send(method, path, *arguments) response.uri = URI.join(endpoint, path) handle_response(response) rescue Timeout::Error, Net::OpenTimeout => e raise TimeoutError.new(@request, e.message) rescue OpenSSL::SSL::SSLError => e raise SSLError.new(@request, e.message) rescue SocketError, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::HTTPServerException, Net::ProtocolError, Errno::ECONNABORTED, Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ETIMEDOUT, Errno::ENETUNREACH, Errno::EHOSTUNREACH, Errno::EINVAL, Errno::ENOPROTOOPT => e raise ErrnoError.new(@request, e.message) rescue Zlib::DataError, Zlib::BufError => e raise ZlibError.new(@request, e.message) end
[ "def", "request", "(", "method", ",", "path", ",", "*", "arguments", ")", "response", "=", "http", ".", "send", "(", "method", ",", "path", ",", "*", "arguments", ")", "response", ".", "uri", "=", "URI", ".", "join", "(", "endpoint", ",", "path", ")", "handle_response", "(", "response", ")", "rescue", "Timeout", "::", "Error", ",", "Net", "::", "OpenTimeout", "=>", "e", "raise", "TimeoutError", ".", "new", "(", "@request", ",", "e", ".", "message", ")", "rescue", "OpenSSL", "::", "SSL", "::", "SSLError", "=>", "e", "raise", "SSLError", ".", "new", "(", "@request", ",", "e", ".", "message", ")", "rescue", "SocketError", ",", "EOFError", ",", "Net", "::", "HTTPBadResponse", ",", "Net", "::", "HTTPHeaderSyntaxError", ",", "Net", "::", "HTTPServerException", ",", "Net", "::", "ProtocolError", ",", "Errno", "::", "ECONNABORTED", ",", "Errno", "::", "ECONNREFUSED", ",", "Errno", "::", "ECONNRESET", ",", "Errno", "::", "ETIMEDOUT", ",", "Errno", "::", "ENETUNREACH", ",", "Errno", "::", "EHOSTUNREACH", ",", "Errno", "::", "EINVAL", ",", "Errno", "::", "ENOPROTOOPT", "=>", "e", "raise", "ErrnoError", ".", "new", "(", "@request", ",", "e", ".", "message", ")", "rescue", "Zlib", "::", "DataError", ",", "Zlib", "::", "BufError", "=>", "e", "raise", "ZlibError", ".", "new", "(", "@request", ",", "e", ".", "message", ")", "end" ]
Makes a request to the remote service.
[ "Makes", "a", "request", "to", "the", "remote", "service", "." ]
0d4b1598b50770483306a48f5b25934fa64f22f1
https://github.com/maccman/nestful/blob/0d4b1598b50770483306a48f5b25934fa64f22f1/lib/nestful/connection.rb#L62-L90
train
Invoca/exception_handling
lib/exception_handling/exception_info.rb
ExceptionHandling.ExceptionInfo.extract_and_merge_controller_data
def extract_and_merge_controller_data(data) if @controller data[:request] = { params: @controller.request.parameters.to_hash, rails_root: defined?(Rails) && defined?(Rails.root) ? Rails.root : "Rails.root not defined. Is this a test environment?", url: @controller.complete_request_uri } data[:environment].merge!(@controller.request.env.to_hash) @controller.session[:fault_in_session] data[:session] = { key: @controller.request.session_options[:id], data: @controller.session.to_hash } end end
ruby
def extract_and_merge_controller_data(data) if @controller data[:request] = { params: @controller.request.parameters.to_hash, rails_root: defined?(Rails) && defined?(Rails.root) ? Rails.root : "Rails.root not defined. Is this a test environment?", url: @controller.complete_request_uri } data[:environment].merge!(@controller.request.env.to_hash) @controller.session[:fault_in_session] data[:session] = { key: @controller.request.session_options[:id], data: @controller.session.to_hash } end end
[ "def", "extract_and_merge_controller_data", "(", "data", ")", "if", "@controller", "data", "[", ":request", "]", "=", "{", "params", ":", "@controller", ".", "request", ".", "parameters", ".", "to_hash", ",", "rails_root", ":", "defined?", "(", "Rails", ")", "&&", "defined?", "(", "Rails", ".", "root", ")", "?", "Rails", ".", "root", ":", "\"Rails.root not defined. Is this a test environment?\"", ",", "url", ":", "@controller", ".", "complete_request_uri", "}", "data", "[", ":environment", "]", ".", "merge!", "(", "@controller", ".", "request", ".", "env", ".", "to_hash", ")", "@controller", ".", "session", "[", ":fault_in_session", "]", "data", "[", ":session", "]", "=", "{", "key", ":", "@controller", ".", "request", ".", "session_options", "[", ":id", "]", ",", "data", ":", "@controller", ".", "session", ".", "to_hash", "}", "end", "end" ]
Pull certain fields out of the controller and add to the data hash.
[ "Pull", "certain", "fields", "out", "of", "the", "controller", "and", "add", "to", "the", "data", "hash", "." ]
706e7a34379ba085475e754f1b634dc3627ff498
https://github.com/Invoca/exception_handling/blob/706e7a34379ba085475e754f1b634dc3627ff498/lib/exception_handling/exception_info.rb#L207-L222
train
jbussdieker/ruby-rsync
lib/rsync/change.rb
Rsync.Change.summary
def summary if update_type == :message message elsif update_type == :recv and @data[2,9] == "+++++++++" "creating local" elsif update_type == :recv "updating local" elsif update_type == :sent and @data[2,9] == "+++++++++" "creating remote" elsif update_type == :sent "updating remote" else changes = [] [:checksum, :size, :timestamp, :permissions, :owner, :group, :acl].each do |prop| changes << prop if send(prop) == :changed end changes.join(", ") end end
ruby
def summary if update_type == :message message elsif update_type == :recv and @data[2,9] == "+++++++++" "creating local" elsif update_type == :recv "updating local" elsif update_type == :sent and @data[2,9] == "+++++++++" "creating remote" elsif update_type == :sent "updating remote" else changes = [] [:checksum, :size, :timestamp, :permissions, :owner, :group, :acl].each do |prop| changes << prop if send(prop) == :changed end changes.join(", ") end end
[ "def", "summary", "if", "update_type", "==", ":message", "message", "elsif", "update_type", "==", ":recv", "and", "@data", "[", "2", ",", "9", "]", "==", "\"+++++++++\"", "\"creating local\"", "elsif", "update_type", "==", ":recv", "\"updating local\"", "elsif", "update_type", "==", ":sent", "and", "@data", "[", "2", ",", "9", "]", "==", "\"+++++++++\"", "\"creating remote\"", "elsif", "update_type", "==", ":sent", "\"updating remote\"", "else", "changes", "=", "[", "]", "[", ":checksum", ",", ":size", ",", ":timestamp", ",", ":permissions", ",", ":owner", ",", ":group", ",", ":acl", "]", ".", "each", "do", "|", "prop", "|", "changes", "<<", "prop", "if", "send", "(", "prop", ")", "==", ":changed", "end", "changes", ".", "join", "(", "\", \"", ")", "end", "end" ]
Simple description of the change. @return [String]
[ "Simple", "description", "of", "the", "change", "." ]
38f529d5908d763d04636e2a3df7269c3f636d48
https://github.com/jbussdieker/ruby-rsync/blob/38f529d5908d763d04636e2a3df7269c3f636d48/lib/rsync/change.rb#L34-L52
train
gosu/fidgit
lib/fidgit/elements/element.rb
Fidgit.Element.with
def with(&block) raise ArgumentError.new("Must pass a block") unless block_given? case block.arity when 1 yield self when 0 instance_methods_eval(&block) else raise "block arity must be 0 or 1" end end
ruby
def with(&block) raise ArgumentError.new("Must pass a block") unless block_given? case block.arity when 1 yield self when 0 instance_methods_eval(&block) else raise "block arity must be 0 or 1" end end
[ "def", "with", "(", "&", "block", ")", "raise", "ArgumentError", ".", "new", "(", "\"Must pass a block\"", ")", "unless", "block_given?", "case", "block", ".", "arity", "when", "1", "yield", "self", "when", "0", "instance_methods_eval", "(", "&", "block", ")", "else", "raise", "\"block arity must be 0 or 1\"", "end", "end" ]
Evaluate a block, just like it was a constructor block.
[ "Evaluate", "a", "block", "just", "like", "it", "was", "a", "constructor", "block", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/elements/element.rb#L275-L285
train
gosu/fidgit
lib/fidgit/schema.rb
Fidgit.Schema.merge_constants!
def merge_constants!(constants_hash) constants_hash.each_pair do |name, value| @constants[name] = case value when Array case value.size when 3 then Gosu::Color.rgb(*value) when 4 then Gosu::Color.rgba(*value) else raise "Colors must be in 0..255, RGB or RGBA array format" end else value end end self end
ruby
def merge_constants!(constants_hash) constants_hash.each_pair do |name, value| @constants[name] = case value when Array case value.size when 3 then Gosu::Color.rgb(*value) when 4 then Gosu::Color.rgba(*value) else raise "Colors must be in 0..255, RGB or RGBA array format" end else value end end self end
[ "def", "merge_constants!", "(", "constants_hash", ")", "constants_hash", ".", "each_pair", "do", "|", "name", ",", "value", "|", "@constants", "[", "name", "]", "=", "case", "value", "when", "Array", "case", "value", ".", "size", "when", "3", "then", "Gosu", "::", "Color", ".", "rgb", "(", "*", "value", ")", "when", "4", "then", "Gosu", "::", "Color", ".", "rgba", "(", "*", "value", ")", "else", "raise", "\"Colors must be in 0..255, RGB or RGBA array format\"", "end", "else", "value", "end", "end", "self", "end" ]
Merge in a hash containing constant values. Arrays will be resolved as colors in RGBA or RGB format. @param [Hash<Symbol => Object>] constants_hash
[ "Merge", "in", "a", "hash", "containing", "constant", "values", ".", "Arrays", "will", "be", "resolved", "as", "colors", "in", "RGBA", "or", "RGB", "format", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/schema.rb#L35-L51
train
gosu/fidgit
lib/fidgit/schema.rb
Fidgit.Schema.merge_elements!
def merge_elements!(elements_hash) elements_hash.each_pair do |klass_names, data| klass = Fidgit klass_names.to_s.split('::').each do |klass_name| klass = klass.const_get klass_name end raise "elements must be names of classes derived from #{Element}" unless klass.ancestors.include? Fidgit::Element @elements[klass] ||= {} @elements[klass].deep_merge! data end self end
ruby
def merge_elements!(elements_hash) elements_hash.each_pair do |klass_names, data| klass = Fidgit klass_names.to_s.split('::').each do |klass_name| klass = klass.const_get klass_name end raise "elements must be names of classes derived from #{Element}" unless klass.ancestors.include? Fidgit::Element @elements[klass] ||= {} @elements[klass].deep_merge! data end self end
[ "def", "merge_elements!", "(", "elements_hash", ")", "elements_hash", ".", "each_pair", "do", "|", "klass_names", ",", "data", "|", "klass", "=", "Fidgit", "klass_names", ".", "to_s", ".", "split", "(", "'::'", ")", ".", "each", "do", "|", "klass_name", "|", "klass", "=", "klass", ".", "const_get", "klass_name", "end", "raise", "\"elements must be names of classes derived from #{Element}\"", "unless", "klass", ".", "ancestors", ".", "include?", "Fidgit", "::", "Element", "@elements", "[", "klass", "]", "||=", "{", "}", "@elements", "[", "klass", "]", ".", "deep_merge!", "data", "end", "self", "end" ]
Merge in a hash containing default values for each element. @param [Hash<Symbol => Hash>] elements_hash
[ "Merge", "in", "a", "hash", "containing", "default", "values", "for", "each", "element", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/schema.rb#L56-L69
train
gosu/fidgit
lib/fidgit/elements/text_area.rb
Fidgit.TextArea.selection_range
def selection_range from = [@text_input.selection_start, caret_position].min to = [@text_input.selection_start, caret_position].max (from...to) end
ruby
def selection_range from = [@text_input.selection_start, caret_position].min to = [@text_input.selection_start, caret_position].max (from...to) end
[ "def", "selection_range", "from", "=", "[", "@text_input", ".", "selection_start", ",", "caret_position", "]", ".", "min", "to", "=", "[", "@text_input", ".", "selection_start", ",", "caret_position", "]", ".", "max", "(", "from", "...", "to", ")", "end" ]
Returns the range of the selection. @return [Range]
[ "Returns", "the", "range", "of", "the", "selection", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/elements/text_area.rb#L47-L52
train
gosu/fidgit
lib/fidgit/elements/text_area.rb
Fidgit.TextArea.selection_text=
def selection_text=(str) from = [@text_input.selection_start, @text_input.caret_pos].min to = [@text_input.selection_start, @text_input.caret_pos].max new_length = str.length full_text = text tags_length_before = (0...from).inject(0) {|m, i| m + @tags[i].length } tags_length_inside = (from...to).inject(0) {|m, i| m + @tags[i].length } range = (selection_range.first + tags_length_before)...(selection_range.last + tags_length_before + tags_length_inside) full_text[range] = str.encode('UTF-8', undef: :replace) @text_input.text = full_text @text_input.selection_start = @text_input.caret_pos = from + new_length recalc # This may roll back the text if it is too long! publish :changed, self.text str end
ruby
def selection_text=(str) from = [@text_input.selection_start, @text_input.caret_pos].min to = [@text_input.selection_start, @text_input.caret_pos].max new_length = str.length full_text = text tags_length_before = (0...from).inject(0) {|m, i| m + @tags[i].length } tags_length_inside = (from...to).inject(0) {|m, i| m + @tags[i].length } range = (selection_range.first + tags_length_before)...(selection_range.last + tags_length_before + tags_length_inside) full_text[range] = str.encode('UTF-8', undef: :replace) @text_input.text = full_text @text_input.selection_start = @text_input.caret_pos = from + new_length recalc # This may roll back the text if it is too long! publish :changed, self.text str end
[ "def", "selection_text", "=", "(", "str", ")", "from", "=", "[", "@text_input", ".", "selection_start", ",", "@text_input", ".", "caret_pos", "]", ".", "min", "to", "=", "[", "@text_input", ".", "selection_start", ",", "@text_input", ".", "caret_pos", "]", ".", "max", "new_length", "=", "str", ".", "length", "full_text", "=", "text", "tags_length_before", "=", "(", "0", "...", "from", ")", ".", "inject", "(", "0", ")", "{", "|", "m", ",", "i", "|", "m", "+", "@tags", "[", "i", "]", ".", "length", "}", "tags_length_inside", "=", "(", "from", "...", "to", ")", ".", "inject", "(", "0", ")", "{", "|", "m", ",", "i", "|", "m", "+", "@tags", "[", "i", "]", ".", "length", "}", "range", "=", "(", "selection_range", ".", "first", "+", "tags_length_before", ")", "...", "(", "selection_range", ".", "last", "+", "tags_length_before", "+", "tags_length_inside", ")", "full_text", "[", "range", "]", "=", "str", ".", "encode", "(", "'UTF-8'", ",", "undef", ":", ":replace", ")", "@text_input", ".", "text", "=", "full_text", "@text_input", ".", "selection_start", "=", "@text_input", ".", "caret_pos", "=", "from", "+", "new_length", "recalc", "publish", ":changed", ",", "self", ".", "text", "str", "end" ]
Sets the text within the selection. The caret will be placed at the end of the inserted text. @param [String] str Text to insert. @return [String] The new selection text.
[ "Sets", "the", "text", "within", "the", "selection", ".", "The", "caret", "will", "be", "placed", "at", "the", "end", "of", "the", "inserted", "text", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/elements/text_area.rb#L65-L84
train
gosu/fidgit
lib/fidgit/elements/text_area.rb
Fidgit.TextArea.caret_position=
def caret_position=(position) raise ArgumentError, "Caret position must be in the range 0 to the length of the text (inclusive)" unless position.between?(0, stripped_text.length) @text_input.caret_pos = position position end
ruby
def caret_position=(position) raise ArgumentError, "Caret position must be in the range 0 to the length of the text (inclusive)" unless position.between?(0, stripped_text.length) @text_input.caret_pos = position position end
[ "def", "caret_position", "=", "(", "position", ")", "raise", "ArgumentError", ",", "\"Caret position must be in the range 0 to the length of the text (inclusive)\"", "unless", "position", ".", "between?", "(", "0", ",", "stripped_text", ".", "length", ")", "@text_input", ".", "caret_pos", "=", "position", "position", "end" ]
Position of the caret. @param [Integer] pos Position of caret in the text. @return [Integer] New position of caret.
[ "Position", "of", "the", "caret", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/elements/text_area.rb#L97-L102
train
gosu/fidgit
lib/fidgit/elements/text_area.rb
Fidgit.TextArea.draw_foreground
def draw_foreground # Always roll back changes made by the user unless the text is editable. if editable? or text == @old_text recalc if focused? # Workaround for Windows draw/update bug. @old_caret_position = caret_position @old_selection_start = @text_input.selection_start else roll_back end if caret_position > stripped_text.length self.caret_position = stripped_text.length end if @text_input.selection_start >= stripped_text.length @text_input.selection_start = stripped_text.length end # Draw the selection. selection_range.each do |pos| char_x, char_y = @caret_positions[pos] char_width = @char_widths[pos] left, top = x + padding_left + char_x, y + padding_top + char_y draw_rect left, top, char_width, font.height, z, @selection_color end # Draw text. @lines.each_with_index do |line, index| font.draw(line, x + padding_left, y + padding_top + y_at_line(index), z) end # Draw the caret. if focused? and ((Gosu::milliseconds / @caret_period) % 2 == 0) caret_x, caret_y = @caret_positions[caret_position] left, top = x + padding_left + caret_x, y + padding_top + caret_y draw_rect left, top, 1, font.height, z, @caret_color end end
ruby
def draw_foreground # Always roll back changes made by the user unless the text is editable. if editable? or text == @old_text recalc if focused? # Workaround for Windows draw/update bug. @old_caret_position = caret_position @old_selection_start = @text_input.selection_start else roll_back end if caret_position > stripped_text.length self.caret_position = stripped_text.length end if @text_input.selection_start >= stripped_text.length @text_input.selection_start = stripped_text.length end # Draw the selection. selection_range.each do |pos| char_x, char_y = @caret_positions[pos] char_width = @char_widths[pos] left, top = x + padding_left + char_x, y + padding_top + char_y draw_rect left, top, char_width, font.height, z, @selection_color end # Draw text. @lines.each_with_index do |line, index| font.draw(line, x + padding_left, y + padding_top + y_at_line(index), z) end # Draw the caret. if focused? and ((Gosu::milliseconds / @caret_period) % 2 == 0) caret_x, caret_y = @caret_positions[caret_position] left, top = x + padding_left + caret_x, y + padding_top + caret_y draw_rect left, top, 1, font.height, z, @caret_color end end
[ "def", "draw_foreground", "if", "editable?", "or", "text", "==", "@old_text", "recalc", "if", "focused?", "@old_caret_position", "=", "caret_position", "@old_selection_start", "=", "@text_input", ".", "selection_start", "else", "roll_back", "end", "if", "caret_position", ">", "stripped_text", ".", "length", "self", ".", "caret_position", "=", "stripped_text", ".", "length", "end", "if", "@text_input", ".", "selection_start", ">=", "stripped_text", ".", "length", "@text_input", ".", "selection_start", "=", "stripped_text", ".", "length", "end", "selection_range", ".", "each", "do", "|", "pos", "|", "char_x", ",", "char_y", "=", "@caret_positions", "[", "pos", "]", "char_width", "=", "@char_widths", "[", "pos", "]", "left", ",", "top", "=", "x", "+", "padding_left", "+", "char_x", ",", "y", "+", "padding_top", "+", "char_y", "draw_rect", "left", ",", "top", ",", "char_width", ",", "font", ".", "height", ",", "z", ",", "@selection_color", "end", "@lines", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "font", ".", "draw", "(", "line", ",", "x", "+", "padding_left", ",", "y", "+", "padding_top", "+", "y_at_line", "(", "index", ")", ",", "z", ")", "end", "if", "focused?", "and", "(", "(", "Gosu", "::", "milliseconds", "/", "@caret_period", ")", "%", "2", "==", "0", ")", "caret_x", ",", "caret_y", "=", "@caret_positions", "[", "caret_position", "]", "left", ",", "top", "=", "x", "+", "padding_left", "+", "caret_x", ",", "y", "+", "padding_top", "+", "caret_y", "draw_rect", "left", ",", "top", ",", "1", ",", "font", ".", "height", ",", "z", ",", "@caret_color", "end", "end" ]
Draw the text area. @return [nil]
[ "Draw", "the", "text", "area", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/elements/text_area.rb#L226-L263
train
gosu/fidgit
lib/fidgit/elements/text_area.rb
Fidgit.TextArea.text_index_at_position
def text_index_at_position(x, y) # Move caret to position the user clicks on. mouse_x, mouse_y = x - (self.x + padding_left), y - (self.y + padding_top) @char_widths.each.with_index do |width, i| char_x, char_y = @caret_positions[i] if mouse_x.between?(char_x, char_x + width) and mouse_y.between?(char_y, char_y + font.height) return i end end nil # Didn't find a character at that position. end
ruby
def text_index_at_position(x, y) # Move caret to position the user clicks on. mouse_x, mouse_y = x - (self.x + padding_left), y - (self.y + padding_top) @char_widths.each.with_index do |width, i| char_x, char_y = @caret_positions[i] if mouse_x.between?(char_x, char_x + width) and mouse_y.between?(char_y, char_y + font.height) return i end end nil # Didn't find a character at that position. end
[ "def", "text_index_at_position", "(", "x", ",", "y", ")", "mouse_x", ",", "mouse_y", "=", "x", "-", "(", "self", ".", "x", "+", "padding_left", ")", ",", "y", "-", "(", "self", ".", "y", "+", "padding_top", ")", "@char_widths", ".", "each", ".", "with_index", "do", "|", "width", ",", "i", "|", "char_x", ",", "char_y", "=", "@caret_positions", "[", "i", "]", "if", "mouse_x", ".", "between?", "(", "char_x", ",", "char_x", "+", "width", ")", "and", "mouse_y", ".", "between?", "(", "char_y", ",", "char_y", "+", "font", ".", "height", ")", "return", "i", "end", "end", "nil", "end" ]
Index of character in reference to the displayable text.
[ "Index", "of", "character", "in", "reference", "to", "the", "displayable", "text", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/elements/text_area.rb#L267-L278
train
gosu/fidgit
lib/fidgit/elements/text_area.rb
Fidgit.TextArea.cut
def cut str = selection_text unless str.empty? Clipboard.copy str self.selection_text = '' if editable? end end
ruby
def cut str = selection_text unless str.empty? Clipboard.copy str self.selection_text = '' if editable? end end
[ "def", "cut", "str", "=", "selection_text", "unless", "str", ".", "empty?", "Clipboard", ".", "copy", "str", "self", ".", "selection_text", "=", "''", "if", "editable?", "end", "end" ]
Cut the selection and copy it to the clipboard.
[ "Cut", "the", "selection", "and", "copy", "it", "to", "the", "clipboard", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/elements/text_area.rb#L444-L450
train
gosu/fidgit
lib/fidgit/elements/container.rb
Fidgit.Container.button
def button(text, options = {}, &block) Button.new(text, {parent: self}.merge!(options), &block) end
ruby
def button(text, options = {}, &block) Button.new(text, {parent: self}.merge!(options), &block) end
[ "def", "button", "(", "text", ",", "options", "=", "{", "}", ",", "&", "block", ")", "Button", ".", "new", "(", "text", ",", "{", "parent", ":", "self", "}", ".", "merge!", "(", "options", ")", ",", "&", "block", ")", "end" ]
Create a button within the container.
[ "Create", "a", "button", "within", "the", "container", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/elements/container.rb#L58-L60
train
gosu/fidgit
lib/fidgit/elements/container.rb
Fidgit.Container.image_frame
def image_frame(image, options = {}, &block) ImageFrame.new(image, {parent: self}.merge!(options), &block) end
ruby
def image_frame(image, options = {}, &block) ImageFrame.new(image, {parent: self}.merge!(options), &block) end
[ "def", "image_frame", "(", "image", ",", "options", "=", "{", "}", ",", "&", "block", ")", "ImageFrame", ".", "new", "(", "image", ",", "{", "parent", ":", "self", "}", ".", "merge!", "(", "options", ")", ",", "&", "block", ")", "end" ]
Create an icon.
[ "Create", "an", "icon", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/elements/container.rb#L85-L87
train
gosu/fidgit
lib/fidgit/elements/container.rb
Fidgit.Container.hit_element
def hit_element(x, y) @children.reverse_each do |child| case child when Container, Composite if element = child.hit_element(x, y) return element end else return child if child.hit?(x, y) end end self if hit?(x, y) end
ruby
def hit_element(x, y) @children.reverse_each do |child| case child when Container, Composite if element = child.hit_element(x, y) return element end else return child if child.hit?(x, y) end end self if hit?(x, y) end
[ "def", "hit_element", "(", "x", ",", "y", ")", "@children", ".", "reverse_each", "do", "|", "child", "|", "case", "child", "when", "Container", ",", "Composite", "if", "element", "=", "child", ".", "hit_element", "(", "x", ",", "y", ")", "return", "element", "end", "else", "return", "child", "if", "child", ".", "hit?", "(", "x", ",", "y", ")", "end", "end", "self", "if", "hit?", "(", "x", ",", "y", ")", "end" ]
Returns the element within this container that was hit, @return [Element, nil] The element hit, otherwise nil.
[ "Returns", "the", "element", "within", "this", "container", "that", "was", "hit" ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/elements/container.rb#L157-L170
train
gosu/fidgit
lib/fidgit/elements/label.rb
Fidgit.Label.icon_position=
def icon_position=(position) raise ArgumentError.new("icon_position must be one of #{ICON_POSITIONS}") unless ICON_POSITIONS.include? position @icon_position = position case @icon_position when :top, :bottom @contents.instance_variable_set :@type, :fixed_columns @contents.instance_variable_set :@num_columns, 1 when :left, :right @contents.instance_variable_set :@type, :fixed_rows @contents.instance_variable_set :@num_rows, 1 end self.icon = @icon.image if @icon.image # Force the icon into the correct position. position end
ruby
def icon_position=(position) raise ArgumentError.new("icon_position must be one of #{ICON_POSITIONS}") unless ICON_POSITIONS.include? position @icon_position = position case @icon_position when :top, :bottom @contents.instance_variable_set :@type, :fixed_columns @contents.instance_variable_set :@num_columns, 1 when :left, :right @contents.instance_variable_set :@type, :fixed_rows @contents.instance_variable_set :@num_rows, 1 end self.icon = @icon.image if @icon.image # Force the icon into the correct position. position end
[ "def", "icon_position", "=", "(", "position", ")", "raise", "ArgumentError", ".", "new", "(", "\"icon_position must be one of #{ICON_POSITIONS}\"", ")", "unless", "ICON_POSITIONS", ".", "include?", "position", "@icon_position", "=", "position", "case", "@icon_position", "when", ":top", ",", ":bottom", "@contents", ".", "instance_variable_set", ":@type", ",", ":fixed_columns", "@contents", ".", "instance_variable_set", ":@num_columns", ",", "1", "when", ":left", ",", ":right", "@contents", ".", "instance_variable_set", ":@type", ",", ":fixed_rows", "@contents", ".", "instance_variable_set", ":@num_rows", ",", "1", "end", "self", ".", "icon", "=", "@icon", ".", "image", "if", "@icon", ".", "image", "position", "end" ]
Set the position of the icon, respective to the text.
[ "Set", "the", "position", "of", "the", "icon", "respective", "to", "the", "text", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/elements/label.rb#L32-L49
train
gosu/fidgit
lib/fidgit/elements/packer.rb
Fidgit.Packer.layout
def layout # This assumes that the container overlaps all the children. # Move all children if we have moved. @children.each.with_index do |child, index| child.x = padding_left + x child.y = padding_top + y end # Make us as wrap around the largest child. rect.width = (@children.map {|c| c.width }.max || 0) + padding_left + padding_right rect.height = (@children.map {|c| c.height }.max || 0) + padding_top + padding_bottom super end
ruby
def layout # This assumes that the container overlaps all the children. # Move all children if we have moved. @children.each.with_index do |child, index| child.x = padding_left + x child.y = padding_top + y end # Make us as wrap around the largest child. rect.width = (@children.map {|c| c.width }.max || 0) + padding_left + padding_right rect.height = (@children.map {|c| c.height }.max || 0) + padding_top + padding_bottom super end
[ "def", "layout", "@children", ".", "each", ".", "with_index", "do", "|", "child", ",", "index", "|", "child", ".", "x", "=", "padding_left", "+", "x", "child", ".", "y", "=", "padding_top", "+", "y", "end", "rect", ".", "width", "=", "(", "@children", ".", "map", "{", "|", "c", "|", "c", ".", "width", "}", ".", "max", "||", "0", ")", "+", "padding_left", "+", "padding_right", "rect", ".", "height", "=", "(", "@children", ".", "map", "{", "|", "c", "|", "c", ".", "height", "}", ".", "max", "||", "0", ")", "+", "padding_top", "+", "padding_bottom", "super", "end" ]
Recalculate the size of the container. Should be overridden by any descendant that manages the positions of its children.
[ "Recalculate", "the", "size", "of", "the", "container", ".", "Should", "be", "overridden", "by", "any", "descendant", "that", "manages", "the", "positions", "of", "its", "children", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/elements/packer.rb#L26-L40
train
gosu/fidgit
lib/fidgit/states/gui_state.rb
Fidgit.GuiState.draw_rect
def draw_rect(x, y, width, height, z, color, mode = :default) @@draw_pixel.draw x, y, z, width, height, color, mode nil end
ruby
def draw_rect(x, y, width, height, z, color, mode = :default) @@draw_pixel.draw x, y, z, width, height, color, mode nil end
[ "def", "draw_rect", "(", "x", ",", "y", ",", "width", ",", "height", ",", "z", ",", "color", ",", "mode", "=", ":default", ")", "@@draw_pixel", ".", "draw", "x", ",", "y", ",", "z", ",", "width", ",", "height", ",", "color", ",", "mode", "nil", "end" ]
Draw a filled rectangle.
[ "Draw", "a", "filled", "rectangle", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/states/gui_state.rb#L223-L227
train
gosu/fidgit
lib/fidgit/states/gui_state.rb
Fidgit.GuiState.draw_frame
def draw_frame(x, y, width, height, thickness, z, color, mode = :default) draw_rect(x - thickness, y, thickness, height, z, color, mode) # left draw_rect(x - thickness, y - thickness, width + thickness * 2, thickness, z, color, mode) # top (full) draw_rect(x + width, y, thickness, height, z, color, mode) # right draw_rect(x - thickness, y + height, width + thickness * 2, thickness, z, color, mode) # bottom (full) nil end
ruby
def draw_frame(x, y, width, height, thickness, z, color, mode = :default) draw_rect(x - thickness, y, thickness, height, z, color, mode) # left draw_rect(x - thickness, y - thickness, width + thickness * 2, thickness, z, color, mode) # top (full) draw_rect(x + width, y, thickness, height, z, color, mode) # right draw_rect(x - thickness, y + height, width + thickness * 2, thickness, z, color, mode) # bottom (full) nil end
[ "def", "draw_frame", "(", "x", ",", "y", ",", "width", ",", "height", ",", "thickness", ",", "z", ",", "color", ",", "mode", "=", ":default", ")", "draw_rect", "(", "x", "-", "thickness", ",", "y", ",", "thickness", ",", "height", ",", "z", ",", "color", ",", "mode", ")", "draw_rect", "(", "x", "-", "thickness", ",", "y", "-", "thickness", ",", "width", "+", "thickness", "*", "2", ",", "thickness", ",", "z", ",", "color", ",", "mode", ")", "draw_rect", "(", "x", "+", "width", ",", "y", ",", "thickness", ",", "height", ",", "z", ",", "color", ",", "mode", ")", "draw_rect", "(", "x", "-", "thickness", ",", "y", "+", "height", ",", "width", "+", "thickness", "*", "2", ",", "thickness", ",", "z", ",", "color", ",", "mode", ")", "nil", "end" ]
Draw an unfilled rectangle.
[ "Draw", "an", "unfilled", "rectangle", "." ]
f60290252fe713622c2d128c366843a55d124b7b
https://github.com/gosu/fidgit/blob/f60290252fe713622c2d128c366843a55d124b7b/lib/fidgit/states/gui_state.rb#L230-L237
train
guard/notiffany
lib/notiffany/notifier.rb
Notiffany.Notifier.turn_on
def turn_on(options = {}) _check_server! return unless enabled? fail "Already active!" if active? _turn_on_notifiers(options) _env.notify_active = true end
ruby
def turn_on(options = {}) _check_server! return unless enabled? fail "Already active!" if active? _turn_on_notifiers(options) _env.notify_active = true end
[ "def", "turn_on", "(", "options", "=", "{", "}", ")", "_check_server!", "return", "unless", "enabled?", "fail", "\"Already active!\"", "if", "active?", "_turn_on_notifiers", "(", "options", ")", "_env", ".", "notify_active", "=", "true", "end" ]
Turn notifications on. @param [Hash] options the turn_on options @option options [Boolean] silent disable any logging
[ "Turn", "notifications", "on", "." ]
e654d6abc02549f09b970d21f143db15d546bfcc
https://github.com/guard/notiffany/blob/e654d6abc02549f09b970d21f143db15d546bfcc/lib/notiffany/notifier.rb#L109-L117
train
guard/notiffany
lib/notiffany/notifier.rb
Notiffany.Notifier.turn_off
def turn_off _check_server! fail "Not active!" unless active? @detected.available.each do |obj| obj.turn_off if obj.respond_to?(:turn_off) end _env.notify_active = false end
ruby
def turn_off _check_server! fail "Not active!" unless active? @detected.available.each do |obj| obj.turn_off if obj.respond_to?(:turn_off) end _env.notify_active = false end
[ "def", "turn_off", "_check_server!", "fail", "\"Not active!\"", "unless", "active?", "@detected", ".", "available", ".", "each", "do", "|", "obj", "|", "obj", ".", "turn_off", "if", "obj", ".", "respond_to?", "(", ":turn_off", ")", "end", "_env", ".", "notify_active", "=", "false", "end" ]
Turn notifications off.
[ "Turn", "notifications", "off", "." ]
e654d6abc02549f09b970d21f143db15d546bfcc
https://github.com/guard/notiffany/blob/e654d6abc02549f09b970d21f143db15d546bfcc/lib/notiffany/notifier.rb#L120-L130
train
guard/notiffany
lib/notiffany/notifier.rb
Notiffany.Notifier.notify
def notify(message, message_opts = {}) if _client? return unless enabled? else return unless active? end @detected.available.each do |notifier| notifier.notify(message, message_opts.dup) end end
ruby
def notify(message, message_opts = {}) if _client? return unless enabled? else return unless active? end @detected.available.each do |notifier| notifier.notify(message, message_opts.dup) end end
[ "def", "notify", "(", "message", ",", "message_opts", "=", "{", "}", ")", "if", "_client?", "return", "unless", "enabled?", "else", "return", "unless", "active?", "end", "@detected", ".", "available", ".", "each", "do", "|", "notifier", "|", "notifier", ".", "notify", "(", "message", ",", "message_opts", ".", "dup", ")", "end", "end" ]
Show a system notification with all configured notifiers. @param [String] message the message to show @option opts [Symbol, String] image the image symbol or path to an image @option opts [String] title the notification title
[ "Show", "a", "system", "notification", "with", "all", "configured", "notifiers", "." ]
e654d6abc02549f09b970d21f143db15d546bfcc
https://github.com/guard/notiffany/blob/e654d6abc02549f09b970d21f143db15d546bfcc/lib/notiffany/notifier.rb#L148-L158
train
turn-project/turn
lib/turn/controller.rb
Turn.Controller.runner
def runner @runner ||= ( require 'turn/runners/minirunner' case config.runmode when :marshal Turn::MiniRunner when :solo require 'turn/runners/solorunner' Turn::SoloRunner when :cross require 'turn/runners/crossrunner' Turn::CrossRunner else Turn::MiniRunner end ) end
ruby
def runner @runner ||= ( require 'turn/runners/minirunner' case config.runmode when :marshal Turn::MiniRunner when :solo require 'turn/runners/solorunner' Turn::SoloRunner when :cross require 'turn/runners/crossrunner' Turn::CrossRunner else Turn::MiniRunner end ) end
[ "def", "runner", "@runner", "||=", "(", "require", "'turn/runners/minirunner'", "case", "config", ".", "runmode", "when", ":marshal", "Turn", "::", "MiniRunner", "when", ":solo", "require", "'turn/runners/solorunner'", "Turn", "::", "SoloRunner", "when", ":cross", "require", "'turn/runners/crossrunner'", "Turn", "::", "CrossRunner", "else", "Turn", "::", "MiniRunner", "end", ")", "end" ]
Insatance of Runner, selected based on format and runmode.
[ "Insatance", "of", "Runner", "selected", "based", "on", "format", "and", "runmode", "." ]
8ef637f0806217a3ad39f8f9742808dc37f57a33
https://github.com/turn-project/turn/blob/8ef637f0806217a3ad39f8f9742808dc37f57a33/lib/turn/controller.rb#L41-L58
train
turn-project/turn
lib/turn/reporters/pretty_reporter.rb
Turn.PrettyReporter.pass
def pass(message=nil) banner PASS if message message = Colorize.magenta(message) message = message.to_s.tabto(TAB_SIZE) io.puts(message) end end
ruby
def pass(message=nil) banner PASS if message message = Colorize.magenta(message) message = message.to_s.tabto(TAB_SIZE) io.puts(message) end end
[ "def", "pass", "(", "message", "=", "nil", ")", "banner", "PASS", "if", "message", "message", "=", "Colorize", ".", "magenta", "(", "message", ")", "message", "=", "message", ".", "to_s", ".", "tabto", "(", "TAB_SIZE", ")", "io", ".", "puts", "(", "message", ")", "end", "end" ]
Invoked when a test passes.
[ "Invoked", "when", "a", "test", "passes", "." ]
8ef637f0806217a3ad39f8f9742808dc37f57a33
https://github.com/turn-project/turn/blob/8ef637f0806217a3ad39f8f9742808dc37f57a33/lib/turn/reporters/pretty_reporter.rb#L50-L59
train
turn-project/turn
lib/turn/reporters/pretty_reporter.rb
Turn.PrettyReporter.finish_suite
def finish_suite(suite) total = colorize_count("%d tests", suite.count_tests, :bold) passes = colorize_count("%d passed", suite.count_passes, :pass) assertions = colorize_count("%d assertions", suite.count_assertions, nil) failures = colorize_count("%d failures", suite.count_failures, :fail) errors = colorize_count("%d errors", suite.count_errors, :error) skips = colorize_count("%d skips", suite.count_skips, :skip) io.puts "Finished in %.6f seconds." % (Time.now - @time) io.puts io.puts [ total, passes, failures, errors, skips, assertions ].join(", ") # Please keep this newline, since it will be useful when after test case # there will be other lines. For example "rake aborted!" or kind of. io.puts end
ruby
def finish_suite(suite) total = colorize_count("%d tests", suite.count_tests, :bold) passes = colorize_count("%d passed", suite.count_passes, :pass) assertions = colorize_count("%d assertions", suite.count_assertions, nil) failures = colorize_count("%d failures", suite.count_failures, :fail) errors = colorize_count("%d errors", suite.count_errors, :error) skips = colorize_count("%d skips", suite.count_skips, :skip) io.puts "Finished in %.6f seconds." % (Time.now - @time) io.puts io.puts [ total, passes, failures, errors, skips, assertions ].join(", ") # Please keep this newline, since it will be useful when after test case # there will be other lines. For example "rake aborted!" or kind of. io.puts end
[ "def", "finish_suite", "(", "suite", ")", "total", "=", "colorize_count", "(", "\"%d tests\"", ",", "suite", ".", "count_tests", ",", ":bold", ")", "passes", "=", "colorize_count", "(", "\"%d passed\"", ",", "suite", ".", "count_passes", ",", ":pass", ")", "assertions", "=", "colorize_count", "(", "\"%d assertions\"", ",", "suite", ".", "count_assertions", ",", "nil", ")", "failures", "=", "colorize_count", "(", "\"%d failures\"", ",", "suite", ".", "count_failures", ",", ":fail", ")", "errors", "=", "colorize_count", "(", "\"%d errors\"", ",", "suite", ".", "count_errors", ",", ":error", ")", "skips", "=", "colorize_count", "(", "\"%d skips\"", ",", "suite", ".", "count_skips", ",", ":skip", ")", "io", ".", "puts", "\"Finished in %.6f seconds.\"", "%", "(", "Time", ".", "now", "-", "@time", ")", "io", ".", "puts", "io", ".", "puts", "[", "total", ",", "passes", ",", "failures", ",", "errors", ",", "skips", ",", "assertions", "]", ".", "join", "(", "\", \"", ")", "io", ".", "puts", "end" ]
After all tests are run, this is the last observable action.
[ "After", "all", "tests", "are", "run", "this", "is", "the", "last", "observable", "action", "." ]
8ef637f0806217a3ad39f8f9742808dc37f57a33
https://github.com/turn-project/turn/blob/8ef637f0806217a3ad39f8f9742808dc37f57a33/lib/turn/reporters/pretty_reporter.rb#L89-L105
train
turn-project/turn
lib/turn/reporters/pretty_reporter.rb
Turn.PrettyReporter.colorize_count
def colorize_count(str, count, colorize_method) str= str % [count] str= Colorize.send(colorize_method, str) if colorize_method and count != 0 str end
ruby
def colorize_count(str, count, colorize_method) str= str % [count] str= Colorize.send(colorize_method, str) if colorize_method and count != 0 str end
[ "def", "colorize_count", "(", "str", ",", "count", ",", "colorize_method", ")", "str", "=", "str", "%", "[", "count", "]", "str", "=", "Colorize", ".", "send", "(", "colorize_method", ",", "str", ")", "if", "colorize_method", "and", "count", "!=", "0", "str", "end" ]
Creates an optionally-colorized string describing the number of occurances an event occurred. @param [String] str A printf-style string that expects an integer argument (i.e. the count) @param [Integer] count The number of occurances of the event being described. @param [nil, Symbol] colorize_method The method on Colorize to call in order to apply color to the result, or nil to not apply any coloring at all.
[ "Creates", "an", "optionally", "-", "colorized", "string", "describing", "the", "number", "of", "occurances", "an", "event", "occurred", "." ]
8ef637f0806217a3ad39f8f9742808dc37f57a33
https://github.com/turn-project/turn/blob/8ef637f0806217a3ad39f8f9742808dc37f57a33/lib/turn/reporters/pretty_reporter.rb#L114-L118
train
turn-project/turn
lib/turn/reporters/pretty_reporter.rb
Turn.PrettyReporter.prettify
def prettify(raised, message=nil) # Get message from raised, if not given message ||= raised.message backtrace = raised.respond_to?(:backtrace) ? raised.backtrace : raised.location # Filter and clean backtrace backtrace = clean_backtrace(backtrace) # Add trace mark to first line. backtrace.first.insert(0, TRACE_MARK) io.puts Colorize.bold(message.tabto(TAB_SIZE)) io.puts backtrace.shift.tabto(TAB_SIZE - TRACE_MARK.length) io.puts backtrace.join("\n").tabto(TAB_SIZE) io.puts end
ruby
def prettify(raised, message=nil) # Get message from raised, if not given message ||= raised.message backtrace = raised.respond_to?(:backtrace) ? raised.backtrace : raised.location # Filter and clean backtrace backtrace = clean_backtrace(backtrace) # Add trace mark to first line. backtrace.first.insert(0, TRACE_MARK) io.puts Colorize.bold(message.tabto(TAB_SIZE)) io.puts backtrace.shift.tabto(TAB_SIZE - TRACE_MARK.length) io.puts backtrace.join("\n").tabto(TAB_SIZE) io.puts end
[ "def", "prettify", "(", "raised", ",", "message", "=", "nil", ")", "message", "||=", "raised", ".", "message", "backtrace", "=", "raised", ".", "respond_to?", "(", ":backtrace", ")", "?", "raised", ".", "backtrace", ":", "raised", ".", "location", "backtrace", "=", "clean_backtrace", "(", "backtrace", ")", "backtrace", ".", "first", ".", "insert", "(", "0", ",", "TRACE_MARK", ")", "io", ".", "puts", "Colorize", ".", "bold", "(", "message", ".", "tabto", "(", "TAB_SIZE", ")", ")", "io", ".", "puts", "backtrace", ".", "shift", ".", "tabto", "(", "TAB_SIZE", "-", "TRACE_MARK", ".", "length", ")", "io", ".", "puts", "backtrace", ".", "join", "(", "\"\\n\"", ")", ".", "tabto", "(", "TAB_SIZE", ")", "io", ".", "puts", "end" ]
Cleanups and prints test payload Example: fail is not 1 @ test/test_runners.rb:46:in `test_autorun_with_trace' bin/turn:4:in `<main>'
[ "Cleanups", "and", "prints", "test", "payload" ]
8ef637f0806217a3ad39f8f9742808dc37f57a33
https://github.com/turn-project/turn/blob/8ef637f0806217a3ad39f8f9742808dc37f57a33/lib/turn/reporters/pretty_reporter.rb#L147-L163
train
turn-project/turn
lib/turn/command.rb
Turn.Command.main
def main(*argv) option_parser.parse!(argv) @loadpath = ['lib'] if loadpath.empty? tests = ARGV.empty? ? nil : argv.dup #config = Turn::Configuration.new do |c| config = Turn.config do |c| c.live = live c.log = log c.loadpath = loadpath c.requires = requires c.tests = tests c.runmode = runmode c.format = outmode c.mode = decmode c.pattern = pattern c.matchcase = matchcase c.trace = trace c.natural = natural c.verbose = verbose c.mark = mark c.ansi = ansi unless ansi.nil? end controller = Turn::Controller.new(config) #result = controller.start #if result # exit(result.passed? ? 0 : -1) #else # no tests # exit(-1) #end controller.start #exit(success ? 0 : -1) end
ruby
def main(*argv) option_parser.parse!(argv) @loadpath = ['lib'] if loadpath.empty? tests = ARGV.empty? ? nil : argv.dup #config = Turn::Configuration.new do |c| config = Turn.config do |c| c.live = live c.log = log c.loadpath = loadpath c.requires = requires c.tests = tests c.runmode = runmode c.format = outmode c.mode = decmode c.pattern = pattern c.matchcase = matchcase c.trace = trace c.natural = natural c.verbose = verbose c.mark = mark c.ansi = ansi unless ansi.nil? end controller = Turn::Controller.new(config) #result = controller.start #if result # exit(result.passed? ? 0 : -1) #else # no tests # exit(-1) #end controller.start #exit(success ? 0 : -1) end
[ "def", "main", "(", "*", "argv", ")", "option_parser", ".", "parse!", "(", "argv", ")", "@loadpath", "=", "[", "'lib'", "]", "if", "loadpath", ".", "empty?", "tests", "=", "ARGV", ".", "empty?", "?", "nil", ":", "argv", ".", "dup", "config", "=", "Turn", ".", "config", "do", "|", "c", "|", "c", ".", "live", "=", "live", "c", ".", "log", "=", "log", "c", ".", "loadpath", "=", "loadpath", "c", ".", "requires", "=", "requires", "c", ".", "tests", "=", "tests", "c", ".", "runmode", "=", "runmode", "c", ".", "format", "=", "outmode", "c", ".", "mode", "=", "decmode", "c", ".", "pattern", "=", "pattern", "c", ".", "matchcase", "=", "matchcase", "c", ".", "trace", "=", "trace", "c", ".", "natural", "=", "natural", "c", ".", "verbose", "=", "verbose", "c", ".", "mark", "=", "mark", "c", ".", "ansi", "=", "ansi", "unless", "ansi", ".", "nil?", "end", "controller", "=", "Turn", "::", "Controller", ".", "new", "(", "config", ")", "controller", ".", "start", "end" ]
Run command.
[ "Run", "command", "." ]
8ef637f0806217a3ad39f8f9742808dc37f57a33
https://github.com/turn-project/turn/blob/8ef637f0806217a3ad39f8f9742808dc37f57a33/lib/turn/command.rb#L109-L146
train
turn-project/turn
lib/turn/configuration.rb
Turn.Configuration.files
def files @files ||= ( fs = tests.map do |t| File.directory?(t) ? Dir[File.join(t, '**', '*')] : Dir[t] end fs = fs.flatten.reject{ |f| File.directory?(f) } ex = exclude.map do |x| File.directory?(x) ? Dir[File.join(x, '**', '*')] : Dir[x] end ex = ex.flatten.reject{ |f| File.directory?(f) } (fs - ex).uniq.map{ |f| File.expand_path(f) } ).flatten end
ruby
def files @files ||= ( fs = tests.map do |t| File.directory?(t) ? Dir[File.join(t, '**', '*')] : Dir[t] end fs = fs.flatten.reject{ |f| File.directory?(f) } ex = exclude.map do |x| File.directory?(x) ? Dir[File.join(x, '**', '*')] : Dir[x] end ex = ex.flatten.reject{ |f| File.directory?(f) } (fs - ex).uniq.map{ |f| File.expand_path(f) } ).flatten end
[ "def", "files", "@files", "||=", "(", "fs", "=", "tests", ".", "map", "do", "|", "t", "|", "File", ".", "directory?", "(", "t", ")", "?", "Dir", "[", "File", ".", "join", "(", "t", ",", "'**'", ",", "'*'", ")", "]", ":", "Dir", "[", "t", "]", "end", "fs", "=", "fs", ".", "flatten", ".", "reject", "{", "|", "f", "|", "File", ".", "directory?", "(", "f", ")", "}", "ex", "=", "exclude", ".", "map", "do", "|", "x", "|", "File", ".", "directory?", "(", "x", ")", "?", "Dir", "[", "File", ".", "join", "(", "x", ",", "'**'", ",", "'*'", ")", "]", ":", "Dir", "[", "x", "]", "end", "ex", "=", "ex", ".", "flatten", ".", "reject", "{", "|", "f", "|", "File", ".", "directory?", "(", "f", ")", "}", "(", "fs", "-", "ex", ")", ".", "uniq", ".", "map", "{", "|", "f", "|", "File", ".", "expand_path", "(", "f", ")", "}", ")", ".", "flatten", "end" ]
Test files.
[ "Test", "files", "." ]
8ef637f0806217a3ad39f8f9742808dc37f57a33
https://github.com/turn-project/turn/blob/8ef637f0806217a3ad39f8f9742808dc37f57a33/lib/turn/configuration.rb#L163-L177
train
turn-project/turn
lib/turn/configuration.rb
Turn.Configuration.reporter_class
def reporter_class rpt_format = format || :pretty class_name = rpt_format.to_s.capitalize + "Reporter" path = "turn/reporters/#{rpt_format}_reporter" [File.expand_path('~'), Dir.pwd].each do |dir| file = File.join(dir, ".turn", "reporters", "#{rpt_format}_reporter.rb") path = file if File.exist?(file) end require path Turn.const_get(class_name) end
ruby
def reporter_class rpt_format = format || :pretty class_name = rpt_format.to_s.capitalize + "Reporter" path = "turn/reporters/#{rpt_format}_reporter" [File.expand_path('~'), Dir.pwd].each do |dir| file = File.join(dir, ".turn", "reporters", "#{rpt_format}_reporter.rb") path = file if File.exist?(file) end require path Turn.const_get(class_name) end
[ "def", "reporter_class", "rpt_format", "=", "format", "||", ":pretty", "class_name", "=", "rpt_format", ".", "to_s", ".", "capitalize", "+", "\"Reporter\"", "path", "=", "\"turn/reporters/#{rpt_format}_reporter\"", "[", "File", ".", "expand_path", "(", "'~'", ")", ",", "Dir", ".", "pwd", "]", ".", "each", "do", "|", "dir", "|", "file", "=", "File", ".", "join", "(", "dir", ",", "\".turn\"", ",", "\"reporters\"", ",", "\"#{rpt_format}_reporter.rb\"", ")", "path", "=", "file", "if", "File", ".", "exist?", "(", "file", ")", "end", "require", "path", "Turn", ".", "const_get", "(", "class_name", ")", "end" ]
Load reporter based on output mode and return its class.
[ "Load", "reporter", "based", "on", "output", "mode", "and", "return", "its", "class", "." ]
8ef637f0806217a3ad39f8f9742808dc37f57a33
https://github.com/turn-project/turn/blob/8ef637f0806217a3ad39f8f9742808dc37f57a33/lib/turn/configuration.rb#L190-L204
train
turn-project/turn
lib/turn/runners/minirunner.rb
Turn.MiniRunner.start
def start(args=[]) # minitest changed #run in 6023c879cf3d5169953e on April 6th, 2011 if ::MiniTest::Unit.respond_to?(:runner=) ::MiniTest::Unit.runner = self end # FIXME: why isn't @test_count set? run(args) return @turn_suite end
ruby
def start(args=[]) # minitest changed #run in 6023c879cf3d5169953e on April 6th, 2011 if ::MiniTest::Unit.respond_to?(:runner=) ::MiniTest::Unit.runner = self end # FIXME: why isn't @test_count set? run(args) return @turn_suite end
[ "def", "start", "(", "args", "=", "[", "]", ")", "if", "::", "MiniTest", "::", "Unit", ".", "respond_to?", "(", ":runner=", ")", "::", "MiniTest", "::", "Unit", ".", "runner", "=", "self", "end", "run", "(", "args", ")", "return", "@turn_suite", "end" ]
Turn calls this method to start the test run.
[ "Turn", "calls", "this", "method", "to", "start", "the", "test", "run", "." ]
8ef637f0806217a3ad39f8f9742808dc37f57a33
https://github.com/turn-project/turn/blob/8ef637f0806217a3ad39f8f9742808dc37f57a33/lib/turn/runners/minirunner.rb#L35-L43
train
stripe/poncho
lib/poncho/request.rb
Poncho.Request.action_dispatch_params
def action_dispatch_params action_dispatch_params = env['action_dispatch.request.path_parameters'] || {} action_dispatch_params.inject({}) {|hash, (key, value)| hash[key.to_s] = value; hash } end
ruby
def action_dispatch_params action_dispatch_params = env['action_dispatch.request.path_parameters'] || {} action_dispatch_params.inject({}) {|hash, (key, value)| hash[key.to_s] = value; hash } end
[ "def", "action_dispatch_params", "action_dispatch_params", "=", "env", "[", "'action_dispatch.request.path_parameters'", "]", "||", "{", "}", "action_dispatch_params", ".", "inject", "(", "{", "}", ")", "{", "|", "hash", ",", "(", "key", ",", "value", ")", "|", "hash", "[", "key", ".", "to_s", "]", "=", "value", ";", "hash", "}", "end" ]
Pass in params from Rails routing
[ "Pass", "in", "params", "from", "Rails", "routing" ]
c056e16ddc7932af0d48d7c754dd754744d6b5d2
https://github.com/stripe/poncho/blob/c056e16ddc7932af0d48d7c754dd754744d6b5d2/lib/poncho/request.rb#L59-L62
train
theforeman/foreman_chef
app/services/foreman_chef/chef_server_importer.rb
ForemanChef.ChefServerImporter.changes
def changes changes = {'new' => {}, 'obsolete' => {}, 'updated' => {}} if @environment.nil? new_environments.each do |env| changes['new'][env] = {} end old_environments.each do |env| changes['obsolete'][env] = {} end else env = @environment changes['new'][env] = {} if new_environments.include?(@environment) changes['obsolete'][env] = {} if old_environments.include?(@environment) end changes end
ruby
def changes changes = {'new' => {}, 'obsolete' => {}, 'updated' => {}} if @environment.nil? new_environments.each do |env| changes['new'][env] = {} end old_environments.each do |env| changes['obsolete'][env] = {} end else env = @environment changes['new'][env] = {} if new_environments.include?(@environment) changes['obsolete'][env] = {} if old_environments.include?(@environment) end changes end
[ "def", "changes", "changes", "=", "{", "'new'", "=>", "{", "}", ",", "'obsolete'", "=>", "{", "}", ",", "'updated'", "=>", "{", "}", "}", "if", "@environment", ".", "nil?", "new_environments", ".", "each", "do", "|", "env", "|", "changes", "[", "'new'", "]", "[", "env", "]", "=", "{", "}", "end", "old_environments", ".", "each", "do", "|", "env", "|", "changes", "[", "'obsolete'", "]", "[", "env", "]", "=", "{", "}", "end", "else", "env", "=", "@environment", "changes", "[", "'new'", "]", "[", "env", "]", "=", "{", "}", "if", "new_environments", ".", "include?", "(", "@environment", ")", "changes", "[", "'obsolete'", "]", "[", "env", "]", "=", "{", "}", "if", "old_environments", ".", "include?", "(", "@environment", ")", "end", "changes", "end" ]
return changes hash, currently exists to keep compatibility with importer html
[ "return", "changes", "hash", "currently", "exists", "to", "keep", "compatibility", "with", "importer", "html" ]
cc06963dce795dee98e22bafa446abae5003de4b
https://github.com/theforeman/foreman_chef/blob/cc06963dce795dee98e22bafa446abae5003de4b/app/services/foreman_chef/chef_server_importer.rb#L24-L41
train
stripe/poncho
lib/poncho/errors.rb
Poncho.Errors.as_json
def as_json(options=nil) return {} if messages.empty? attribute, types = messages.first type = types.first { :error => { :param => attribute, :type => type, :message => nil } } end
ruby
def as_json(options=nil) return {} if messages.empty? attribute, types = messages.first type = types.first { :error => { :param => attribute, :type => type, :message => nil } } end
[ "def", "as_json", "(", "options", "=", "nil", ")", "return", "{", "}", "if", "messages", ".", "empty?", "attribute", ",", "types", "=", "messages", ".", "first", "type", "=", "types", ".", "first", "{", ":error", "=>", "{", ":param", "=>", "attribute", ",", ":type", "=>", "type", ",", ":message", "=>", "nil", "}", "}", "end" ]
Return the first error we get
[ "Return", "the", "first", "error", "we", "get" ]
c056e16ddc7932af0d48d7c754dd754744d6b5d2
https://github.com/stripe/poncho/blob/c056e16ddc7932af0d48d7c754dd754744d6b5d2/lib/poncho/errors.rb#L107-L119
train
theforeman/foreman_chef
app/models/foreman_chef/fact_parser.rb
ForemanChef.FactParser.set_additional_attributes
def set_additional_attributes(attributes, name) if name =~ VIRTUAL_NAMES attributes[:virtual] = true if $1.nil? && name =~ BRIDGES attributes[:bridge] = true else attributes[:attached_to] = $1 end else attributes[:virtual] = false end attributes end
ruby
def set_additional_attributes(attributes, name) if name =~ VIRTUAL_NAMES attributes[:virtual] = true if $1.nil? && name =~ BRIDGES attributes[:bridge] = true else attributes[:attached_to] = $1 end else attributes[:virtual] = false end attributes end
[ "def", "set_additional_attributes", "(", "attributes", ",", "name", ")", "if", "name", "=~", "VIRTUAL_NAMES", "attributes", "[", ":virtual", "]", "=", "true", "if", "$1", ".", "nil?", "&&", "name", "=~", "BRIDGES", "attributes", "[", ":bridge", "]", "=", "true", "else", "attributes", "[", ":attached_to", "]", "=", "$1", "end", "else", "attributes", "[", ":virtual", "]", "=", "false", "end", "attributes", "end" ]
adds attributes like virtual
[ "adds", "attributes", "like", "virtual" ]
cc06963dce795dee98e22bafa446abae5003de4b
https://github.com/theforeman/foreman_chef/blob/cc06963dce795dee98e22bafa446abae5003de4b/app/models/foreman_chef/fact_parser.rb#L140-L152
train
stripe/poncho
lib/poncho/resource.rb
Poncho.Resource.param_for_validation?
def param_for_validation?(name) if respond_to?(name) !send(name).nil? else !param_before_type_cast(name).nil? end end
ruby
def param_for_validation?(name) if respond_to?(name) !send(name).nil? else !param_before_type_cast(name).nil? end end
[ "def", "param_for_validation?", "(", "name", ")", "if", "respond_to?", "(", "name", ")", "!", "send", "(", "name", ")", ".", "nil?", "else", "!", "param_before_type_cast", "(", "name", ")", ".", "nil?", "end", "end" ]
Validation We want to validate an attribute if its uncoerced value is not nil
[ "Validation", "We", "want", "to", "validate", "an", "attribute", "if", "its", "uncoerced", "value", "is", "not", "nil" ]
c056e16ddc7932af0d48d7c754dd754744d6b5d2
https://github.com/stripe/poncho/blob/c056e16ddc7932af0d48d7c754dd754744d6b5d2/lib/poncho/resource.rb#L58-L64
train
yamasolutions/integral
app/models/integral/post.rb
Integral.Post.set_tags_context
def set_tags_context return unless tag_list_changed? || status_changed? || !persisted? # Give all tags current context set_tag_list_on(tag_context, tag_list) # Clear previous contexts self.tag_list = [] inactive_tag_contexts.each do |context| set_tag_list_on(context, []) end end
ruby
def set_tags_context return unless tag_list_changed? || status_changed? || !persisted? # Give all tags current context set_tag_list_on(tag_context, tag_list) # Clear previous contexts self.tag_list = [] inactive_tag_contexts.each do |context| set_tag_list_on(context, []) end end
[ "def", "set_tags_context", "return", "unless", "tag_list_changed?", "||", "status_changed?", "||", "!", "persisted?", "set_tag_list_on", "(", "tag_context", ",", "tag_list", ")", "self", ".", "tag_list", "=", "[", "]", "inactive_tag_contexts", ".", "each", "do", "|", "context", "|", "set_tag_list_on", "(", "context", ",", "[", "]", ")", "end", "end" ]
Set the context of tags so that draft and archived tags are not displayed publicly
[ "Set", "the", "context", "of", "tags", "so", "that", "draft", "and", "archived", "tags", "are", "not", "displayed", "publicly" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/app/models/integral/post.rb#L125-L136
train
yamasolutions/integral
app/models/integral/user.rb
Integral.User.role?
def role?(role_sym) role_sym = [role_sym] unless role_sym.is_a?(Array) roles.map { |r| r.name.underscore.to_sym }.any? { |user_role| role_sym.include?(user_role) } end
ruby
def role?(role_sym) role_sym = [role_sym] unless role_sym.is_a?(Array) roles.map { |r| r.name.underscore.to_sym }.any? { |user_role| role_sym.include?(user_role) } end
[ "def", "role?", "(", "role_sym", ")", "role_sym", "=", "[", "role_sym", "]", "unless", "role_sym", ".", "is_a?", "(", "Array", ")", "roles", ".", "map", "{", "|", "r", "|", "r", ".", "name", ".", "underscore", ".", "to_sym", "}", ".", "any?", "{", "|", "user_role", "|", "role_sym", ".", "include?", "(", "user_role", ")", "}", "end" ]
Checks if the User has a given role @param role_sym [Symbol] role(s) to check - Can be array of symbols or one symbol @return [Boolean] whether or not user has role(s)
[ "Checks", "if", "the", "User", "has", "a", "given", "role" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/app/models/integral/user.rb#L31-L35
train
yamasolutions/integral
lib/integral/list_renderer.rb
Integral.ListRenderer.render
def render rendered_items = '' list.list_items.each do |list_item| rendered_items += render_item(list_item) end content_tag opts[:wrapper_element], rendered_items, html_options, false end
ruby
def render rendered_items = '' list.list_items.each do |list_item| rendered_items += render_item(list_item) end content_tag opts[:wrapper_element], rendered_items, html_options, false end
[ "def", "render", "rendered_items", "=", "''", "list", ".", "list_items", ".", "each", "do", "|", "list_item", "|", "rendered_items", "+=", "render_item", "(", "list_item", ")", "end", "content_tag", "opts", "[", ":wrapper_element", "]", ",", "rendered_items", ",", "html_options", ",", "false", "end" ]
Renders the provided list @return [String] the rendered list item
[ "Renders", "the", "provided", "list" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/lib/integral/list_renderer.rb#L42-L50
train
yamasolutions/integral
spec/support/features/helpers.rb
Features.Helpers.sign_in
def sign_in(user=create(:user)) visit new_user_session_path within("#new_user") do fill_in 'user_email', with: user.email fill_in 'user_password', with: user.password end click_button 'Log in' end
ruby
def sign_in(user=create(:user)) visit new_user_session_path within("#new_user") do fill_in 'user_email', with: user.email fill_in 'user_password', with: user.password end click_button 'Log in' end
[ "def", "sign_in", "(", "user", "=", "create", "(", ":user", ")", ")", "visit", "new_user_session_path", "within", "(", "\"#new_user\"", ")", "do", "fill_in", "'user_email'", ",", "with", ":", "user", ".", "email", "fill_in", "'user_password'", ",", "with", ":", "user", ".", "password", "end", "click_button", "'Log in'", "end" ]
Signs a user in @param user [Integral::User] user to sign in
[ "Signs", "a", "user", "in" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/spec/support/features/helpers.rb#L6-L15
train
yamasolutions/integral
app/controllers/integral/posts_controller.rb
Integral.PostsController.find_related_posts
def find_related_posts @related_posts = @post.find_related_tags.limit(amount_of_related_posts_to_display) amount_of_related_posts = @related_posts.length if amount_of_related_posts != amount_of_related_posts_to_display && (amount_of_related_posts + @popular_posts.length) >= amount_of_related_posts_to_display @related_posts = @related_posts.to_a.concat(@popular_posts[0...amount_of_related_posts_to_display - amount_of_related_posts]) end end
ruby
def find_related_posts @related_posts = @post.find_related_tags.limit(amount_of_related_posts_to_display) amount_of_related_posts = @related_posts.length if amount_of_related_posts != amount_of_related_posts_to_display && (amount_of_related_posts + @popular_posts.length) >= amount_of_related_posts_to_display @related_posts = @related_posts.to_a.concat(@popular_posts[0...amount_of_related_posts_to_display - amount_of_related_posts]) end end
[ "def", "find_related_posts", "@related_posts", "=", "@post", ".", "find_related_tags", ".", "limit", "(", "amount_of_related_posts_to_display", ")", "amount_of_related_posts", "=", "@related_posts", ".", "length", "if", "amount_of_related_posts", "!=", "amount_of_related_posts_to_display", "&&", "(", "amount_of_related_posts", "+", "@popular_posts", ".", "length", ")", ">=", "amount_of_related_posts_to_display", "@related_posts", "=", "@related_posts", ".", "to_a", ".", "concat", "(", "@popular_posts", "[", "0", "...", "amount_of_related_posts_to_display", "-", "amount_of_related_posts", "]", ")", "end", "end" ]
Creates array of related posts. If enough related posts do not exist uses popular posts
[ "Creates", "array", "of", "related", "posts", ".", "If", "enough", "related", "posts", "do", "not", "exist", "uses", "popular", "posts" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/app/controllers/integral/posts_controller.rb#L39-L46
train
yamasolutions/integral
app/uploaders/integral/image_uploader.rb
Integral.ImageUploader.full_filename
def full_filename(for_file) parent_name = super(for_file) extension = File.extname(parent_name) base_name = parent_name.chomp(extension) base_name = base_name[version_name.size.succ..-1] if version_name [base_name, version_name].compact.join('-') + extension end
ruby
def full_filename(for_file) parent_name = super(for_file) extension = File.extname(parent_name) base_name = parent_name.chomp(extension) base_name = base_name[version_name.size.succ..-1] if version_name [base_name, version_name].compact.join('-') + extension end
[ "def", "full_filename", "(", "for_file", ")", "parent_name", "=", "super", "(", "for_file", ")", "extension", "=", "File", ".", "extname", "(", "parent_name", ")", "base_name", "=", "parent_name", ".", "chomp", "(", "extension", ")", "base_name", "=", "base_name", "[", "version_name", ".", "size", ".", "succ", "..", "-", "1", "]", "if", "version_name", "[", "base_name", ",", "version_name", "]", ".", "compact", ".", "join", "(", "'-'", ")", "+", "extension", "end" ]
Override full_filename to set version name at the end
[ "Override", "full_filename", "to", "set", "version", "name", "at", "the", "end" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/app/uploaders/integral/image_uploader.rb#L57-L63
train
yamasolutions/integral
app/uploaders/integral/image_uploader.rb
Integral.ImageUploader.full_original_filename
def full_original_filename parent_name = super extension = File.extname(parent_name) base_name = parent_name.chomp(extension) base_name = base_name[version_name.size.succ..-1] if version_name [base_name, version_name].compact.join('-') + extension end
ruby
def full_original_filename parent_name = super extension = File.extname(parent_name) base_name = parent_name.chomp(extension) base_name = base_name[version_name.size.succ..-1] if version_name [base_name, version_name].compact.join('-') + extension end
[ "def", "full_original_filename", "parent_name", "=", "super", "extension", "=", "File", ".", "extname", "(", "parent_name", ")", "base_name", "=", "parent_name", ".", "chomp", "(", "extension", ")", "base_name", "=", "base_name", "[", "version_name", ".", "size", ".", "succ", "..", "-", "1", "]", "if", "version_name", "[", "base_name", ",", "version_name", "]", ".", "compact", ".", "join", "(", "'-'", ")", "+", "extension", "end" ]
Override full_original_filename to set version name at the end
[ "Override", "full_original_filename", "to", "set", "version", "name", "at", "the", "end" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/app/uploaders/integral/image_uploader.rb#L66-L72
train
yamasolutions/integral
app/helpers/integral/gallery_helper.rb
Integral.GalleryHelper.render_thumb_gallery
def render_thumb_gallery(list, opts = {}) opts.reverse_merge!( renderer: Integral::SwiperListRenderer, item_renderer: Integral::PartialListItemRenderer, item_renderer_opts: { partial_path: 'integral/shared/gallery/thumb_slide', wrapper_element: 'div', image_version: :small, html_classes: 'swiper-slide' } ) opts[:renderer].render(list, opts).html_safe end
ruby
def render_thumb_gallery(list, opts = {}) opts.reverse_merge!( renderer: Integral::SwiperListRenderer, item_renderer: Integral::PartialListItemRenderer, item_renderer_opts: { partial_path: 'integral/shared/gallery/thumb_slide', wrapper_element: 'div', image_version: :small, html_classes: 'swiper-slide' } ) opts[:renderer].render(list, opts).html_safe end
[ "def", "render_thumb_gallery", "(", "list", ",", "opts", "=", "{", "}", ")", "opts", ".", "reverse_merge!", "(", "renderer", ":", "Integral", "::", "SwiperListRenderer", ",", "item_renderer", ":", "Integral", "::", "PartialListItemRenderer", ",", "item_renderer_opts", ":", "{", "partial_path", ":", "'integral/shared/gallery/thumb_slide'", ",", "wrapper_element", ":", "'div'", ",", "image_version", ":", ":small", ",", "html_classes", ":", "'swiper-slide'", "}", ")", "opts", "[", ":renderer", "]", ".", "render", "(", "list", ",", "opts", ")", ".", "html_safe", "end" ]
Renders a thumbnail gallery
[ "Renders", "a", "thumbnail", "gallery" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/app/helpers/integral/gallery_helper.rb#L5-L18
train
yamasolutions/integral
app/models/integral/enquiry.rb
Integral.Enquiry.process
def process ContactMailer.forward_enquiry(self).deliver_later ContactMailer.auto_reply(self).deliver_later NewsletterSignup.create(name: name, email: email, context: context) if newsletter_opt_in? end
ruby
def process ContactMailer.forward_enquiry(self).deliver_later ContactMailer.auto_reply(self).deliver_later NewsletterSignup.create(name: name, email: email, context: context) if newsletter_opt_in? end
[ "def", "process", "ContactMailer", ".", "forward_enquiry", "(", "self", ")", ".", "deliver_later", "ContactMailer", ".", "auto_reply", "(", "self", ")", ".", "deliver_later", "NewsletterSignup", ".", "create", "(", "name", ":", "name", ",", "email", ":", "email", ",", "context", ":", "context", ")", "if", "newsletter_opt_in?", "end" ]
Forward the enquiry on and send an auto reply. Create newsletter signup if necessary
[ "Forward", "the", "enquiry", "on", "and", "send", "an", "auto", "reply", ".", "Create", "newsletter", "signup", "if", "necessary" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/app/models/integral/enquiry.rb#L17-L21
train
yamasolutions/integral
lib/integral/list_item_renderer.rb
Integral.ListItemRenderer.render_children
def render_children children = '' list_item.children.each do |child| children += self.class.render(child, opts) end children end
ruby
def render_children children = '' list_item.children.each do |child| children += self.class.render(child, opts) end children end
[ "def", "render_children", "children", "=", "''", "list_item", ".", "children", ".", "each", "do", "|", "child", "|", "children", "+=", "self", ".", "class", ".", "render", "(", "child", ",", "opts", ")", "end", "children", "end" ]
Loop over all list item children calling render on each @return [String] compiled string of all the rendered list item children
[ "Loop", "over", "all", "list", "item", "children", "calling", "render", "on", "each" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/lib/integral/list_item_renderer.rb#L65-L73
train
yamasolutions/integral
lib/integral/list_item_renderer.rb
Integral.ListItemRenderer.provide_attr
def provide_attr(attr) list_item_attr_value = list_item.public_send(attr) # Provide user supplied attr return list_item_attr_value if list_item_attr_value.present? # Provide object supplied attr return object_data[attr] if object_available? # Provide error - Object is linked but has been deleted return 'Object Unavailable' if list_item.object? && !object_available? # Provide empty string - no attr supplied and no object linked '' end
ruby
def provide_attr(attr) list_item_attr_value = list_item.public_send(attr) # Provide user supplied attr return list_item_attr_value if list_item_attr_value.present? # Provide object supplied attr return object_data[attr] if object_available? # Provide error - Object is linked but has been deleted return 'Object Unavailable' if list_item.object? && !object_available? # Provide empty string - no attr supplied and no object linked '' end
[ "def", "provide_attr", "(", "attr", ")", "list_item_attr_value", "=", "list_item", ".", "public_send", "(", "attr", ")", "return", "list_item_attr_value", "if", "list_item_attr_value", ".", "present?", "return", "object_data", "[", "attr", "]", "if", "object_available?", "return", "'Object Unavailable'", "if", "list_item", ".", "object?", "&&", "!", "object_available?", "''", "end" ]
Works out what the provided attr evaluates to. @param attr [Symbol] attribute to evaluate @return [String] value of attribute
[ "Works", "out", "what", "the", "provided", "attr", "evaluates", "to", "." ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/lib/integral/list_item_renderer.rb#L174-L188
train
yamasolutions/integral
app/decorators/integral/post_decorator.rb
Integral.PostDecorator.header_tags
def header_tags return I18n.t('integral.posts.show.subtitle') if object.tags_on('published').empty? header_tags = '' object.tags_on('published').each_with_index do |tag, i| header_tags += tag.name header_tags += ' | ' unless i == object.tags_on('published').size - 1 end header_tags end
ruby
def header_tags return I18n.t('integral.posts.show.subtitle') if object.tags_on('published').empty? header_tags = '' object.tags_on('published').each_with_index do |tag, i| header_tags += tag.name header_tags += ' | ' unless i == object.tags_on('published').size - 1 end header_tags end
[ "def", "header_tags", "return", "I18n", ".", "t", "(", "'integral.posts.show.subtitle'", ")", "if", "object", ".", "tags_on", "(", "'published'", ")", ".", "empty?", "header_tags", "=", "''", "object", ".", "tags_on", "(", "'published'", ")", ".", "each_with_index", "do", "|", "tag", ",", "i", "|", "header_tags", "+=", "tag", ".", "name", "header_tags", "+=", "' | '", "unless", "i", "==", "object", ".", "tags_on", "(", "'published'", ")", ".", "size", "-", "1", "end", "header_tags", "end" ]
Tags to be used within the header of an article to describe the subject
[ "Tags", "to", "be", "used", "within", "the", "header", "of", "an", "article", "to", "describe", "the", "subject" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/app/decorators/integral/post_decorator.rb#L40-L49
train
yamasolutions/integral
app/decorators/integral/post_decorator.rb
Integral.PostDecorator.preview_image
def preview_image(size = :small) preview_image = object&.preview_image&.url(size) return preview_image if preview_image.present? image(size, false) end
ruby
def preview_image(size = :small) preview_image = object&.preview_image&.url(size) return preview_image if preview_image.present? image(size, false) end
[ "def", "preview_image", "(", "size", "=", ":small", ")", "preview_image", "=", "object", "&.", "preview_image", "&.", "url", "(", "size", ")", "return", "preview_image", "if", "preview_image", ".", "present?", "image", "(", "size", ",", "false", ")", "end" ]
Preview image for the post if present. Otherwise returns featured image
[ "Preview", "image", "for", "the", "post", "if", "present", ".", "Otherwise", "returns", "featured", "image" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/app/decorators/integral/post_decorator.rb#L52-L57
train
yamasolutions/integral
app/decorators/integral/post_decorator.rb
Integral.PostDecorator.image
def image(size = :small, fallback = true) image = object&.image&.url(size) return image if image.present? h.image_url('integral/defaults/no_image_available.jpg') if fallback end
ruby
def image(size = :small, fallback = true) image = object&.image&.url(size) return image if image.present? h.image_url('integral/defaults/no_image_available.jpg') if fallback end
[ "def", "image", "(", "size", "=", ":small", ",", "fallback", "=", "true", ")", "image", "=", "object", "&.", "image", "&.", "url", "(", "size", ")", "return", "image", "if", "image", ".", "present?", "h", ".", "image_url", "(", "'integral/defaults/no_image_available.jpg'", ")", "if", "fallback", "end" ]
Image for the post if present. Otherwise returns default image
[ "Image", "for", "the", "post", "if", "present", ".", "Otherwise", "returns", "default", "image" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/app/decorators/integral/post_decorator.rb#L60-L65
train
yamasolutions/integral
app/helpers/integral/support_helper.rb
Integral.SupportHelper.anchor_to
def anchor_to(body, location) current_path = url_for(only_path: false) path = "#{current_path}##{location}" link_to body, path end
ruby
def anchor_to(body, location) current_path = url_for(only_path: false) path = "#{current_path}##{location}" link_to body, path end
[ "def", "anchor_to", "(", "body", ",", "location", ")", "current_path", "=", "url_for", "(", "only_path", ":", "false", ")", "path", "=", "\"#{current_path}##{location}\"", "link_to", "body", ",", "path", "end" ]
Creates an anchor link @param body [String] body of the link @param location [String] location of the anchor @return [String] anchor to a particular location of the current page
[ "Creates", "an", "anchor", "link" ]
d8077b6658c8b6713d97b44ff0e136f212354a25
https://github.com/yamasolutions/integral/blob/d8077b6658c8b6713d97b44ff0e136f212354a25/app/helpers/integral/support_helper.rb#L27-L32
train