repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
alloy/lowdown
lib/lowdown/client.rb
Lowdown.Client.send_notification
def send_notification(notification, delegate:, context: nil) raise ArgumentError, "Invalid notification: #{notification.inspect}" unless notification.valid? topic = notification.topic || @default_topic headers = {} headers["apns-expiration"] = (notification.expiration || 0).to_i headers["apns-id"] = notification.formatted_id headers["apns-priority"] = notification.priority if notification.priority headers["apns-topic"] = topic if topic body = notification.formatted_payload.to_json @connection.async.post(path: "/3/device/#{notification.token}", headers: headers, body: body, delegate: delegate, context: context) end
ruby
def send_notification(notification, delegate:, context: nil) raise ArgumentError, "Invalid notification: #{notification.inspect}" unless notification.valid? topic = notification.topic || @default_topic headers = {} headers["apns-expiration"] = (notification.expiration || 0).to_i headers["apns-id"] = notification.formatted_id headers["apns-priority"] = notification.priority if notification.priority headers["apns-topic"] = topic if topic body = notification.formatted_payload.to_json @connection.async.post(path: "/3/device/#{notification.token}", headers: headers, body: body, delegate: delegate, context: context) end
[ "def", "send_notification", "(", "notification", ",", "delegate", ":", ",", "context", ":", "nil", ")", "raise", "ArgumentError", ",", "\"Invalid notification: #{notification.inspect}\"", "unless", "notification", ".", "valid?", "topic", "=", "notification", ".", "topic", "||", "@default_topic", "headers", "=", "{", "}", "headers", "[", "\"apns-expiration\"", "]", "=", "(", "notification", ".", "expiration", "||", "0", ")", ".", "to_i", "headers", "[", "\"apns-id\"", "]", "=", "notification", ".", "formatted_id", "headers", "[", "\"apns-priority\"", "]", "=", "notification", ".", "priority", "if", "notification", ".", "priority", "headers", "[", "\"apns-topic\"", "]", "=", "topic", "if", "topic", "body", "=", "notification", ".", "formatted_payload", ".", "to_json", "@connection", ".", "async", ".", "post", "(", "path", ":", "\"/3/device/#{notification.token}\"", ",", "headers", ":", "headers", ",", "body", ":", "body", ",", "delegate", ":", "delegate", ",", "context", ":", "context", ")", "end" ]
Verifies the `notification` is valid and then sends it to the remote service. Response feedback is provided via a delegate mechanism. @note In general, you will probably want to use {#group} to be able to use {RequestGroup#send_notification}, which takes a traditional blocks-based callback approach. @see Connection#post @param [Notification] notification the notification object whose data to send to the service. @param [Connection::DelegateProtocol] delegate an object that implements the connection delegate protocol. @param [Object, nil] context any object that you want to be passed to the delegate once the response is back. @raise [ArgumentError] raised if the Notification is not {Notification#valid?}. @return [void]
[ "Verifies", "the", "notification", "is", "valid", "and", "then", "sends", "it", "to", "the", "remote", "service", ".", "Response", "feedback", "is", "provided", "via", "a", "delegate", "mechanism", "." ]
7a75185d2b93015c18b6093f6784938d42c021f7
https://github.com/alloy/lowdown/blob/7a75185d2b93015c18b6093f6784938d42c021f7/lib/lowdown/client.rb#L275-L292
train
xiewenwei/sneakers_packer
lib/sneakers_packer/rpc_client.rb
SneakersPacker.RpcClient.call
def call(request, options = {}) add_request(request) @publisher.publish(request.message, routing_key: request.name, correlation_id: request.call_id, reply_to: @subscriber.reply_queue_name) timeout = (options[:timeout] || SneakersPacker.conf.rpc_timeout).to_i client_lock.synchronize { request.condition.wait(client_lock, timeout) } remove_request(request) if request.processed? request.response_data else raise RemoteCallTimeoutError, "Remote call timeouts.Exceed #{timeout} seconds." end end
ruby
def call(request, options = {}) add_request(request) @publisher.publish(request.message, routing_key: request.name, correlation_id: request.call_id, reply_to: @subscriber.reply_queue_name) timeout = (options[:timeout] || SneakersPacker.conf.rpc_timeout).to_i client_lock.synchronize { request.condition.wait(client_lock, timeout) } remove_request(request) if request.processed? request.response_data else raise RemoteCallTimeoutError, "Remote call timeouts.Exceed #{timeout} seconds." end end
[ "def", "call", "(", "request", ",", "options", "=", "{", "}", ")", "add_request", "(", "request", ")", "@publisher", ".", "publish", "(", "request", ".", "message", ",", "routing_key", ":", "request", ".", "name", ",", "correlation_id", ":", "request", ".", "call_id", ",", "reply_to", ":", "@subscriber", ".", "reply_queue_name", ")", "timeout", "=", "(", "options", "[", ":timeout", "]", "||", "SneakersPacker", ".", "conf", ".", "rpc_timeout", ")", ".", "to_i", "client_lock", ".", "synchronize", "{", "request", ".", "condition", ".", "wait", "(", "client_lock", ",", "timeout", ")", "}", "remove_request", "(", "request", ")", "if", "request", ".", "processed?", "request", ".", "response_data", "else", "raise", "RemoteCallTimeoutError", ",", "\"Remote call timeouts.Exceed #{timeout} seconds.\"", "end", "end" ]
call remote service via rabbitmq rpc @param name route_key for service @param message @param options{timeout} [int] timeout. seconds. optional @return result of service @raise RemoteCallTimeoutError if timeout
[ "call", "remote", "service", "via", "rabbitmq", "rpc" ]
938286c2a275a63db89d14fec2deb9b8b8e61fbf
https://github.com/xiewenwei/sneakers_packer/blob/938286c2a275a63db89d14fec2deb9b8b8e61fbf/lib/sneakers_packer/rpc_client.rb#L20-L39
train
Squeegy/fleximage
lib/fleximage/helper.rb
Fleximage.Helper.embedded_image_tag
def embedded_image_tag(model, options = {}) model.load_image format = options[:format] || :jpg mime = Mime::Type.lookup_by_extension(format.to_s).to_s image = model.output_image(:format => format) data = Base64.encode64(image) options = { :alt => model.class.to_s }.merge(options) result = image_tag("data:#{mime};base64,#{data}", options) result.gsub(%r{src=".*/images/data:}, 'src="data:') rescue Fleximage::Model::MasterImageNotFound => e nil end
ruby
def embedded_image_tag(model, options = {}) model.load_image format = options[:format] || :jpg mime = Mime::Type.lookup_by_extension(format.to_s).to_s image = model.output_image(:format => format) data = Base64.encode64(image) options = { :alt => model.class.to_s }.merge(options) result = image_tag("data:#{mime};base64,#{data}", options) result.gsub(%r{src=".*/images/data:}, 'src="data:') rescue Fleximage::Model::MasterImageNotFound => e nil end
[ "def", "embedded_image_tag", "(", "model", ",", "options", "=", "{", "}", ")", "model", ".", "load_image", "format", "=", "options", "[", ":format", "]", "||", ":jpg", "mime", "=", "Mime", "::", "Type", ".", "lookup_by_extension", "(", "format", ".", "to_s", ")", ".", "to_s", "image", "=", "model", ".", "output_image", "(", ":format", "=>", "format", ")", "data", "=", "Base64", ".", "encode64", "(", "image", ")", "options", "=", "{", ":alt", "=>", "model", ".", "class", ".", "to_s", "}", ".", "merge", "(", "options", ")", "result", "=", "image_tag", "(", "\"data:#{mime};base64,#{data}\"", ",", "options", ")", "result", ".", "gsub", "(", "%r{", "}", ",", "'src=\"data:'", ")", "rescue", "Fleximage", "::", "Model", "::", "MasterImageNotFound", "=>", "e", "nil", "end" ]
Creates an image tag that links directly to image data. Recommended for displays of a temporary upload that is not saved to a record in the databse yet.
[ "Creates", "an", "image", "tag", "that", "links", "directly", "to", "image", "data", ".", "Recommended", "for", "displays", "of", "a", "temporary", "upload", "that", "is", "not", "saved", "to", "a", "record", "in", "the", "databse", "yet", "." ]
dd6a486c29df3f56c0347dc9a70273f9aaf432fd
https://github.com/Squeegy/fleximage/blob/dd6a486c29df3f56c0347dc9a70273f9aaf432fd/lib/fleximage/helper.rb#L6-L20
train
Squeegy/fleximage
lib/fleximage/helper.rb
Fleximage.Helper.link_to_edit_in_aviary
def link_to_edit_in_aviary(text, model, options = {}) key = aviary_image_hash(model) image_url = options.delete(:image_url) || url_for(:action => 'aviary_image', :id => model, :only_path => false, :key => key) post_url = options.delete(:image_update_url) || url_for(:action => 'aviary_image_update', :id => model, :only_path => false, :key => key) api_key = Fleximage::AviaryController.api_key url = "http://aviary.com/flash/aviary/index.aspx?tid=1&phoenix&apil=#{api_key}&loadurl=#{CGI.escape image_url}&posturl=#{CGI.escape post_url}" link_to text, url, { :target => 'aviary' }.merge(options) end
ruby
def link_to_edit_in_aviary(text, model, options = {}) key = aviary_image_hash(model) image_url = options.delete(:image_url) || url_for(:action => 'aviary_image', :id => model, :only_path => false, :key => key) post_url = options.delete(:image_update_url) || url_for(:action => 'aviary_image_update', :id => model, :only_path => false, :key => key) api_key = Fleximage::AviaryController.api_key url = "http://aviary.com/flash/aviary/index.aspx?tid=1&phoenix&apil=#{api_key}&loadurl=#{CGI.escape image_url}&posturl=#{CGI.escape post_url}" link_to text, url, { :target => 'aviary' }.merge(options) end
[ "def", "link_to_edit_in_aviary", "(", "text", ",", "model", ",", "options", "=", "{", "}", ")", "key", "=", "aviary_image_hash", "(", "model", ")", "image_url", "=", "options", ".", "delete", "(", ":image_url", ")", "||", "url_for", "(", ":action", "=>", "'aviary_image'", ",", ":id", "=>", "model", ",", ":only_path", "=>", "false", ",", ":key", "=>", "key", ")", "post_url", "=", "options", ".", "delete", "(", ":image_update_url", ")", "||", "url_for", "(", ":action", "=>", "'aviary_image_update'", ",", ":id", "=>", "model", ",", ":only_path", "=>", "false", ",", ":key", "=>", "key", ")", "api_key", "=", "Fleximage", "::", "AviaryController", ".", "api_key", "url", "=", "\"http://aviary.com/flash/aviary/index.aspx?tid=1&phoenix&apil=#{api_key}&loadurl=#{CGI.escape image_url}&posturl=#{CGI.escape post_url}\"", "link_to", "text", ",", "url", ",", "{", ":target", "=>", "'aviary'", "}", ".", "merge", "(", "options", ")", "end" ]
Creates a link that opens an image for editing in Aviary. Options: * image_url: url to the master image used by Aviary for editing. Defauls to <tt>url_for(:action => 'aviary_image', :id => model, :only_path => false)</tt> * post_url: url where Aviary will post the updated image. Defauls to <tt>url_for(:action => 'aviary_image_update', :id => model, :only_path => false)</tt> All other options are passed directly to the @link_to@ helper.
[ "Creates", "a", "link", "that", "opens", "an", "image", "for", "editing", "in", "Aviary", "." ]
dd6a486c29df3f56c0347dc9a70273f9aaf432fd
https://github.com/Squeegy/fleximage/blob/dd6a486c29df3f56c0347dc9a70273f9aaf432fd/lib/fleximage/helper.rb#L30-L38
train
rvm/rvm-gem
lib/rvm/environment/alias.rb
RVM.Environment.alias_list
def alias_list lines = normalize_array(rvm(:alias, :list).stdout) lines.inject({}) do |acc, current| alias_name, ruby_string = current.to_s.split(" => ") unless alias_name.empty? || ruby_string.empty? acc[alias_name] = ruby_string end acc end end
ruby
def alias_list lines = normalize_array(rvm(:alias, :list).stdout) lines.inject({}) do |acc, current| alias_name, ruby_string = current.to_s.split(" => ") unless alias_name.empty? || ruby_string.empty? acc[alias_name] = ruby_string end acc end end
[ "def", "alias_list", "lines", "=", "normalize_array", "(", "rvm", "(", ":alias", ",", ":list", ")", ".", "stdout", ")", "lines", ".", "inject", "(", "{", "}", ")", "do", "|", "acc", ",", "current", "|", "alias_name", ",", "ruby_string", "=", "current", ".", "to_s", ".", "split", "(", "\" => \"", ")", "unless", "alias_name", ".", "empty?", "||", "ruby_string", ".", "empty?", "acc", "[", "alias_name", "]", "=", "ruby_string", "end", "acc", "end", "end" ]
Returns a hash of aliases.
[ "Returns", "a", "hash", "of", "aliases", "." ]
7ef58904108a1abf1dbabafc605ece1fc9c53668
https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/alias.rb#L5-L14
train
alloy/lowdown
lib/lowdown/connection.rb
Lowdown.Connection.post
def post(path:, headers:, body:, delegate:, context: nil) request("POST", path, headers, body, delegate, context) end
ruby
def post(path:, headers:, body:, delegate:, context: nil) request("POST", path, headers, body, delegate, context) end
[ "def", "post", "(", "path", ":", ",", "headers", ":", ",", "body", ":", ",", "delegate", ":", ",", "context", ":", "nil", ")", "request", "(", "\"POST\"", ",", "path", ",", "headers", ",", "body", ",", "delegate", ",", "context", ")", "end" ]
Sends the provided data as a `POST` request to the service. @note It is strongly advised that the delegate object is a Celluloid actor and that you pass in an async proxy of that object, but that is not required. If you do not pass in an actor, then be advised that the callback will run on this connection’s private thread and thus you should not perform long blocking operations. @param [String] path the request path, which should be `/3/device/<device-token>`. @param [Hash] headers the additional headers for the request. By default it sends `:method`, `:path`, and `content-length`. @param [String] body the (JSON) encoded payload data to send to the service. @param [DelegateProtocol] delegate an object that implements the delegate protocol. @param [Object, nil] context any object that you want to be passed to the delegate once the response is back. @return [void]
[ "Sends", "the", "provided", "data", "as", "a", "POST", "request", "to", "the", "service", "." ]
7a75185d2b93015c18b6093f6784938d42c021f7
https://github.com/alloy/lowdown/blob/7a75185d2b93015c18b6093f6784938d42c021f7/lib/lowdown/connection.rb#L334-L336
train
rvm/rvm-gem
lib/rvm/environment/sets.rb
RVM.Environment.ruby
def ruby(runnable, options = {}) if runnable.respond_to?(:path) # Call the path ruby_run runnable.path, options elsif runnable.respond_to?(:to_str) runnable = runnable.to_str File.exist?(runnable) ? ruby_run(runnable, options) : ruby_eval(runnable, options) elsif runnable.respond_to?(:read) ruby_run runnable.read end end
ruby
def ruby(runnable, options = {}) if runnable.respond_to?(:path) # Call the path ruby_run runnable.path, options elsif runnable.respond_to?(:to_str) runnable = runnable.to_str File.exist?(runnable) ? ruby_run(runnable, options) : ruby_eval(runnable, options) elsif runnable.respond_to?(:read) ruby_run runnable.read end end
[ "def", "ruby", "(", "runnable", ",", "options", "=", "{", "}", ")", "if", "runnable", ".", "respond_to?", "(", ":path", ")", "ruby_run", "runnable", ".", "path", ",", "options", "elsif", "runnable", ".", "respond_to?", "(", ":to_str", ")", "runnable", "=", "runnable", ".", "to_str", "File", ".", "exist?", "(", "runnable", ")", "?", "ruby_run", "(", "runnable", ",", "options", ")", ":", "ruby_eval", "(", "runnable", ",", "options", ")", "elsif", "runnable", ".", "respond_to?", "(", ":read", ")", "ruby_run", "runnable", ".", "read", "end", "end" ]
Passed either something containing ruby code or a path to a ruby file, will attempt to exectute it in the current environment.
[ "Passed", "either", "something", "containing", "ruby", "code", "or", "a", "path", "to", "a", "ruby", "file", "will", "attempt", "to", "exectute", "it", "in", "the", "current", "environment", "." ]
7ef58904108a1abf1dbabafc605ece1fc9c53668
https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/sets.rb#L7-L17
train
rvm/rvm-gem
lib/rvm/environment/sets.rb
RVM.Environment.system
def system(command, *args) identifier = extract_identifier!(args) args = [identifier, :exec, command, *args].compact rvm(*args).successful? end
ruby
def system(command, *args) identifier = extract_identifier!(args) args = [identifier, :exec, command, *args].compact rvm(*args).successful? end
[ "def", "system", "(", "command", ",", "*", "args", ")", "identifier", "=", "extract_identifier!", "(", "args", ")", "args", "=", "[", "identifier", ",", ":exec", ",", "command", ",", "*", "args", "]", ".", "compact", "rvm", "(", "*", "args", ")", ".", "successful?", "end" ]
Like Kernel.system, but evaluates it within the environment. Also note that it doesn't support redirection etc.
[ "Like", "Kernel", ".", "system", "but", "evaluates", "it", "within", "the", "environment", ".", "Also", "note", "that", "it", "doesn", "t", "support", "redirection", "etc", "." ]
7ef58904108a1abf1dbabafc605ece1fc9c53668
https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/sets.rb#L54-L58
train
rvm/rvm-gem
lib/rvm/environment/sets.rb
RVM.Environment.extract_environment!
def extract_environment!(options) values = [] [:environment, :env, :rubies, :ruby].each do |k| values << options.delete(k) end values.compact.first end
ruby
def extract_environment!(options) values = [] [:environment, :env, :rubies, :ruby].each do |k| values << options.delete(k) end values.compact.first end
[ "def", "extract_environment!", "(", "options", ")", "values", "=", "[", "]", "[", ":environment", ",", ":env", ",", ":rubies", ",", ":ruby", "]", ".", "each", "do", "|", "k", "|", "values", "<<", "options", ".", "delete", "(", "k", ")", "end", "values", ".", "compact", ".", "first", "end" ]
From an options hash, extract the environment identifier.
[ "From", "an", "options", "hash", "extract", "the", "environment", "identifier", "." ]
7ef58904108a1abf1dbabafc605ece1fc9c53668
https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/sets.rb#L89-L95
train
rvm/rvm-gem
lib/rvm/environment/sets.rb
RVM.Environment.extract_identifier!
def extract_identifier!(args) options = extract_options!(args) identifier = normalize_set_identifier(extract_environment!(options)) args << options identifier end
ruby
def extract_identifier!(args) options = extract_options!(args) identifier = normalize_set_identifier(extract_environment!(options)) args << options identifier end
[ "def", "extract_identifier!", "(", "args", ")", "options", "=", "extract_options!", "(", "args", ")", "identifier", "=", "normalize_set_identifier", "(", "extract_environment!", "(", "options", ")", ")", "args", "<<", "options", "identifier", "end" ]
Shorthand to extra an identifier from args. Since we
[ "Shorthand", "to", "extra", "an", "identifier", "from", "args", ".", "Since", "we" ]
7ef58904108a1abf1dbabafc605ece1fc9c53668
https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/sets.rb#L99-L104
train
rvm/rvm-gem
lib/rvm/environment/utility.rb
RVM.Environment.chdir
def chdir(dir) run_silently :pushd, dir.to_s result = Dir.chdir(dir) { yield } run_silently :popd result end
ruby
def chdir(dir) run_silently :pushd, dir.to_s result = Dir.chdir(dir) { yield } run_silently :popd result end
[ "def", "chdir", "(", "dir", ")", "run_silently", ":pushd", ",", "dir", ".", "to_s", "result", "=", "Dir", ".", "chdir", "(", "dir", ")", "{", "yield", "}", "run_silently", ":popd", "result", "end" ]
Run commands inside the given directory.
[ "Run", "commands", "inside", "the", "given", "directory", "." ]
7ef58904108a1abf1dbabafc605ece1fc9c53668
https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/utility.rb#L81-L86
train
rvm/rvm-gem
lib/rvm/environment/utility.rb
RVM.Environment.normalize_array
def normalize_array(value) value.split("\n").map { |line| line.strip }.reject { |line| line.empty? } end
ruby
def normalize_array(value) value.split("\n").map { |line| line.strip }.reject { |line| line.empty? } end
[ "def", "normalize_array", "(", "value", ")", "value", ".", "split", "(", "\"\\n\"", ")", ".", "map", "{", "|", "line", "|", "line", ".", "strip", "}", ".", "reject", "{", "|", "line", "|", "line", ".", "empty?", "}", "end" ]
Normalizes an array, removing blank lines.
[ "Normalizes", "an", "array", "removing", "blank", "lines", "." ]
7ef58904108a1abf1dbabafc605ece1fc9c53668
https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/utility.rb#L133-L135
train
rvm/rvm-gem
lib/rvm/environment/utility.rb
RVM.Environment.hash_to_options
def hash_to_options(options) result = [] options.each_pair do |key, value| real_key = "--#{key.to_s.gsub("_", "-")}" if value == true result << real_key elsif value != false result << real_key result << value.to_s end end result end
ruby
def hash_to_options(options) result = [] options.each_pair do |key, value| real_key = "--#{key.to_s.gsub("_", "-")}" if value == true result << real_key elsif value != false result << real_key result << value.to_s end end result end
[ "def", "hash_to_options", "(", "options", ")", "result", "=", "[", "]", "options", ".", "each_pair", "do", "|", "key", ",", "value", "|", "real_key", "=", "\"--#{key.to_s.gsub(\"_\", \"-\")}\"", "if", "value", "==", "true", "result", "<<", "real_key", "elsif", "value", "!=", "false", "result", "<<", "real_key", "result", "<<", "value", ".", "to_s", "end", "end", "result", "end" ]
Converts a hash of options to an array of command line argumets. If the value is false, it wont be added but if it is true only the key will be added. Lastly, when the value is neither true or false, to_s will becalled on it and it shall be added to the array.
[ "Converts", "a", "hash", "of", "options", "to", "an", "array", "of", "command", "line", "argumets", ".", "If", "the", "value", "is", "false", "it", "wont", "be", "added", "but", "if", "it", "is", "true", "only", "the", "key", "will", "be", "added", ".", "Lastly", "when", "the", "value", "is", "neither", "true", "or", "false", "to_s", "will", "becalled", "on", "it", "and", "it", "shall", "be", "added", "to", "the", "array", "." ]
7ef58904108a1abf1dbabafc605ece1fc9c53668
https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/utility.rb#L146-L158
train
rvm/rvm-gem
lib/rvm/environment/utility.rb
RVM.Environment.normalize_option_value
def normalize_option_value(value) case value when Array value.map { |option| normalize_option_value(option) }.join(",") else value.to_s end end
ruby
def normalize_option_value(value) case value when Array value.map { |option| normalize_option_value(option) }.join(",") else value.to_s end end
[ "def", "normalize_option_value", "(", "value", ")", "case", "value", "when", "Array", "value", ".", "map", "{", "|", "option", "|", "normalize_option_value", "(", "option", ")", "}", ".", "join", "(", "\",\"", ")", "else", "value", ".", "to_s", "end", "end" ]
Recursively normalize options.
[ "Recursively", "normalize", "options", "." ]
7ef58904108a1abf1dbabafc605ece1fc9c53668
https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/utility.rb#L161-L168
train
rvm/rvm-gem
lib/rvm/environment/tools.rb
RVM.Environment.tools_path_identifier
def tools_path_identifier(path) path_identifier = rvm(:tools, "path-identifier", path.to_s) if path_identifier.exit_status == 2 error_message = "The rvmrc located in '#{path}' could not be loaded, likely due to trust mechanisms." error_message << " Please run 'rvm rvmrc {trust,untrust} \"#{path}\"' to continue, or set rvm_trust_rvmrcs_flag to 1." raise ErrorLoadingRVMRC, error_message end return normalize(path_identifier.stdout) end
ruby
def tools_path_identifier(path) path_identifier = rvm(:tools, "path-identifier", path.to_s) if path_identifier.exit_status == 2 error_message = "The rvmrc located in '#{path}' could not be loaded, likely due to trust mechanisms." error_message << " Please run 'rvm rvmrc {trust,untrust} \"#{path}\"' to continue, or set rvm_trust_rvmrcs_flag to 1." raise ErrorLoadingRVMRC, error_message end return normalize(path_identifier.stdout) end
[ "def", "tools_path_identifier", "(", "path", ")", "path_identifier", "=", "rvm", "(", ":tools", ",", "\"path-identifier\"", ",", "path", ".", "to_s", ")", "if", "path_identifier", ".", "exit_status", "==", "2", "error_message", "=", "\"The rvmrc located in '#{path}' could not be loaded, likely due to trust mechanisms.\"", "error_message", "<<", "\" Please run 'rvm rvmrc {trust,untrust} \\\"#{path}\\\"' to continue, or set rvm_trust_rvmrcs_flag to 1.\"", "raise", "ErrorLoadingRVMRC", ",", "error_message", "end", "return", "normalize", "(", "path_identifier", ".", "stdout", ")", "end" ]
Gets the identifier after cd'ing to a path, no destructive.
[ "Gets", "the", "identifier", "after", "cd", "ing", "to", "a", "path", "no", "destructive", "." ]
7ef58904108a1abf1dbabafc605ece1fc9c53668
https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/tools.rb#L10-L18
train
rvm/rvm-gem
lib/rvm/environment/rubies.rb
RVM.Environment.use
def use(ruby_string, opts = {}) ruby_string = ruby_string.to_s result = rvm(:use, ruby_string) successful = result.successful? if successful @environment_name = ruby_string @expanded_name = nil use_env_from_result! result if opts[:replace_env] end successful end
ruby
def use(ruby_string, opts = {}) ruby_string = ruby_string.to_s result = rvm(:use, ruby_string) successful = result.successful? if successful @environment_name = ruby_string @expanded_name = nil use_env_from_result! result if opts[:replace_env] end successful end
[ "def", "use", "(", "ruby_string", ",", "opts", "=", "{", "}", ")", "ruby_string", "=", "ruby_string", ".", "to_s", "result", "=", "rvm", "(", ":use", ",", "ruby_string", ")", "successful", "=", "result", ".", "successful?", "if", "successful", "@environment_name", "=", "ruby_string", "@expanded_name", "=", "nil", "use_env_from_result!", "result", "if", "opts", "[", ":replace_env", "]", "end", "successful", "end" ]
Changes the ruby string for the current environment. env.use '1.9.2' # => true env.use 'ree' # => true env.use 'foo' # => false
[ "Changes", "the", "ruby", "string", "for", "the", "current", "environment", "." ]
7ef58904108a1abf1dbabafc605ece1fc9c53668
https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment/rubies.rb#L25-L35
train
rvm/rvm-gem
lib/rvm/environment.rb
RVM.Environment.source_rvm_environment
def source_rvm_environment rvm_path = config_value_for(:rvm_path, self.class.default_rvm_path, false) actual_config = defined_config.merge('rvm_path' => rvm_path) config = [] actual_config.each_pair do |k, v| config << "#{k}=#{escape_argument(v.to_s)}" end run_silently "export #{config.join(" ")}" run_silently :source, File.join(rvm_path, "scripts", "rvm") end
ruby
def source_rvm_environment rvm_path = config_value_for(:rvm_path, self.class.default_rvm_path, false) actual_config = defined_config.merge('rvm_path' => rvm_path) config = [] actual_config.each_pair do |k, v| config << "#{k}=#{escape_argument(v.to_s)}" end run_silently "export #{config.join(" ")}" run_silently :source, File.join(rvm_path, "scripts", "rvm") end
[ "def", "source_rvm_environment", "rvm_path", "=", "config_value_for", "(", ":rvm_path", ",", "self", ".", "class", ".", "default_rvm_path", ",", "false", ")", "actual_config", "=", "defined_config", ".", "merge", "(", "'rvm_path'", "=>", "rvm_path", ")", "config", "=", "[", "]", "actual_config", ".", "each_pair", "do", "|", "k", ",", "v", "|", "config", "<<", "\"#{k}=#{escape_argument(v.to_s)}\"", "end", "run_silently", "\"export #{config.join(\" \")}\"", "run_silently", ":source", ",", "File", ".", "join", "(", "rvm_path", ",", "\"scripts\"", ",", "\"rvm\"", ")", "end" ]
Automatically load rvm config from the multiple sources.
[ "Automatically", "load", "rvm", "config", "from", "the", "multiple", "sources", "." ]
7ef58904108a1abf1dbabafc605ece1fc9c53668
https://github.com/rvm/rvm-gem/blob/7ef58904108a1abf1dbabafc605ece1fc9c53668/lib/rvm/environment.rb#L53-L62
train
alloy/lowdown
lib/lowdown/notification.rb
Lowdown.Notification.formatted_payload
def formatted_payload if @payload.key?("aps") @payload else payload = {} payload["aps"] = aps = {} @payload.each do |key, value| next if value.nil? key = key.to_s if APS_KEYS.include?(key) aps[key] = value else payload[key] = value end end payload end end
ruby
def formatted_payload if @payload.key?("aps") @payload else payload = {} payload["aps"] = aps = {} @payload.each do |key, value| next if value.nil? key = key.to_s if APS_KEYS.include?(key) aps[key] = value else payload[key] = value end end payload end end
[ "def", "formatted_payload", "if", "@payload", ".", "key?", "(", "\"aps\"", ")", "@payload", "else", "payload", "=", "{", "}", "payload", "[", "\"aps\"", "]", "=", "aps", "=", "{", "}", "@payload", ".", "each", "do", "|", "key", ",", "value", "|", "next", "if", "value", ".", "nil?", "key", "=", "key", ".", "to_s", "if", "APS_KEYS", ".", "include?", "(", "key", ")", "aps", "[", "key", "]", "=", "value", "else", "payload", "[", "key", "]", "=", "value", "end", "end", "payload", "end", "end" ]
Unless the payload contains an `aps` entry, the payload is assumed to be a mix of APN defined attributes and custom attributes and re-organized according to the specifications. @see https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH107-SW1 @return [Hash] the payload organized according to the APN specification.
[ "Unless", "the", "payload", "contains", "an", "aps", "entry", "the", "payload", "is", "assumed", "to", "be", "a", "mix", "of", "APN", "defined", "attributes", "and", "custom", "attributes", "and", "re", "-", "organized", "according", "to", "the", "specifications", "." ]
7a75185d2b93015c18b6093f6784938d42c021f7
https://github.com/alloy/lowdown/blob/7a75185d2b93015c18b6093f6784938d42c021f7/lib/lowdown/notification.rb#L94-L111
train
take-five/acts_as_ordered_tree
lib/acts_as_ordered_tree/persevering_transaction.rb
ActsAsOrderedTree.PerseveringTransaction.start
def start(&block) @attempts += 1 with_transaction_state(&block) rescue ActiveRecord::StatementInvalid => error raise unless connection.open_transactions.zero? raise unless error.message =~ DEADLOCK_MESSAGES raise if attempts >= RETRY_COUNT logger.info "Deadlock detected on attempt #{attempts}, restarting transaction" pause and retry end
ruby
def start(&block) @attempts += 1 with_transaction_state(&block) rescue ActiveRecord::StatementInvalid => error raise unless connection.open_transactions.zero? raise unless error.message =~ DEADLOCK_MESSAGES raise if attempts >= RETRY_COUNT logger.info "Deadlock detected on attempt #{attempts}, restarting transaction" pause and retry end
[ "def", "start", "(", "&", "block", ")", "@attempts", "+=", "1", "with_transaction_state", "(", "&", "block", ")", "rescue", "ActiveRecord", "::", "StatementInvalid", "=>", "error", "raise", "unless", "connection", ".", "open_transactions", ".", "zero?", "raise", "unless", "error", ".", "message", "=~", "DEADLOCK_MESSAGES", "raise", "if", "attempts", ">=", "RETRY_COUNT", "logger", ".", "info", "\"Deadlock detected on attempt #{attempts}, restarting transaction\"", "pause", "and", "retry", "end" ]
Starts persevering transaction
[ "Starts", "persevering", "transaction" ]
082b08d7e5560256d09987bfb015d684f93b56ed
https://github.com/take-five/acts_as_ordered_tree/blob/082b08d7e5560256d09987bfb015d684f93b56ed/lib/acts_as_ordered_tree/persevering_transaction.rb#L46-L58
train
jdtornow/challah
lib/challah/encrypter.rb
Challah.Encrypter.compare
def compare(crypted_string, plain_string) BCrypt::Password.new(crypted_string).is_password?(plain_string) rescue BCrypt::Errors::InvalidHash false end
ruby
def compare(crypted_string, plain_string) BCrypt::Password.new(crypted_string).is_password?(plain_string) rescue BCrypt::Errors::InvalidHash false end
[ "def", "compare", "(", "crypted_string", ",", "plain_string", ")", "BCrypt", "::", "Password", ".", "new", "(", "crypted_string", ")", ".", "is_password?", "(", "plain_string", ")", "rescue", "BCrypt", "::", "Errors", "::", "InvalidHash", "false", "end" ]
Returns true if the the bcrypted value of a is equal to b
[ "Returns", "true", "if", "the", "the", "bcrypted", "value", "of", "a", "is", "equal", "to", "b" ]
251328f3762bb33c85c873ac8b1268fc0ba32f52
https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/encrypter.rb#L36-L40
train
jdtornow/challah
lib/challah/audit.rb
Challah.Audit.clear_audit_attributes
def clear_audit_attributes all_audit_attributes.each do |attribute_name| if respond_to?(attribute_name) && respond_to?("#{ attribute_name }=") write_attribute(attribute_name, nil) end end @changed_attributes = changed_attributes.reduce(ActiveSupport::HashWithIndifferentAccess.new) do |result, (key, value)| unless all_audit_attributes.include?(key.to_sym) result[key] = value end result end end
ruby
def clear_audit_attributes all_audit_attributes.each do |attribute_name| if respond_to?(attribute_name) && respond_to?("#{ attribute_name }=") write_attribute(attribute_name, nil) end end @changed_attributes = changed_attributes.reduce(ActiveSupport::HashWithIndifferentAccess.new) do |result, (key, value)| unless all_audit_attributes.include?(key.to_sym) result[key] = value end result end end
[ "def", "clear_audit_attributes", "all_audit_attributes", ".", "each", "do", "|", "attribute_name", "|", "if", "respond_to?", "(", "attribute_name", ")", "&&", "respond_to?", "(", "\"#{ attribute_name }=\"", ")", "write_attribute", "(", "attribute_name", ",", "nil", ")", "end", "end", "@changed_attributes", "=", "changed_attributes", ".", "reduce", "(", "ActiveSupport", "::", "HashWithIndifferentAccess", ".", "new", ")", "do", "|", "result", ",", "(", "key", ",", "value", ")", "|", "unless", "all_audit_attributes", ".", "include?", "(", "key", ".", "to_sym", ")", "result", "[", "key", "]", "=", "value", "end", "result", "end", "end" ]
Clear attributes and changed_attributes
[ "Clear", "attributes", "and", "changed_attributes" ]
251328f3762bb33c85c873ac8b1268fc0ba32f52
https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/audit.rb#L94-L108
train
jonahb/bing-search
lib/bing-search/client.rb
BingSearch.Client.image
def image(query, opts = {}) invoke 'Image', query, opts, param_name_replacements: {filters: 'ImageFilters'}, params: {filters: image_filters_from_opts(opts)} end
ruby
def image(query, opts = {}) invoke 'Image', query, opts, param_name_replacements: {filters: 'ImageFilters'}, params: {filters: image_filters_from_opts(opts)} end
[ "def", "image", "(", "query", ",", "opts", "=", "{", "}", ")", "invoke", "'Image'", ",", "query", ",", "opts", ",", "param_name_replacements", ":", "{", "filters", ":", "'ImageFilters'", "}", ",", "params", ":", "{", "filters", ":", "image_filters_from_opts", "(", "opts", ")", "}", "end" ]
Searches for images @!macro general @option opts [Integer] :minimum_height In pixels; ANDed with other filters @option opts [Integer] :minimum_width In pixels; ANDed with other filters @option opts [Array<ImageFilter>] :filters Multiple filters are ANDed @return [Array<ImageResult>]
[ "Searches", "for", "images" ]
c0c1a6f51f42fbf41e1c5901a9158a4b9682898f
https://github.com/jonahb/bing-search/blob/c0c1a6f51f42fbf41e1c5901a9158a4b9682898f/lib/bing-search/client.rb#L169-L175
train
jonahb/bing-search
lib/bing-search/client.rb
BingSearch.Client.video
def video(query, opts = {}) invoke 'Video', query, opts, passthrough_opts: %i(filters sort), enum_opt_to_module: {filters: VideoFilter, sort: VideoSort}, param_name_replacements: {filters: 'VideoFilters', sort: 'VideoSortBy'} end
ruby
def video(query, opts = {}) invoke 'Video', query, opts, passthrough_opts: %i(filters sort), enum_opt_to_module: {filters: VideoFilter, sort: VideoSort}, param_name_replacements: {filters: 'VideoFilters', sort: 'VideoSortBy'} end
[ "def", "video", "(", "query", ",", "opts", "=", "{", "}", ")", "invoke", "'Video'", ",", "query", ",", "opts", ",", "passthrough_opts", ":", "%i(", "filters", "sort", ")", ",", "enum_opt_to_module", ":", "{", "filters", ":", "VideoFilter", ",", "sort", ":", "VideoSort", "}", ",", "param_name_replacements", ":", "{", "filters", ":", "'VideoFilters'", ",", "sort", ":", "'VideoSortBy'", "}", "end" ]
Searches for videos @!macro general @option opts [Array<VideoFilter>] :filters Multiple filters are ANDed. At most one duration is allowed. @option opts [VideoSort] :sort @return [Array<VideoResult>]
[ "Searches", "for", "videos" ]
c0c1a6f51f42fbf41e1c5901a9158a4b9682898f
https://github.com/jonahb/bing-search/blob/c0c1a6f51f42fbf41e1c5901a9158a4b9682898f/lib/bing-search/client.rb#L184-L191
train
jonahb/bing-search
lib/bing-search/client.rb
BingSearch.Client.news
def news(query, opts = {}) invoke 'News', query, opts, passthrough_opts: %i(category location_override sort), enum_opt_to_module: {category: NewsCategory, sort: NewsSort}, param_name_replacements: {category: 'NewsCategory', location_override: 'NewsLocationOverride', sort: 'NewsSortBy'} end
ruby
def news(query, opts = {}) invoke 'News', query, opts, passthrough_opts: %i(category location_override sort), enum_opt_to_module: {category: NewsCategory, sort: NewsSort}, param_name_replacements: {category: 'NewsCategory', location_override: 'NewsLocationOverride', sort: 'NewsSortBy'} end
[ "def", "news", "(", "query", ",", "opts", "=", "{", "}", ")", "invoke", "'News'", ",", "query", ",", "opts", ",", "passthrough_opts", ":", "%i(", "category", "location_override", "sort", ")", ",", "enum_opt_to_module", ":", "{", "category", ":", "NewsCategory", ",", "sort", ":", "NewsSort", "}", ",", "param_name_replacements", ":", "{", "category", ":", "'NewsCategory'", ",", "location_override", ":", "'NewsLocationOverride'", ",", "sort", ":", "'NewsSortBy'", "}", "end" ]
Searches for news @!macro general @option opts [Boolean] :highlighting (false) Whether to surround query terms in {NewsResult#description} with the delimiter {BingSearch::HIGHLIGHT_DELIMITER}. @option opts [NewsCategory] :category Only applies in the en-US market. If no news matches the category, Bing returns results from a mix of categories. @option opts [String] :location_override Overrides Bing's location detection. Example: +US.WA+ @option opts [NewsSort] :sort @return [Array<NewsResult>]
[ "Searches", "for", "news" ]
c0c1a6f51f42fbf41e1c5901a9158a4b9682898f
https://github.com/jonahb/bing-search/blob/c0c1a6f51f42fbf41e1c5901a9158a4b9682898f/lib/bing-search/client.rb#L206-L213
train
jdtornow/challah
lib/challah/validators/password_validator.rb
Challah.PasswordValidator.validate
def validate(record) if record.password_provider? or options[:force] if record.new_record? and record.password.to_s.blank? and !record.password_changed? record.errors.add :password, :blank elsif record.password_changed? if record.password.to_s.size < 4 record.errors.add :password, :invalid_password elsif record.password.to_s != record.password_confirmation.to_s record.errors.add :password, :no_match_password end end end end
ruby
def validate(record) if record.password_provider? or options[:force] if record.new_record? and record.password.to_s.blank? and !record.password_changed? record.errors.add :password, :blank elsif record.password_changed? if record.password.to_s.size < 4 record.errors.add :password, :invalid_password elsif record.password.to_s != record.password_confirmation.to_s record.errors.add :password, :no_match_password end end end end
[ "def", "validate", "(", "record", ")", "if", "record", ".", "password_provider?", "or", "options", "[", ":force", "]", "if", "record", ".", "new_record?", "and", "record", ".", "password", ".", "to_s", ".", "blank?", "and", "!", "record", ".", "password_changed?", "record", ".", "errors", ".", "add", ":password", ",", ":blank", "elsif", "record", ".", "password_changed?", "if", "record", ".", "password", ".", "to_s", ".", "size", "<", "4", "record", ".", "errors", ".", "add", ":password", ",", ":invalid_password", "elsif", "record", ".", "password", ".", "to_s", "!=", "record", ".", "password_confirmation", ".", "to_s", "record", ".", "errors", ".", "add", ":password", ",", ":no_match_password", "end", "end", "end", "end" ]
Check to make sure a valid password and confirmation were set
[ "Check", "to", "make", "sure", "a", "valid", "password", "and", "confirmation", "were", "set" ]
251328f3762bb33c85c873ac8b1268fc0ba32f52
https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/validators/password_validator.rb#L4-L16
train
moiristo/settler
lib/settler/abstract_setting.rb
Settler.AbstractSetting.valid_values
def valid_values if validators['inclusion'] return case when validators['inclusion'].is_a?(Array) then validators['inclusion'] when validators['inclusion'].is_a?(String) then validators['inclusion'].to_s.split(',').map{|v| v.to_s.strip } else nil end end nil end
ruby
def valid_values if validators['inclusion'] return case when validators['inclusion'].is_a?(Array) then validators['inclusion'] when validators['inclusion'].is_a?(String) then validators['inclusion'].to_s.split(',').map{|v| v.to_s.strip } else nil end end nil end
[ "def", "valid_values", "if", "validators", "[", "'inclusion'", "]", "return", "case", "when", "validators", "[", "'inclusion'", "]", ".", "is_a?", "(", "Array", ")", "then", "validators", "[", "'inclusion'", "]", "when", "validators", "[", "'inclusion'", "]", ".", "is_a?", "(", "String", ")", "then", "validators", "[", "'inclusion'", "]", ".", "to_s", ".", "split", "(", "','", ")", ".", "map", "{", "|", "v", "|", "v", ".", "to_s", ".", "strip", "}", "else", "nil", "end", "end", "nil", "end" ]
Returns all valid values for this setting, which is based on the presence of an inclusion validator. Will return nil if no valid values could be determined.
[ "Returns", "all", "valid", "values", "for", "this", "setting", "which", "is", "based", "on", "the", "presence", "of", "an", "inclusion", "validator", ".", "Will", "return", "nil", "if", "no", "valid", "values", "could", "be", "determined", "." ]
c56bf98b6c5c03b05119dbe53042b89e47d8bf21
https://github.com/moiristo/settler/blob/c56bf98b6c5c03b05119dbe53042b89e47d8bf21/lib/settler/abstract_setting.rb#L49-L58
train
sstephenson/hike
lib/hike/cached_trail.rb
Hike.CachedTrail.find_in_paths
def find_in_paths(logical_path, &block) dirname, basename = File.split(logical_path) @paths.each do |base_path| match(File.expand_path(dirname, base_path), basename, &block) end end
ruby
def find_in_paths(logical_path, &block) dirname, basename = File.split(logical_path) @paths.each do |base_path| match(File.expand_path(dirname, base_path), basename, &block) end end
[ "def", "find_in_paths", "(", "logical_path", ",", "&", "block", ")", "dirname", ",", "basename", "=", "File", ".", "split", "(", "logical_path", ")", "@paths", ".", "each", "do", "|", "base_path", "|", "match", "(", "File", ".", "expand_path", "(", "dirname", ",", "base_path", ")", ",", "basename", ",", "&", "block", ")", "end", "end" ]
Finds logical path across all `paths`
[ "Finds", "logical", "path", "across", "all", "paths" ]
3abf0b3feb47c26911f8cedf2cd409471fd26da1
https://github.com/sstephenson/hike/blob/3abf0b3feb47c26911f8cedf2cd409471fd26da1/lib/hike/cached_trail.rb#L105-L110
train
sstephenson/hike
lib/hike/cached_trail.rb
Hike.CachedTrail.match
def match(dirname, basename) # Potential `entries` syscall matches = @entries[dirname] pattern = @patterns[basename] matches = matches.select { |m| m =~ pattern } sort_matches(matches, basename).each do |path| filename = File.join(dirname, path) # Potential `stat` syscall stat = @stats[filename] # Exclude directories if stat && stat.file? yield filename end end end
ruby
def match(dirname, basename) # Potential `entries` syscall matches = @entries[dirname] pattern = @patterns[basename] matches = matches.select { |m| m =~ pattern } sort_matches(matches, basename).each do |path| filename = File.join(dirname, path) # Potential `stat` syscall stat = @stats[filename] # Exclude directories if stat && stat.file? yield filename end end end
[ "def", "match", "(", "dirname", ",", "basename", ")", "matches", "=", "@entries", "[", "dirname", "]", "pattern", "=", "@patterns", "[", "basename", "]", "matches", "=", "matches", ".", "select", "{", "|", "m", "|", "m", "=~", "pattern", "}", "sort_matches", "(", "matches", ",", "basename", ")", ".", "each", "do", "|", "path", "|", "filename", "=", "File", ".", "join", "(", "dirname", ",", "path", ")", "stat", "=", "@stats", "[", "filename", "]", "if", "stat", "&&", "stat", ".", "file?", "yield", "filename", "end", "end", "end" ]
Checks if the path is actually on the file system and performs any syscalls if necessary.
[ "Checks", "if", "the", "path", "is", "actually", "on", "the", "file", "system", "and", "performs", "any", "syscalls", "if", "necessary", "." ]
3abf0b3feb47c26911f8cedf2cd409471fd26da1
https://github.com/sstephenson/hike/blob/3abf0b3feb47c26911f8cedf2cd409471fd26da1/lib/hike/cached_trail.rb#L122-L140
train
sstephenson/hike
lib/hike/cached_trail.rb
Hike.CachedTrail.sort_matches
def sort_matches(matches, basename) extname = File.extname(basename) aliases = @reverse_aliases[extname] || [] matches.sort_by do |match| extnames = match.sub(basename, '').scan(/\.[^.]+/) extnames.inject(0) do |sum, ext| if i = extensions.index(ext) sum + i + 1 elsif i = aliases.index(ext) sum + i + 11 else sum end end end end
ruby
def sort_matches(matches, basename) extname = File.extname(basename) aliases = @reverse_aliases[extname] || [] matches.sort_by do |match| extnames = match.sub(basename, '').scan(/\.[^.]+/) extnames.inject(0) do |sum, ext| if i = extensions.index(ext) sum + i + 1 elsif i = aliases.index(ext) sum + i + 11 else sum end end end end
[ "def", "sort_matches", "(", "matches", ",", "basename", ")", "extname", "=", "File", ".", "extname", "(", "basename", ")", "aliases", "=", "@reverse_aliases", "[", "extname", "]", "||", "[", "]", "matches", ".", "sort_by", "do", "|", "match", "|", "extnames", "=", "match", ".", "sub", "(", "basename", ",", "''", ")", ".", "scan", "(", "/", "\\.", "/", ")", "extnames", ".", "inject", "(", "0", ")", "do", "|", "sum", ",", "ext", "|", "if", "i", "=", "extensions", ".", "index", "(", "ext", ")", "sum", "+", "i", "+", "1", "elsif", "i", "=", "aliases", ".", "index", "(", "ext", ")", "sum", "+", "i", "+", "11", "else", "sum", "end", "end", "end", "end" ]
Sorts candidate matches by their extension priority. Extensions in the front of the `extensions` carry more weight.
[ "Sorts", "candidate", "matches", "by", "their", "extension", "priority", ".", "Extensions", "in", "the", "front", "of", "the", "extensions", "carry", "more", "weight", "." ]
3abf0b3feb47c26911f8cedf2cd409471fd26da1
https://github.com/sstephenson/hike/blob/3abf0b3feb47c26911f8cedf2cd409471fd26da1/lib/hike/cached_trail.rb#L170-L186
train
jdtornow/challah
lib/challah/concerns/user/provideable.rb
Challah.UserProvideable.update_modified_providers_after_save
def update_modified_providers_after_save # Save password provider if @password_updated or @username_updated Challah.providers[:password].save(self) @password_updated = false @username_updated = false @password = nil end # Save any other providers Challah.custom_providers.each do |name, klass| custom_provider_attributes = provider_attributes[name] if custom_provider_attributes.respond_to?(:fetch) if klass.valid?(self) klass.save(self) end end end end
ruby
def update_modified_providers_after_save # Save password provider if @password_updated or @username_updated Challah.providers[:password].save(self) @password_updated = false @username_updated = false @password = nil end # Save any other providers Challah.custom_providers.each do |name, klass| custom_provider_attributes = provider_attributes[name] if custom_provider_attributes.respond_to?(:fetch) if klass.valid?(self) klass.save(self) end end end end
[ "def", "update_modified_providers_after_save", "if", "@password_updated", "or", "@username_updated", "Challah", ".", "providers", "[", ":password", "]", ".", "save", "(", "self", ")", "@password_updated", "=", "false", "@username_updated", "=", "false", "@password", "=", "nil", "end", "Challah", ".", "custom_providers", ".", "each", "do", "|", "name", ",", "klass", "|", "custom_provider_attributes", "=", "provider_attributes", "[", "name", "]", "if", "custom_provider_attributes", ".", "respond_to?", "(", ":fetch", ")", "if", "klass", ".", "valid?", "(", "self", ")", "klass", ".", "save", "(", "self", ")", "end", "end", "end", "end" ]
If password or username was changed, update the authorization record
[ "If", "password", "or", "username", "was", "changed", "update", "the", "authorization", "record" ]
251328f3762bb33c85c873ac8b1268fc0ba32f52
https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/concerns/user/provideable.rb#L84-L103
train
jdtornow/challah
lib/challah/session.rb
Challah.Session.method_missing
def method_missing(sym, *args, &block) if @params.has_key?(sym) return @params[sym] elsif sym.to_s =~ /^[a-z0-9_]*=$/ return @params[sym.to_s.sub(/^(.*?)=$/, '\1').to_sym] = args.shift elsif sym.to_s =~ /^[a-z0-9_]*\?$/ return !!@params[sym.to_s.sub(/^(.*?)\?$/, '\1').to_sym] end super(sym, *args, &block) end
ruby
def method_missing(sym, *args, &block) if @params.has_key?(sym) return @params[sym] elsif sym.to_s =~ /^[a-z0-9_]*=$/ return @params[sym.to_s.sub(/^(.*?)=$/, '\1').to_sym] = args.shift elsif sym.to_s =~ /^[a-z0-9_]*\?$/ return !!@params[sym.to_s.sub(/^(.*?)\?$/, '\1').to_sym] end super(sym, *args, &block) end
[ "def", "method_missing", "(", "sym", ",", "*", "args", ",", "&", "block", ")", "if", "@params", ".", "has_key?", "(", "sym", ")", "return", "@params", "[", "sym", "]", "elsif", "sym", ".", "to_s", "=~", "/", "/", "return", "@params", "[", "sym", ".", "to_s", ".", "sub", "(", "/", "/", ",", "'\\1'", ")", ".", "to_sym", "]", "=", "args", ".", "shift", "elsif", "sym", ".", "to_s", "=~", "/", "\\?", "/", "return", "!", "!", "@params", "[", "sym", ".", "to_s", ".", "sub", "(", "/", "\\?", "/", ",", "'\\1'", ")", ".", "to_sym", "]", "end", "super", "(", "sym", ",", "*", "args", ",", "&", "block", ")", "end" ]
Allow for dynamic setting of instance variables. also allows for variable? to see if it was provided
[ "Allow", "for", "dynamic", "setting", "of", "instance", "variables", ".", "also", "allows", "for", "variable?", "to", "see", "if", "it", "was", "provided" ]
251328f3762bb33c85c873ac8b1268fc0ba32f52
https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/session.rb#L99-L109
train
jdtornow/challah
lib/challah/session.rb
Challah.Session.authenticate!
def authenticate! Challah.techniques.values.each do |klass| technique = klass.new(self) technique.user_model = user_model if technique.respond_to?(:"user_model=") @user = technique.authenticate if @user @persist = technique.respond_to?(:persist?) ? technique.persist? : false break end end if @user # Only update user record if persistence is on for the technique. # Otherwise this builds up quick (one session for each API call) if @persist @user.successful_authentication!(ip) end return @valid = true end @valid = false end
ruby
def authenticate! Challah.techniques.values.each do |klass| technique = klass.new(self) technique.user_model = user_model if technique.respond_to?(:"user_model=") @user = technique.authenticate if @user @persist = technique.respond_to?(:persist?) ? technique.persist? : false break end end if @user # Only update user record if persistence is on for the technique. # Otherwise this builds up quick (one session for each API call) if @persist @user.successful_authentication!(ip) end return @valid = true end @valid = false end
[ "def", "authenticate!", "Challah", ".", "techniques", ".", "values", ".", "each", "do", "|", "klass", "|", "technique", "=", "klass", ".", "new", "(", "self", ")", "technique", ".", "user_model", "=", "user_model", "if", "technique", ".", "respond_to?", "(", ":\"", "\"", ")", "@user", "=", "technique", ".", "authenticate", "if", "@user", "@persist", "=", "technique", ".", "respond_to?", "(", ":persist?", ")", "?", "technique", ".", "persist?", ":", "false", "break", "end", "end", "if", "@user", "if", "@persist", "@user", ".", "successful_authentication!", "(", "ip", ")", "end", "return", "@valid", "=", "true", "end", "@valid", "=", "false", "end" ]
Try and authenticate against the various auth techniques. If one technique works, then just exit and make the session active.
[ "Try", "and", "authenticate", "against", "the", "various", "auth", "techniques", ".", "If", "one", "technique", "works", "then", "just", "exit", "and", "make", "the", "session", "active", "." ]
251328f3762bb33c85c873ac8b1268fc0ba32f52
https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/session.rb#L162-L186
train
jimeh/redistat
lib/redistat/buffer.rb
Redistat.Buffer.buffer_key
def buffer_key(key, opts) # covert keys to strings, as sorting a Hash with Symbol keys fails on # Ruby 1.8.x. opts = opts.inject({}) do |result, (k, v)| result[k.to_s] = v result end "#{key.to_s}:#{opts.sort.flatten.join(':')}" end
ruby
def buffer_key(key, opts) # covert keys to strings, as sorting a Hash with Symbol keys fails on # Ruby 1.8.x. opts = opts.inject({}) do |result, (k, v)| result[k.to_s] = v result end "#{key.to_s}:#{opts.sort.flatten.join(':')}" end
[ "def", "buffer_key", "(", "key", ",", "opts", ")", "opts", "=", "opts", ".", "inject", "(", "{", "}", ")", "do", "|", "result", ",", "(", "k", ",", "v", ")", "|", "result", "[", "k", ".", "to_s", "]", "=", "v", "result", "end", "\"#{key.to_s}:#{opts.sort.flatten.join(':')}\"", "end" ]
depth_limit is not needed as it's evident in key.to_s
[ "depth_limit", "is", "not", "needed", "as", "it", "s", "evident", "in", "key", ".", "to_s" ]
4c6a6732bfb4d48266b54cc5f4e695be5ebc0122
https://github.com/jimeh/redistat/blob/4c6a6732bfb4d48266b54cc5f4e695be5ebc0122/lib/redistat/buffer.rb#L99-L107
train
jdtornow/challah
lib/challah/plugins.rb
Challah.Plugins.register_plugin
def register_plugin(name, &block) plugin = Plugin.new plugin.instance_eval(&block) @plugins[name] = plugin end
ruby
def register_plugin(name, &block) plugin = Plugin.new plugin.instance_eval(&block) @plugins[name] = plugin end
[ "def", "register_plugin", "(", "name", ",", "&", "block", ")", "plugin", "=", "Plugin", ".", "new", "plugin", ".", "instance_eval", "(", "&", "block", ")", "@plugins", "[", "name", "]", "=", "plugin", "end" ]
Register a new plugin.
[ "Register", "a", "new", "plugin", "." ]
251328f3762bb33c85c873ac8b1268fc0ba32f52
https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/plugins.rb#L30-L34
train
NullVoxPopuli/drawers
lib/drawers/active_support/dependency_extensions.rb
Drawers.DependencyExtensions.resource_path_from_qualified_name
def resource_path_from_qualified_name(qualified_name) path_options = path_options_for_qualified_name(qualified_name) file_path = '' path_options.uniq.each do |path_option| file_path = search_for_file(path_option) break if file_path.present? end return file_path if file_path # Note that sometimes, the resource_type path may only be defined in a # resource type folder # So, look for the first file within the resource type folder # because of ruby namespacing conventions if there is a file in the folder, # it MUST define the namespace path_for_first_file_in(path_options.last) || path_for_first_file_in(path_options[-2]) end
ruby
def resource_path_from_qualified_name(qualified_name) path_options = path_options_for_qualified_name(qualified_name) file_path = '' path_options.uniq.each do |path_option| file_path = search_for_file(path_option) break if file_path.present? end return file_path if file_path # Note that sometimes, the resource_type path may only be defined in a # resource type folder # So, look for the first file within the resource type folder # because of ruby namespacing conventions if there is a file in the folder, # it MUST define the namespace path_for_first_file_in(path_options.last) || path_for_first_file_in(path_options[-2]) end
[ "def", "resource_path_from_qualified_name", "(", "qualified_name", ")", "path_options", "=", "path_options_for_qualified_name", "(", "qualified_name", ")", "file_path", "=", "''", "path_options", ".", "uniq", ".", "each", "do", "|", "path_option", "|", "file_path", "=", "search_for_file", "(", "path_option", ")", "break", "if", "file_path", ".", "present?", "end", "return", "file_path", "if", "file_path", "path_for_first_file_in", "(", "path_options", ".", "last", ")", "||", "path_for_first_file_in", "(", "path_options", "[", "-", "2", "]", ")", "end" ]
A look for the possible places that various qualified names could be @note The Lookup Rules: - all resources are plural - file_names can either be named after the type or traditional ruby/rails nameing i.e.: posts_controller.rb vs controller.rb - regular namespacing still applies. i.e: Api::V2::CategoriesController should be in api/v2/categories/controller.rb @note The Pattern: - namespace_a - api - namespace_b - v2 - resource_name (plural) - posts - file_type.rb - controller.rb (or posts_controller.rb) - operations.rb (or post_operations.rb) - folder_type - operations/ (or post_operations/) - related namespaced classes - create.rb All examples assume default resource directory ("resources") and show the order of lookup @example Api::PostsController Possible Locations - api/posts/controller.rb - api/posts/posts_controller.rb @example Api::PostSerializer Possible Locations - api/posts/serializer.rb - api/posts/post_serializer.rb @example Api::PostOperations::Create Possible Locations - api/posts/operations/create.rb - api/posts/post_operations/create.rb @example Api::V2::CategoriesController Possible Locations - api/v2/categories/controller.rb - api/v2/categories/categories_controller.rb @param [String] qualified_name fully qualified class/module name to find the file location for
[ "A", "look", "for", "the", "possible", "places", "that", "various", "qualified", "names", "could", "be" ]
75936a180b6b9c670144338584b1296af264f377
https://github.com/NullVoxPopuli/drawers/blob/75936a180b6b9c670144338584b1296af264f377/lib/drawers/active_support/dependency_extensions.rb#L63-L81
train
jdtornow/challah
lib/challah/simple_cookie_store.rb
Challah.SimpleCookieStore.existing?
def existing? exists = false if session_cookie and validation_cookie session_tmp = session_cookie.to_s validation_tmp = validation_cookie.to_s if validation_tmp == validation_cookie_value(session_tmp) exists = true end end exists end
ruby
def existing? exists = false if session_cookie and validation_cookie session_tmp = session_cookie.to_s validation_tmp = validation_cookie.to_s if validation_tmp == validation_cookie_value(session_tmp) exists = true end end exists end
[ "def", "existing?", "exists", "=", "false", "if", "session_cookie", "and", "validation_cookie", "session_tmp", "=", "session_cookie", ".", "to_s", "validation_tmp", "=", "validation_cookie", ".", "to_s", "if", "validation_tmp", "==", "validation_cookie_value", "(", "session_tmp", ")", "exists", "=", "true", "end", "end", "exists", "end" ]
Do the cookies exist, and are they valid?
[ "Do", "the", "cookies", "exist", "and", "are", "they", "valid?" ]
251328f3762bb33c85c873ac8b1268fc0ba32f52
https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/simple_cookie_store.rb#L54-L67
train
jdtornow/challah
lib/challah/techniques/password_technique.rb
Challah.PasswordTechnique.authenticate
def authenticate if username? and password? user = user_model.find_for_session(username) if user if user.valid_session? if user.authenticate(@password) return user end end user.failed_authentication! user = nil end end nil end
ruby
def authenticate if username? and password? user = user_model.find_for_session(username) if user if user.valid_session? if user.authenticate(@password) return user end end user.failed_authentication! user = nil end end nil end
[ "def", "authenticate", "if", "username?", "and", "password?", "user", "=", "user_model", ".", "find_for_session", "(", "username", ")", "if", "user", "if", "user", ".", "valid_session?", "if", "user", ".", "authenticate", "(", "@password", ")", "return", "user", "end", "end", "user", ".", "failed_authentication!", "user", "=", "nil", "end", "end", "nil", "end" ]
grab the params we want from this request if we can successfully authenticate, return a User instance, otherwise nil
[ "grab", "the", "params", "we", "want", "from", "this", "request", "if", "we", "can", "successfully", "authenticate", "return", "a", "User", "instance", "otherwise", "nil" ]
251328f3762bb33c85c873ac8b1268fc0ba32f52
https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/techniques/password_technique.rb#L14-L31
train
sstephenson/hike
lib/hike/fileutils.rb
Hike.FileUtils.entries
def entries(path) if File.directory?(path) Dir.entries(path).reject { |entry| entry =~ /^\.|~$|^\#.*\#$/ }.sort else [] end end
ruby
def entries(path) if File.directory?(path) Dir.entries(path).reject { |entry| entry =~ /^\.|~$|^\#.*\#$/ }.sort else [] end end
[ "def", "entries", "(", "path", ")", "if", "File", ".", "directory?", "(", "path", ")", "Dir", ".", "entries", "(", "path", ")", ".", "reject", "{", "|", "entry", "|", "entry", "=~", "/", "\\.", "\\#", "\\#", "/", "}", ".", "sort", "else", "[", "]", "end", "end" ]
A version of `Dir.entries` that filters out `.` files and `~` swap files. Returns an empty `Array` if the directory does not exist.
[ "A", "version", "of", "Dir", ".", "entries", "that", "filters", "out", ".", "files", "and", "~", "swap", "files", ".", "Returns", "an", "empty", "Array", "if", "the", "directory", "does", "not", "exist", "." ]
3abf0b3feb47c26911f8cedf2cd409471fd26da1
https://github.com/sstephenson/hike/blob/3abf0b3feb47c26911f8cedf2cd409471fd26da1/lib/hike/fileutils.rb#L16-L22
train
jdtornow/challah
lib/challah/validators/email_validator.rb
Challah.EmailValidator.validate_each
def validate_each(record, attribute, value) unless value =~ EmailValidator.pattern record.errors.add(attribute, options[:message] || :invalid_email) end end
ruby
def validate_each(record, attribute, value) unless value =~ EmailValidator.pattern record.errors.add(attribute, options[:message] || :invalid_email) end end
[ "def", "validate_each", "(", "record", ",", "attribute", ",", "value", ")", "unless", "value", "=~", "EmailValidator", ".", "pattern", "record", ".", "errors", ".", "add", "(", "attribute", ",", "options", "[", ":message", "]", "||", ":invalid_email", ")", "end", "end" ]
Called automatically by ActiveModel validation..
[ "Called", "automatically", "by", "ActiveModel", "validation", ".." ]
251328f3762bb33c85c873ac8b1268fc0ba32f52
https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/validators/email_validator.rb#L10-L14
train
jdtornow/challah
lib/challah/concerns/user/authenticateable.rb
Challah.UserAuthenticateable.authenticate
def authenticate(*args) return false unless active? if args.length > 1 method = args.shift if Challah.authenticators[method] return Challah.authenticators[method].match?(self, providers[method], *args) end false else self.authenticate(:password, args[0]) end end
ruby
def authenticate(*args) return false unless active? if args.length > 1 method = args.shift if Challah.authenticators[method] return Challah.authenticators[method].match?(self, providers[method], *args) end false else self.authenticate(:password, args[0]) end end
[ "def", "authenticate", "(", "*", "args", ")", "return", "false", "unless", "active?", "if", "args", ".", "length", ">", "1", "method", "=", "args", ".", "shift", "if", "Challah", ".", "authenticators", "[", "method", "]", "return", "Challah", ".", "authenticators", "[", "method", "]", ".", "match?", "(", "self", ",", "providers", "[", "method", "]", ",", "*", "args", ")", "end", "false", "else", "self", ".", "authenticate", "(", ":password", ",", "args", "[", "0", "]", ")", "end", "end" ]
Generic authentication method. By default, this just checks to see if the password given matches this user. You can also pass in the first parameter as the method to use for a different type of authentication.
[ "Generic", "authentication", "method", ".", "By", "default", "this", "just", "checks", "to", "see", "if", "the", "password", "given", "matches", "this", "user", ".", "You", "can", "also", "pass", "in", "the", "first", "parameter", "as", "the", "method", "to", "use", "for", "a", "different", "type", "of", "authentication", "." ]
251328f3762bb33c85c873ac8b1268fc0ba32f52
https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/concerns/user/authenticateable.rb#L6-L20
train
jdtornow/challah
lib/challah/concerns/user/authenticateable.rb
Challah.UserAuthenticateable.successful_authentication!
def successful_authentication!(ip_address = nil) self.last_session_at = Time.now self.last_session_ip = ip_address if respond_to?(:last_session_ip=) self.save self.increment!(:session_count, 1) end
ruby
def successful_authentication!(ip_address = nil) self.last_session_at = Time.now self.last_session_ip = ip_address if respond_to?(:last_session_ip=) self.save self.increment!(:session_count, 1) end
[ "def", "successful_authentication!", "(", "ip_address", "=", "nil", ")", "self", ".", "last_session_at", "=", "Time", ".", "now", "self", ".", "last_session_ip", "=", "ip_address", "if", "respond_to?", "(", ":last_session_ip=", ")", "self", ".", "save", "self", ".", "increment!", "(", ":session_count", ",", "1", ")", "end" ]
Called when a +Session+ validation is successful, and this user has been authenticated.
[ "Called", "when", "a", "+", "Session", "+", "validation", "is", "successful", "and", "this", "user", "has", "been", "authenticated", "." ]
251328f3762bb33c85c873ac8b1268fc0ba32f52
https://github.com/jdtornow/challah/blob/251328f3762bb33c85c873ac8b1268fc0ba32f52/lib/challah/concerns/user/authenticateable.rb#L36-L41
train
dicom/rtp-connect
lib/rtp-connect/control_point.rb
RTP.ControlPoint.dcm_mlc_positions
def dcm_mlc_positions(scale=nil) coeff = (scale == :elekta ? -1 : 1) # As with the collimators, the first side (1/a) may need scale invertion: pos_a = @mlc_lp_a.collect{|p| (p.to_f * 10 * coeff).round(1) unless p.empty?}.compact pos_b = @mlc_lp_b.collect{|p| (p.to_f * 10).round(1) unless p.empty?}.compact (pos_a + pos_b).join("\\") end
ruby
def dcm_mlc_positions(scale=nil) coeff = (scale == :elekta ? -1 : 1) # As with the collimators, the first side (1/a) may need scale invertion: pos_a = @mlc_lp_a.collect{|p| (p.to_f * 10 * coeff).round(1) unless p.empty?}.compact pos_b = @mlc_lp_b.collect{|p| (p.to_f * 10).round(1) unless p.empty?}.compact (pos_a + pos_b).join("\\") end
[ "def", "dcm_mlc_positions", "(", "scale", "=", "nil", ")", "coeff", "=", "(", "scale", "==", ":elekta", "?", "-", "1", ":", "1", ")", "pos_a", "=", "@mlc_lp_a", ".", "collect", "{", "|", "p", "|", "(", "p", ".", "to_f", "*", "10", "*", "coeff", ")", ".", "round", "(", "1", ")", "unless", "p", ".", "empty?", "}", ".", "compact", "pos_b", "=", "@mlc_lp_b", ".", "collect", "{", "|", "p", "|", "(", "p", ".", "to_f", "*", "10", ")", ".", "round", "(", "1", ")", "unless", "p", ".", "empty?", "}", ".", "compact", "(", "pos_a", "+", "pos_b", ")", ".", "join", "(", "\"\\\\\"", ")", "end" ]
Converts the mlc_lp_a & mlc_lp_b attributes to a proper DICOM formatted string. @param [Symbol] scale if set, relevant device parameters are converted from native readout format to IEC1217 (supported values are :elekta & :varian) @return [String] the DICOM-formatted leaf pair positions
[ "Converts", "the", "mlc_lp_a", "&", "mlc_lp_b", "attributes", "to", "a", "proper", "DICOM", "formatted", "string", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/control_point.rb#L193-L199
train
dicom/rtp-connect
lib/rtp-connect/control_point.rb
RTP.ControlPoint.dcm_collimator_1
def dcm_collimator_1(scale=nil, axis) coeff = 1 if scale == :elekta axis = (axis == :x ? :y : :x) coeff = -1 elsif scale == :varian coeff = -1 end dcm_collimator(axis, coeff, side=1) end
ruby
def dcm_collimator_1(scale=nil, axis) coeff = 1 if scale == :elekta axis = (axis == :x ? :y : :x) coeff = -1 elsif scale == :varian coeff = -1 end dcm_collimator(axis, coeff, side=1) end
[ "def", "dcm_collimator_1", "(", "scale", "=", "nil", ",", "axis", ")", "coeff", "=", "1", "if", "scale", "==", ":elekta", "axis", "=", "(", "axis", "==", ":x", "?", ":y", ":", ":x", ")", "coeff", "=", "-", "1", "elsif", "scale", "==", ":varian", "coeff", "=", "-", "1", "end", "dcm_collimator", "(", "axis", ",", "coeff", ",", "side", "=", "1", ")", "end" ]
Converts the collimator1 attribute to proper DICOM format. @param [Symbol] scale if set, relevant device parameters are converted from a native readout format to IEC1217 (supported values are :elekta & :varian) @return [Float] the DICOM-formatted collimator_x1 attribute
[ "Converts", "the", "collimator1", "attribute", "to", "proper", "DICOM", "format", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/control_point.rb#L600-L609
train
SCPR/secretary-rails
lib/secretary/versioned_attributes.rb
Secretary.VersionedAttributes.versioned_changes
def versioned_changes modified_changes = {} raw_changes = self.changes.select {|k,_| versioned_attribute?(k)}.to_hash raw_changes.each do |key, (previous, current)| if reflection = self.class.reflect_on_association(key.to_sym) if reflection.collection? previous = previous.map(&:versioned_attributes) current = current.map(&:versioned_attributes) else previous = previous ? previous.versioned_attributes : {} current = if current && !current.marked_for_destruction? current.versioned_attributes else {} end end end # This really shouldn't need to be here, # but there is some confusion if we're destroying # an associated object in a save callback on the # parent object. We can't know that the callback # is going to destroy this object on save, # so we just have to add the association normally # and then filter it out here. if previous != current modified_changes[key] = [previous, current] end end modified_changes end
ruby
def versioned_changes modified_changes = {} raw_changes = self.changes.select {|k,_| versioned_attribute?(k)}.to_hash raw_changes.each do |key, (previous, current)| if reflection = self.class.reflect_on_association(key.to_sym) if reflection.collection? previous = previous.map(&:versioned_attributes) current = current.map(&:versioned_attributes) else previous = previous ? previous.versioned_attributes : {} current = if current && !current.marked_for_destruction? current.versioned_attributes else {} end end end # This really shouldn't need to be here, # but there is some confusion if we're destroying # an associated object in a save callback on the # parent object. We can't know that the callback # is going to destroy this object on save, # so we just have to add the association normally # and then filter it out here. if previous != current modified_changes[key] = [previous, current] end end modified_changes end
[ "def", "versioned_changes", "modified_changes", "=", "{", "}", "raw_changes", "=", "self", ".", "changes", ".", "select", "{", "|", "k", ",", "_", "|", "versioned_attribute?", "(", "k", ")", "}", ".", "to_hash", "raw_changes", ".", "each", "do", "|", "key", ",", "(", "previous", ",", "current", ")", "|", "if", "reflection", "=", "self", ".", "class", ".", "reflect_on_association", "(", "key", ".", "to_sym", ")", "if", "reflection", ".", "collection?", "previous", "=", "previous", ".", "map", "(", "&", ":versioned_attributes", ")", "current", "=", "current", ".", "map", "(", "&", ":versioned_attributes", ")", "else", "previous", "=", "previous", "?", "previous", ".", "versioned_attributes", ":", "{", "}", "current", "=", "if", "current", "&&", "!", "current", ".", "marked_for_destruction?", "current", ".", "versioned_attributes", "else", "{", "}", "end", "end", "end", "if", "previous", "!=", "current", "modified_changes", "[", "key", "]", "=", "[", "previous", ",", "current", "]", "end", "end", "modified_changes", "end" ]
The hash that gets serialized into the `object_changes` column. This takes the `changes` hash and processes the associations to be human-readable objects.
[ "The", "hash", "that", "gets", "serialized", "into", "the", "object_changes", "column", "." ]
f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945
https://github.com/SCPR/secretary-rails/blob/f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945/lib/secretary/versioned_attributes.rb#L78-L111
train
SCPR/secretary-rails
lib/secretary/versioned_attributes.rb
Secretary.VersionedAttributes.versioned_attributes
def versioned_attributes json = self.as_json(:root => false).select do |k,_| versioned_attribute?(k) end json.to_hash end
ruby
def versioned_attributes json = self.as_json(:root => false).select do |k,_| versioned_attribute?(k) end json.to_hash end
[ "def", "versioned_attributes", "json", "=", "self", ".", "as_json", "(", ":root", "=>", "false", ")", ".", "select", "do", "|", "k", ",", "_", "|", "versioned_attribute?", "(", "k", ")", "end", "json", ".", "to_hash", "end" ]
The object's versioned attributes as a hash.
[ "The", "object", "s", "versioned", "attributes", "as", "a", "hash", "." ]
f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945
https://github.com/SCPR/secretary-rails/blob/f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945/lib/secretary/versioned_attributes.rb#L114-L120
train
norman/disqus
lib/disqus/forum.rb
Disqus.Forum.get_thread_by_url
def get_thread_by_url(url) response = Disqus::Api::get_thread_by_url(:url => url, :forum_api_key => key) if response["succeeded"] t = response["message"] Thread.new(t["id"], self, t["slug"], t["title"], t["created_at"], t["allow_comments"], t["url"], t["identifier"]) else raise_api_error(response) end end
ruby
def get_thread_by_url(url) response = Disqus::Api::get_thread_by_url(:url => url, :forum_api_key => key) if response["succeeded"] t = response["message"] Thread.new(t["id"], self, t["slug"], t["title"], t["created_at"], t["allow_comments"], t["url"], t["identifier"]) else raise_api_error(response) end end
[ "def", "get_thread_by_url", "(", "url", ")", "response", "=", "Disqus", "::", "Api", "::", "get_thread_by_url", "(", ":url", "=>", "url", ",", ":forum_api_key", "=>", "key", ")", "if", "response", "[", "\"succeeded\"", "]", "t", "=", "response", "[", "\"message\"", "]", "Thread", ".", "new", "(", "t", "[", "\"id\"", "]", ",", "self", ",", "t", "[", "\"slug\"", "]", ",", "t", "[", "\"title\"", "]", ",", "t", "[", "\"created_at\"", "]", ",", "t", "[", "\"allow_comments\"", "]", ",", "t", "[", "\"url\"", "]", ",", "t", "[", "\"identifier\"", "]", ")", "else", "raise_api_error", "(", "response", ")", "end", "end" ]
Returns a thread associated with the given URL. A thread will only have an associated URL if it was automatically created by Disqus javascript embedded on that page.
[ "Returns", "a", "thread", "associated", "with", "the", "given", "URL", "." ]
6a5fa19d2be2ff67909e988356533a4d7ac2b51b
https://github.com/norman/disqus/blob/6a5fa19d2be2ff67909e988356533a4d7ac2b51b/lib/disqus/forum.rb#L55-L63
train
SCPR/secretary-rails
app/models/secretary/version.rb
Secretary.Version.attribute_diffs
def attribute_diffs @attribute_diffs ||= begin changes = self.object_changes.dup attribute_diffs = {} # Compare each of object_b's attributes to object_a's attributes # And if there is a difference, add it to the Diff changes.each do |attribute, values| # values is [previous_value, new_value] diff = Diffy::Diff.new(values[0].to_s, values[1].to_s) attribute_diffs[attribute] = diff end attribute_diffs end end
ruby
def attribute_diffs @attribute_diffs ||= begin changes = self.object_changes.dup attribute_diffs = {} # Compare each of object_b's attributes to object_a's attributes # And if there is a difference, add it to the Diff changes.each do |attribute, values| # values is [previous_value, new_value] diff = Diffy::Diff.new(values[0].to_s, values[1].to_s) attribute_diffs[attribute] = diff end attribute_diffs end end
[ "def", "attribute_diffs", "@attribute_diffs", "||=", "begin", "changes", "=", "self", ".", "object_changes", ".", "dup", "attribute_diffs", "=", "{", "}", "changes", ".", "each", "do", "|", "attribute", ",", "values", "|", "diff", "=", "Diffy", "::", "Diff", ".", "new", "(", "values", "[", "0", "]", ".", "to_s", ",", "values", "[", "1", "]", ".", "to_s", ")", "attribute_diffs", "[", "attribute", "]", "=", "diff", "end", "attribute_diffs", "end", "end" ]
The attribute diffs for this version
[ "The", "attribute", "diffs", "for", "this", "version" ]
f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945
https://github.com/SCPR/secretary-rails/blob/f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945/app/models/secretary/version.rb#L61-L76
train
SCPR/secretary-rails
lib/secretary/dirty_associations.rb
Secretary.DirtyAssociations.__compat_set_attribute_was
def __compat_set_attribute_was(name, previous) if respond_to?(:set_attribute_was, true) # Rails 4.2+ set_attribute_was(name, previous) else # Rails < 4.2 changed_attributes[name] = previous end end
ruby
def __compat_set_attribute_was(name, previous) if respond_to?(:set_attribute_was, true) # Rails 4.2+ set_attribute_was(name, previous) else # Rails < 4.2 changed_attributes[name] = previous end end
[ "def", "__compat_set_attribute_was", "(", "name", ",", "previous", ")", "if", "respond_to?", "(", ":set_attribute_was", ",", "true", ")", "set_attribute_was", "(", "name", ",", "previous", ")", "else", "changed_attributes", "[", "name", "]", "=", "previous", "end", "end" ]
Rails 4.2 adds "set_attribute_was" which must be used, so we'll check for it.
[ "Rails", "4", ".", "2", "adds", "set_attribute_was", "which", "must", "be", "used", "so", "we", "ll", "check", "for", "it", "." ]
f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945
https://github.com/SCPR/secretary-rails/blob/f831a2e9b7fa4fe7b1d50f6f060ddc77ee857945/lib/secretary/dirty_associations.rb#L125-L133
train
dicom/rtp-connect
lib/rtp-connect/record.rb
RTP.Record.encode
def encode(options={}) encoded_values = values.collect {|v| v && v.encode('ISO8859-1')} encoded_values = discard_unsupported_attributes(encoded_values, options) if options[:version] content = CSV.generate_line(encoded_values, force_quotes: true, row_sep: '') + "," checksum = content.checksum # Complete string is content + checksum (in double quotes) + carriage return + line feed return (content + checksum.to_s.wrap + "\r\n").encode('ISO8859-1') end
ruby
def encode(options={}) encoded_values = values.collect {|v| v && v.encode('ISO8859-1')} encoded_values = discard_unsupported_attributes(encoded_values, options) if options[:version] content = CSV.generate_line(encoded_values, force_quotes: true, row_sep: '') + "," checksum = content.checksum # Complete string is content + checksum (in double quotes) + carriage return + line feed return (content + checksum.to_s.wrap + "\r\n").encode('ISO8859-1') end
[ "def", "encode", "(", "options", "=", "{", "}", ")", "encoded_values", "=", "values", ".", "collect", "{", "|", "v", "|", "v", "&&", "v", ".", "encode", "(", "'ISO8859-1'", ")", "}", "encoded_values", "=", "discard_unsupported_attributes", "(", "encoded_values", ",", "options", ")", "if", "options", "[", ":version", "]", "content", "=", "CSV", ".", "generate_line", "(", "encoded_values", ",", "force_quotes", ":", "true", ",", "row_sep", ":", "''", ")", "+", "\",\"", "checksum", "=", "content", ".", "checksum", "return", "(", "content", "+", "checksum", ".", "to_s", ".", "wrap", "+", "\"\\r\\n\"", ")", ".", "encode", "(", "'ISO8859-1'", ")", "end" ]
Encodes a string from the contents of this instance. This produces the full record string line, including a computed CRC checksum. @param [Hash] options an optional hash parameter @option options [Float] :version the Mosaiq compatibility version number (e.g. 2.4) used for the output @return [String] a proper RTPConnect type CSV string
[ "Encodes", "a", "string", "from", "the", "contents", "of", "this", "instance", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L47-L54
train
dicom/rtp-connect
lib/rtp-connect/record.rb
RTP.Record.get_parent
def get_parent(last_parent, klass) if last_parent.is_a?(klass) return last_parent else return last_parent.get_parent(last_parent.parent, klass) end end
ruby
def get_parent(last_parent, klass) if last_parent.is_a?(klass) return last_parent else return last_parent.get_parent(last_parent.parent, klass) end end
[ "def", "get_parent", "(", "last_parent", ",", "klass", ")", "if", "last_parent", ".", "is_a?", "(", "klass", ")", "return", "last_parent", "else", "return", "last_parent", ".", "get_parent", "(", "last_parent", ".", "parent", ",", "klass", ")", "end", "end" ]
Follows the tree of parents until the appropriate parent of the requesting record is found. @param [Record] last_parent the previous parent (the record from the previous line in the RTP file) @param [Record] klass the expected parent record class of this record (e.g. Plan, Field)
[ "Follows", "the", "tree", "of", "parents", "until", "the", "appropriate", "parent", "of", "the", "requesting", "record", "is", "found", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L61-L67
train
dicom/rtp-connect
lib/rtp-connect/record.rb
RTP.Record.load
def load(string, options={}) # Extract processed values: values = string.to_s.values(options[:repair]) raise ArgumentError, "Invalid argument 'string': Expected at least #{@min_elements} elements for #{@keyword}, got #{values.length}." if values.length < @min_elements RTP.logger.warn "The number of given elements (#{values.length}) exceeds the known number of data elements for this record (#{@max_elements}). This may indicate an invalid string record or that the RTP format has recently been expanded with new elements." if values.length > @max_elements self.send(:set_attributes, values) self end
ruby
def load(string, options={}) # Extract processed values: values = string.to_s.values(options[:repair]) raise ArgumentError, "Invalid argument 'string': Expected at least #{@min_elements} elements for #{@keyword}, got #{values.length}." if values.length < @min_elements RTP.logger.warn "The number of given elements (#{values.length}) exceeds the known number of data elements for this record (#{@max_elements}). This may indicate an invalid string record or that the RTP format has recently been expanded with new elements." if values.length > @max_elements self.send(:set_attributes, values) self end
[ "def", "load", "(", "string", ",", "options", "=", "{", "}", ")", "values", "=", "string", ".", "to_s", ".", "values", "(", "options", "[", ":repair", "]", ")", "raise", "ArgumentError", ",", "\"Invalid argument 'string': Expected at least #{@min_elements} elements for #{@keyword}, got #{values.length}.\"", "if", "values", ".", "length", "<", "@min_elements", "RTP", ".", "logger", ".", "warn", "\"The number of given elements (#{values.length}) exceeds the known number of data elements for this record (#{@max_elements}). This may indicate an invalid string record or that the RTP format has recently been expanded with new elements.\"", "if", "values", ".", "length", ">", "@max_elements", "self", ".", "send", "(", ":set_attributes", ",", "values", ")", "self", "end" ]
Sets up a record by parsing a RTPConnect string line. @param [#to_s] string the extended treatment field definition record string line @return [Record] the updated Record instance @raise [ArgumentError] if given a string containing an invalid number of elements
[ "Sets", "up", "a", "record", "by", "parsing", "a", "RTPConnect", "string", "line", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L86-L93
train
dicom/rtp-connect
lib/rtp-connect/record.rb
RTP.Record.to_s
def to_s(options={}) str = encode(options) children.each do |child| # Note that the extended plan record was introduced in Mosaiq 2.5. str += child.to_s(options) unless child.class == ExtendedPlan && options[:version].to_f < 2.5 end str end
ruby
def to_s(options={}) str = encode(options) children.each do |child| # Note that the extended plan record was introduced in Mosaiq 2.5. str += child.to_s(options) unless child.class == ExtendedPlan && options[:version].to_f < 2.5 end str end
[ "def", "to_s", "(", "options", "=", "{", "}", ")", "str", "=", "encode", "(", "options", ")", "children", ".", "each", "do", "|", "child", "|", "str", "+=", "child", ".", "to_s", "(", "options", ")", "unless", "child", ".", "class", "==", "ExtendedPlan", "&&", "options", "[", ":version", "]", ".", "to_f", "<", "2.5", "end", "str", "end" ]
Encodes the record + any hiearchy of child objects, to a properly formatted RTPConnect ascii string. @param [Hash] options an optional hash parameter @option options [Float] :version the Mosaiq compatibility version number (e.g. 2.4) used for the output @return [String] an RTP string with a single or multiple lines/records
[ "Encodes", "the", "record", "+", "any", "hiearchy", "of", "child", "objects", "to", "a", "properly", "formatted", "RTPConnect", "ascii", "string", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L110-L117
train
dicom/rtp-connect
lib/rtp-connect/record.rb
RTP.Record.delete_child
def delete_child(attribute, instance=nil) if self.send(attribute).is_a?(Array) deleted = self.send(attribute).delete(instance) deleted.parent = nil if deleted else self.send(attribute).parent = nil if self.send(attribute) self.instance_variable_set("@#{attribute}", nil) end end
ruby
def delete_child(attribute, instance=nil) if self.send(attribute).is_a?(Array) deleted = self.send(attribute).delete(instance) deleted.parent = nil if deleted else self.send(attribute).parent = nil if self.send(attribute) self.instance_variable_set("@#{attribute}", nil) end end
[ "def", "delete_child", "(", "attribute", ",", "instance", "=", "nil", ")", "if", "self", ".", "send", "(", "attribute", ")", ".", "is_a?", "(", "Array", ")", "deleted", "=", "self", ".", "send", "(", "attribute", ")", ".", "delete", "(", "instance", ")", "deleted", ".", "parent", "=", "nil", "if", "deleted", "else", "self", ".", "send", "(", "attribute", ")", ".", "parent", "=", "nil", "if", "self", ".", "send", "(", "attribute", ")", "self", ".", "instance_variable_set", "(", "\"@#{attribute}\"", ",", "nil", ")", "end", "end" ]
Removes the reference of the given instance from the attribute of this record. @param [Symbol] attribute the name of the child attribute from which to remove a child @param [Record] instance a child record to be removed from this instance
[ "Removes", "the", "reference", "of", "the", "given", "instance", "from", "the", "attribute", "of", "this", "record", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L139-L147
train
dicom/rtp-connect
lib/rtp-connect/record.rb
RTP.Record.delete_children
def delete_children(attribute) self.send(attribute).each { |c| c.parent = nil } self.send(attribute).clear end
ruby
def delete_children(attribute) self.send(attribute).each { |c| c.parent = nil } self.send(attribute).clear end
[ "def", "delete_children", "(", "attribute", ")", "self", ".", "send", "(", "attribute", ")", ".", "each", "{", "|", "c", "|", "c", ".", "parent", "=", "nil", "}", "self", ".", "send", "(", "attribute", ")", ".", "clear", "end" ]
Removes all child references of the given type from this instance. @param [Symbol] attribute the name of the child attribute to be cleared
[ "Removes", "all", "child", "references", "of", "the", "given", "type", "from", "this", "instance", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L153-L156
train
dicom/rtp-connect
lib/rtp-connect/record.rb
RTP.Record.set_attributes
def set_attributes(values) import_indices([values.length - 1, @max_elements - 1].min).each_with_index do |indices, i| param = nil if indices param = values.values_at(*indices) param = param[0] if param.length == 1 end self.send("#{@attributes[i]}=", param) end @crc = values[-1] end
ruby
def set_attributes(values) import_indices([values.length - 1, @max_elements - 1].min).each_with_index do |indices, i| param = nil if indices param = values.values_at(*indices) param = param[0] if param.length == 1 end self.send("#{@attributes[i]}=", param) end @crc = values[-1] end
[ "def", "set_attributes", "(", "values", ")", "import_indices", "(", "[", "values", ".", "length", "-", "1", ",", "@max_elements", "-", "1", "]", ".", "min", ")", ".", "each_with_index", "do", "|", "indices", ",", "i", "|", "param", "=", "nil", "if", "indices", "param", "=", "values", ".", "values_at", "(", "*", "indices", ")", "param", "=", "param", "[", "0", "]", "if", "param", ".", "length", "==", "1", "end", "self", ".", "send", "(", "\"#{@attributes[i]}=\"", ",", "param", ")", "end", "@crc", "=", "values", "[", "-", "1", "]", "end" ]
Sets the attributes of the record instance. @param [Array<String>] values the record attributes (as parsed from a record string)
[ "Sets", "the", "attributes", "of", "the", "record", "instance", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L162-L172
train
dicom/rtp-connect
lib/rtp-connect/record.rb
RTP.Record.discard_unsupported_attributes
def discard_unsupported_attributes(values, options={}) case self when SiteSetup options[:version].to_f >= 2.6 ? values : values[0..-4] when Field options[:version].to_f >= 2.64 ? values : values[0..-4] when ExtendedField options[:version].to_f >= 2.4 ? values : values[0..-5] when ControlPoint options[:version].to_f >= 2.64 ? values : values[0..31] + values[35..-1] else values end end
ruby
def discard_unsupported_attributes(values, options={}) case self when SiteSetup options[:version].to_f >= 2.6 ? values : values[0..-4] when Field options[:version].to_f >= 2.64 ? values : values[0..-4] when ExtendedField options[:version].to_f >= 2.4 ? values : values[0..-5] when ControlPoint options[:version].to_f >= 2.64 ? values : values[0..31] + values[35..-1] else values end end
[ "def", "discard_unsupported_attributes", "(", "values", ",", "options", "=", "{", "}", ")", "case", "self", "when", "SiteSetup", "options", "[", ":version", "]", ".", "to_f", ">=", "2.6", "?", "values", ":", "values", "[", "0", "..", "-", "4", "]", "when", "Field", "options", "[", ":version", "]", ".", "to_f", ">=", "2.64", "?", "values", ":", "values", "[", "0", "..", "-", "4", "]", "when", "ExtendedField", "options", "[", ":version", "]", ".", "to_f", ">=", "2.4", "?", "values", ":", "values", "[", "0", "..", "-", "5", "]", "when", "ControlPoint", "options", "[", ":version", "]", ".", "to_f", ">=", "2.64", "?", "values", ":", "values", "[", "0", "..", "31", "]", "+", "values", "[", "35", "..", "-", "1", "]", "else", "values", "end", "end" ]
Removes any attributes that are newer than the given compatibility target version. E.g. if a compatibility version of Mosaiq 2.4 is specified, attributes that were introduced in Mosaiq 2.5 or later is removed before the RTP string is created. @param [Array<String>] values the complete set of values of this record @param [Hash] options an optional hash parameter @option options [Float] :version the Mosaiq compatibility version number (e.g. 2.4) used for the output @return [Array<String>] an array of attributes where some of the recent attributes may have been removed
[ "Removes", "any", "attributes", "that", "are", "newer", "than", "the", "given", "compatibility", "target", "version", ".", "E", ".", "g", ".", "if", "a", "compatibility", "version", "of", "Mosaiq", "2", ".", "4", "is", "specified", "attributes", "that", "were", "introduced", "in", "Mosaiq", "2", ".", "5", "or", "later", "is", "removed", "before", "the", "RTP", "string", "is", "created", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L192-L205
train
seanedwards/cfer
lib/cfer/config.rb
Cfer.Config.include_config
def include_config(*files) include_base = File.dirname(@config_file) if @config_file files.each do |file| path = File.join(include_base, file) if include_base include_file(path || file) end end
ruby
def include_config(*files) include_base = File.dirname(@config_file) if @config_file files.each do |file| path = File.join(include_base, file) if include_base include_file(path || file) end end
[ "def", "include_config", "(", "*", "files", ")", "include_base", "=", "File", ".", "dirname", "(", "@config_file", ")", "if", "@config_file", "files", ".", "each", "do", "|", "file", "|", "path", "=", "File", ".", "join", "(", "include_base", ",", "file", ")", "if", "include_base", "include_file", "(", "path", "||", "file", ")", "end", "end" ]
Includes config code from one or more files, and evals it in the context of this stack. Filenames are relative to the file containing the invocation of this method.
[ "Includes", "config", "code", "from", "one", "or", "more", "files", "and", "evals", "it", "in", "the", "context", "of", "this", "stack", ".", "Filenames", "are", "relative", "to", "the", "file", "containing", "the", "invocation", "of", "this", "method", "." ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/config.rb#L34-L40
train
dicom/rtp-connect
lib/rtp-connect/plan.rb
RTP.Plan.write
def write(file, options={}) f = open_file(file) f.write(to_s(options)) f.close end
ruby
def write(file, options={}) f = open_file(file) f.write(to_s(options)) f.close end
[ "def", "write", "(", "file", ",", "options", "=", "{", "}", ")", "f", "=", "open_file", "(", "file", ")", "f", ".", "write", "(", "to_s", "(", "options", ")", ")", "f", ".", "close", "end" ]
Writes the Plan object, along with its hiearchy of child objects, to a properly formatted RTPConnect ascii file. @param [String] file a path/file string @param [Hash] options an optional hash parameter @option options [Float] :version the Mosaiq compatibility version number (e.g. 2.4) used for the output
[ "Writes", "the", "Plan", "object", "along", "with", "its", "hiearchy", "of", "child", "objects", "to", "a", "properly", "formatted", "RTPConnect", "ascii", "file", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan.rb#L317-L321
train
seanedwards/cfer
lib/cfer/cfn/client.rb
Cfer::Cfn.Client.tail
def tail(options = {}) q = [] event_id_highwater = nil counter = 0 number = options[:number] || 0 for_each_event name do |fetched_event| q.unshift fetched_event if counter < number counter = counter + 1 end while q.size > 0 event = q.shift yield event event_id_highwater = event.event_id end sleep_time = 1 running = true if options[:follow] while running sleep_time = [sleep_time * (options[:backoff] || 1), options[:backoff_max_wait] || 15].min begin stack_status = describe_stacks(stack_name: name).stacks.first.stack_status running = running && (/.+_(COMPLETE|FAILED)$/.match(stack_status) == nil) yielding = true for_each_event name do |fetched_event| if event_id_highwater == fetched_event.event_id yielding = false end if yielding q.unshift fetched_event end end rescue Aws::CloudFormation::Errors::Throttling Cfer::LOGGER.debug "AWS SDK is being throttled..." # Keep going though. rescue Aws::CloudFormation::Errors::ValidationError running = false end while q.size > 0 event = q.shift yield event event_id_highwater = event.event_id sleep_time = 1 end sleep sleep_time if running unless options[:no_sleep] end end end
ruby
def tail(options = {}) q = [] event_id_highwater = nil counter = 0 number = options[:number] || 0 for_each_event name do |fetched_event| q.unshift fetched_event if counter < number counter = counter + 1 end while q.size > 0 event = q.shift yield event event_id_highwater = event.event_id end sleep_time = 1 running = true if options[:follow] while running sleep_time = [sleep_time * (options[:backoff] || 1), options[:backoff_max_wait] || 15].min begin stack_status = describe_stacks(stack_name: name).stacks.first.stack_status running = running && (/.+_(COMPLETE|FAILED)$/.match(stack_status) == nil) yielding = true for_each_event name do |fetched_event| if event_id_highwater == fetched_event.event_id yielding = false end if yielding q.unshift fetched_event end end rescue Aws::CloudFormation::Errors::Throttling Cfer::LOGGER.debug "AWS SDK is being throttled..." # Keep going though. rescue Aws::CloudFormation::Errors::ValidationError running = false end while q.size > 0 event = q.shift yield event event_id_highwater = event.event_id sleep_time = 1 end sleep sleep_time if running unless options[:no_sleep] end end end
[ "def", "tail", "(", "options", "=", "{", "}", ")", "q", "=", "[", "]", "event_id_highwater", "=", "nil", "counter", "=", "0", "number", "=", "options", "[", ":number", "]", "||", "0", "for_each_event", "name", "do", "|", "fetched_event", "|", "q", ".", "unshift", "fetched_event", "if", "counter", "<", "number", "counter", "=", "counter", "+", "1", "end", "while", "q", ".", "size", ">", "0", "event", "=", "q", ".", "shift", "yield", "event", "event_id_highwater", "=", "event", ".", "event_id", "end", "sleep_time", "=", "1", "running", "=", "true", "if", "options", "[", ":follow", "]", "while", "running", "sleep_time", "=", "[", "sleep_time", "*", "(", "options", "[", ":backoff", "]", "||", "1", ")", ",", "options", "[", ":backoff_max_wait", "]", "||", "15", "]", ".", "min", "begin", "stack_status", "=", "describe_stacks", "(", "stack_name", ":", "name", ")", ".", "stacks", ".", "first", ".", "stack_status", "running", "=", "running", "&&", "(", "/", "/", ".", "match", "(", "stack_status", ")", "==", "nil", ")", "yielding", "=", "true", "for_each_event", "name", "do", "|", "fetched_event", "|", "if", "event_id_highwater", "==", "fetched_event", ".", "event_id", "yielding", "=", "false", "end", "if", "yielding", "q", ".", "unshift", "fetched_event", "end", "end", "rescue", "Aws", "::", "CloudFormation", "::", "Errors", "::", "Throttling", "Cfer", "::", "LOGGER", ".", "debug", "\"AWS SDK is being throttled...\"", "rescue", "Aws", "::", "CloudFormation", "::", "Errors", "::", "ValidationError", "running", "=", "false", "end", "while", "q", ".", "size", ">", "0", "event", "=", "q", ".", "shift", "yield", "event", "event_id_highwater", "=", "event", ".", "event_id", "sleep_time", "=", "1", "end", "sleep", "sleep_time", "if", "running", "unless", "options", "[", ":no_sleep", "]", "end", "end", "end" ]
Yields to the given block for each CloudFormation event that qualifies, given the specified options. @param options [Hash] The options hash @option options [Fixnum] :number The maximum number of already-existing CloudFormation events to yield. @option options [Boolean] :follow Set to true to wait until the stack enters a `COMPLETE` or `FAILED` state, yielding events as they occur. @option options [Boolean] :no_sleep Don't pause between polling. This is used for tests, and shouldn't be when polling the AWS API. @option options [Fixnum] :backoff The exponential backoff factor (default 1.5) @option options [Fixnum] :backoff_max_wait The maximum amount of time that exponential backoff will wait before polling agian (default 15s)
[ "Yields", "to", "the", "given", "block", "for", "each", "CloudFormation", "event", "that", "qualifies", "given", "the", "specified", "options", "." ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/cfn/client.rb#L154-L207
train
seanedwards/cfer
lib/cfer/block.rb
Cfer.Block.build_from_block
def build_from_block(*args, &block) pre_block Docile.dsl_eval(self, *args, &block) if block post_block self end
ruby
def build_from_block(*args, &block) pre_block Docile.dsl_eval(self, *args, &block) if block post_block self end
[ "def", "build_from_block", "(", "*", "args", ",", "&", "block", ")", "pre_block", "Docile", ".", "dsl_eval", "(", "self", ",", "*", "args", ",", "&", "block", ")", "if", "block", "post_block", "self", "end" ]
Evaluates a DSL directly from a Ruby block, calling pre- and post- hooks. @param args [Array<Object>] Extra arguments to be passed into the block.
[ "Evaluates", "a", "DSL", "directly", "from", "a", "Ruby", "block", "calling", "pre", "-", "and", "post", "-", "hooks", "." ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/block.rb#L10-L15
train
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.add_angle
def add_angle(item, angle_tag, direction_tag, angle, direction, current_angle) if !self.send(current_angle) || angle != self.send(current_angle) self.send("#{current_angle}=", angle) DICOM::Element.new(angle_tag, angle, :parent => item) DICOM::Element.new(direction_tag, (direction.empty? ? 'NONE' : direction), :parent => item) end end
ruby
def add_angle(item, angle_tag, direction_tag, angle, direction, current_angle) if !self.send(current_angle) || angle != self.send(current_angle) self.send("#{current_angle}=", angle) DICOM::Element.new(angle_tag, angle, :parent => item) DICOM::Element.new(direction_tag, (direction.empty? ? 'NONE' : direction), :parent => item) end end
[ "def", "add_angle", "(", "item", ",", "angle_tag", ",", "direction_tag", ",", "angle", ",", "direction", ",", "current_angle", ")", "if", "!", "self", ".", "send", "(", "current_angle", ")", "||", "angle", "!=", "self", ".", "send", "(", "current_angle", ")", "self", ".", "send", "(", "\"#{current_angle}=\"", ",", "angle", ")", "DICOM", "::", "Element", ".", "new", "(", "angle_tag", ",", "angle", ",", ":parent", "=>", "item", ")", "DICOM", "::", "Element", ".", "new", "(", "direction_tag", ",", "(", "direction", ".", "empty?", "?", "'NONE'", ":", "direction", ")", ",", ":parent", "=>", "item", ")", "end", "end" ]
Adds an angular type value to a Control Point Item, by creating the necessary DICOM elements. Note that the element is only added if there is no 'current' attribute defined, or the given value is different form the current attribute. @param [DICOM::Item] item the DICOM control point item in which to create the elements @param [String] angle_tag the DICOM tag of the angle element @param [String] direction_tag the DICOM tag of the direction element @param [String, NilClass] angle the collimator angle attribute @param [String, NilClass] direction the collimator rotation direction attribute @param [Symbol] current_angle the instance variable that keeps track of the current value of this attribute
[ "Adds", "an", "angular", "type", "value", "to", "a", "Control", "Point", "Item", "by", "creating", "the", "necessary", "DICOM", "elements", ".", "Note", "that", "the", "element", "is", "only", "added", "if", "there", "is", "no", "current", "attribute", "defined", "or", "the", "given", "value", "is", "different", "form", "the", "current", "attribute", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L383-L389
train
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.add_couch_position
def add_couch_position(item, tag, value, current) if !self.send(current) || value != self.send(current) self.send("#{current}=", value) DICOM::Element.new(tag, (value.empty? ? '' : value.to_f * 10), :parent => item) end end
ruby
def add_couch_position(item, tag, value, current) if !self.send(current) || value != self.send(current) self.send("#{current}=", value) DICOM::Element.new(tag, (value.empty? ? '' : value.to_f * 10), :parent => item) end end
[ "def", "add_couch_position", "(", "item", ",", "tag", ",", "value", ",", "current", ")", "if", "!", "self", ".", "send", "(", "current", ")", "||", "value", "!=", "self", ".", "send", "(", "current", ")", "self", ".", "send", "(", "\"#{current}=\"", ",", "value", ")", "DICOM", "::", "Element", ".", "new", "(", "tag", ",", "(", "value", ".", "empty?", "?", "''", ":", "value", ".", "to_f", "*", "10", ")", ",", ":parent", "=>", "item", ")", "end", "end" ]
Adds a Table Top Position element to a Control Point Item. Note that the element is only added if there is no 'current' attribute defined, or the given value is different form the current attribute. @param [DICOM::Item] item the DICOM control point item in which to create the element @param [String] tag the DICOM tag of the couch position element @param [String, NilClass] value the couch position @param [Symbol] current the instance variable that keeps track of the current value of this attribute
[ "Adds", "a", "Table", "Top", "Position", "element", "to", "a", "Control", "Point", "Item", ".", "Note", "that", "the", "element", "is", "only", "added", "if", "there", "is", "no", "current", "attribute", "defined", "or", "the", "given", "value", "is", "different", "form", "the", "current", "attribute", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L400-L405
train
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.add_doserate
def add_doserate(value, item) if !@current_doserate || value != @current_doserate @current_doserate = value DICOM::Element.new('300A,0115', value, :parent => item) end end
ruby
def add_doserate(value, item) if !@current_doserate || value != @current_doserate @current_doserate = value DICOM::Element.new('300A,0115', value, :parent => item) end end
[ "def", "add_doserate", "(", "value", ",", "item", ")", "if", "!", "@current_doserate", "||", "value", "!=", "@current_doserate", "@current_doserate", "=", "value", "DICOM", "::", "Element", ".", "new", "(", "'300A,0115'", ",", "value", ",", ":parent", "=>", "item", ")", "end", "end" ]
Adds a Dose Rate Set element to a Control Point Item. Note that the element is only added if there is no 'current' attribute defined, or the given value is different form the current attribute. @param [String, NilClass] value the doserate attribute @param [DICOM::Item] item the DICOM control point item in which to create an element
[ "Adds", "a", "Dose", "Rate", "Set", "element", "to", "a", "Control", "Point", "Item", ".", "Note", "that", "the", "element", "is", "only", "added", "if", "there", "is", "no", "current", "attribute", "defined", "or", "the", "given", "value", "is", "different", "form", "the", "current", "attribute", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L414-L419
train
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.create_control_point
def create_control_point(cp, sequence, options={}) cp_item = DICOM::Item.new(:parent => sequence) # Some CP attributes will always be written (CP index, BLD positions & Cumulative meterset weight). # The other attributes are only written if they are different from the previous control point. # Control Point Index: DICOM::Element.new('300A,0112', "#{cp.index}", :parent => cp_item) # Beam Limiting Device Position Sequence: create_beam_limiting_device_positions(cp_item, cp, options) # Source to Surface Distance: add_ssd(cp.ssd, cp_item) # Cumulative Meterset Weight: DICOM::Element.new('300A,0134', cp.monitor_units.to_f, :parent => cp_item) # Referenced Dose Reference Sequence: create_referenced_dose_reference(cp_item) if options[:dose_ref] # Attributes that are only added if they carry an updated value: # Nominal Beam Energy: add_energy(cp.energy, cp_item) # Dose Rate Set: add_doserate(cp.doserate, cp_item) # Gantry Angle & Rotation Direction: add_angle(cp_item, '300A,011E', '300A,011F', cp.gantry_angle, cp.gantry_dir, :current_gantry) # Beam Limiting Device Angle & Rotation Direction: add_angle(cp_item, '300A,0120', '300A,0121', cp.collimator_angle, cp.collimator_dir, :current_collimator) # Patient Support Angle & Rotation Direction: add_angle(cp_item, '300A,0122', '300A,0123', cp.couch_pedestal, cp.couch_ped_dir, :current_couch_pedestal) # Table Top Eccentric Angle & Rotation Direction: add_angle(cp_item, '300A,0125', '300A,0126', cp.couch_angle, cp.couch_dir, :current_couch_angle) # Table Top Vertical Position: add_couch_position(cp_item, '300A,0128', cp.couch_vertical, :current_couch_vertical) # Table Top Longitudinal Position: add_couch_position(cp_item, '300A,0129', cp.couch_longitudinal, :current_couch_longitudinal) # Table Top Lateral Position: add_couch_position(cp_item, '300A,012A', cp.couch_lateral, :current_couch_lateral) # Isocenter Position (x\y\z): add_isosenter(cp.parent.parent.site_setup, cp_item) cp_item end
ruby
def create_control_point(cp, sequence, options={}) cp_item = DICOM::Item.new(:parent => sequence) # Some CP attributes will always be written (CP index, BLD positions & Cumulative meterset weight). # The other attributes are only written if they are different from the previous control point. # Control Point Index: DICOM::Element.new('300A,0112', "#{cp.index}", :parent => cp_item) # Beam Limiting Device Position Sequence: create_beam_limiting_device_positions(cp_item, cp, options) # Source to Surface Distance: add_ssd(cp.ssd, cp_item) # Cumulative Meterset Weight: DICOM::Element.new('300A,0134', cp.monitor_units.to_f, :parent => cp_item) # Referenced Dose Reference Sequence: create_referenced_dose_reference(cp_item) if options[:dose_ref] # Attributes that are only added if they carry an updated value: # Nominal Beam Energy: add_energy(cp.energy, cp_item) # Dose Rate Set: add_doserate(cp.doserate, cp_item) # Gantry Angle & Rotation Direction: add_angle(cp_item, '300A,011E', '300A,011F', cp.gantry_angle, cp.gantry_dir, :current_gantry) # Beam Limiting Device Angle & Rotation Direction: add_angle(cp_item, '300A,0120', '300A,0121', cp.collimator_angle, cp.collimator_dir, :current_collimator) # Patient Support Angle & Rotation Direction: add_angle(cp_item, '300A,0122', '300A,0123', cp.couch_pedestal, cp.couch_ped_dir, :current_couch_pedestal) # Table Top Eccentric Angle & Rotation Direction: add_angle(cp_item, '300A,0125', '300A,0126', cp.couch_angle, cp.couch_dir, :current_couch_angle) # Table Top Vertical Position: add_couch_position(cp_item, '300A,0128', cp.couch_vertical, :current_couch_vertical) # Table Top Longitudinal Position: add_couch_position(cp_item, '300A,0129', cp.couch_longitudinal, :current_couch_longitudinal) # Table Top Lateral Position: add_couch_position(cp_item, '300A,012A', cp.couch_lateral, :current_couch_lateral) # Isocenter Position (x\y\z): add_isosenter(cp.parent.parent.site_setup, cp_item) cp_item end
[ "def", "create_control_point", "(", "cp", ",", "sequence", ",", "options", "=", "{", "}", ")", "cp_item", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "sequence", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,0112'", ",", "\"#{cp.index}\"", ",", ":parent", "=>", "cp_item", ")", "create_beam_limiting_device_positions", "(", "cp_item", ",", "cp", ",", "options", ")", "add_ssd", "(", "cp", ".", "ssd", ",", "cp_item", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,0134'", ",", "cp", ".", "monitor_units", ".", "to_f", ",", ":parent", "=>", "cp_item", ")", "create_referenced_dose_reference", "(", "cp_item", ")", "if", "options", "[", ":dose_ref", "]", "add_energy", "(", "cp", ".", "energy", ",", "cp_item", ")", "add_doserate", "(", "cp", ".", "doserate", ",", "cp_item", ")", "add_angle", "(", "cp_item", ",", "'300A,011E'", ",", "'300A,011F'", ",", "cp", ".", "gantry_angle", ",", "cp", ".", "gantry_dir", ",", ":current_gantry", ")", "add_angle", "(", "cp_item", ",", "'300A,0120'", ",", "'300A,0121'", ",", "cp", ".", "collimator_angle", ",", "cp", ".", "collimator_dir", ",", ":current_collimator", ")", "add_angle", "(", "cp_item", ",", "'300A,0122'", ",", "'300A,0123'", ",", "cp", ".", "couch_pedestal", ",", "cp", ".", "couch_ped_dir", ",", ":current_couch_pedestal", ")", "add_angle", "(", "cp_item", ",", "'300A,0125'", ",", "'300A,0126'", ",", "cp", ".", "couch_angle", ",", "cp", ".", "couch_dir", ",", ":current_couch_angle", ")", "add_couch_position", "(", "cp_item", ",", "'300A,0128'", ",", "cp", ".", "couch_vertical", ",", ":current_couch_vertical", ")", "add_couch_position", "(", "cp_item", ",", "'300A,0129'", ",", "cp", ".", "couch_longitudinal", ",", ":current_couch_longitudinal", ")", "add_couch_position", "(", "cp_item", ",", "'300A,012A'", ",", "cp", ".", "couch_lateral", ",", ":current_couch_lateral", ")", "add_isosenter", "(", "cp", ".", "parent", ".", "parent", ".", "site_setup", ",", "cp_item", ")", "cp_item", "end" ]
Creates a control point item in the given control point sequence, based on an RTP control point record. @param [ControlPoint] cp the RTP ControlPoint record to convert @param [DICOM::Sequence] sequence the DICOM parent sequence of the item to be created @param [Hash] options the options to use for creating the control point @option options [Boolean] :dose_ref if set, a Referenced Dose Reference sequence will be included in the generated control point item @return [DICOM::Item] the constructed control point DICOM item
[ "Creates", "a", "control", "point", "item", "in", "the", "given", "control", "point", "sequence", "based", "on", "an", "RTP", "control", "point", "record", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L481-L517
train
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.create_beam_limiting_devices
def create_beam_limiting_devices(beam_item, field) bl_seq = DICOM::Sequence.new('300A,00B6', :parent => beam_item) # The ASYMX item ('backup jaws') doesn't exist on all models: if ['SYM', 'ASY'].include?(field.field_x_mode.upcase) bl_item_x = DICOM::Item.new(:parent => bl_seq) DICOM::Element.new('300A,00B8', "ASYMX", :parent => bl_item_x) DICOM::Element.new('300A,00BC', "1", :parent => bl_item_x) end # The ASYMY item is always created: bl_item_y = DICOM::Item.new(:parent => bl_seq) # RT Beam Limiting Device Type: DICOM::Element.new('300A,00B8', "ASYMY", :parent => bl_item_y) # Number of Leaf/Jaw Pairs: DICOM::Element.new('300A,00BC', "1", :parent => bl_item_y) # MLCX item is only created if leaves are defined: # (NB: The RTP file doesn't specify leaf position boundaries, so we # have to set these based on a set of known MLC types, their number # of leaves, and their leaf boundary positions.) if field.control_points.length > 0 bl_item_mlcx = DICOM::Item.new(:parent => bl_seq) DICOM::Element.new('300A,00B8', "MLCX", :parent => bl_item_mlcx) num_leaves = field.control_points.first.mlc_leaves.to_i DICOM::Element.new('300A,00BC', num_leaves.to_s, :parent => bl_item_mlcx) DICOM::Element.new('300A,00BE', "#{RTP.leaf_boundaries(num_leaves).join("\\")}", :parent => bl_item_mlcx) end bl_seq end
ruby
def create_beam_limiting_devices(beam_item, field) bl_seq = DICOM::Sequence.new('300A,00B6', :parent => beam_item) # The ASYMX item ('backup jaws') doesn't exist on all models: if ['SYM', 'ASY'].include?(field.field_x_mode.upcase) bl_item_x = DICOM::Item.new(:parent => bl_seq) DICOM::Element.new('300A,00B8', "ASYMX", :parent => bl_item_x) DICOM::Element.new('300A,00BC', "1", :parent => bl_item_x) end # The ASYMY item is always created: bl_item_y = DICOM::Item.new(:parent => bl_seq) # RT Beam Limiting Device Type: DICOM::Element.new('300A,00B8', "ASYMY", :parent => bl_item_y) # Number of Leaf/Jaw Pairs: DICOM::Element.new('300A,00BC', "1", :parent => bl_item_y) # MLCX item is only created if leaves are defined: # (NB: The RTP file doesn't specify leaf position boundaries, so we # have to set these based on a set of known MLC types, their number # of leaves, and their leaf boundary positions.) if field.control_points.length > 0 bl_item_mlcx = DICOM::Item.new(:parent => bl_seq) DICOM::Element.new('300A,00B8', "MLCX", :parent => bl_item_mlcx) num_leaves = field.control_points.first.mlc_leaves.to_i DICOM::Element.new('300A,00BC', num_leaves.to_s, :parent => bl_item_mlcx) DICOM::Element.new('300A,00BE', "#{RTP.leaf_boundaries(num_leaves).join("\\")}", :parent => bl_item_mlcx) end bl_seq end
[ "def", "create_beam_limiting_devices", "(", "beam_item", ",", "field", ")", "bl_seq", "=", "DICOM", "::", "Sequence", ".", "new", "(", "'300A,00B6'", ",", ":parent", "=>", "beam_item", ")", "if", "[", "'SYM'", ",", "'ASY'", "]", ".", "include?", "(", "field", ".", "field_x_mode", ".", "upcase", ")", "bl_item_x", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "bl_seq", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,00B8'", ",", "\"ASYMX\"", ",", ":parent", "=>", "bl_item_x", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,00BC'", ",", "\"1\"", ",", ":parent", "=>", "bl_item_x", ")", "end", "bl_item_y", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "bl_seq", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,00B8'", ",", "\"ASYMY\"", ",", ":parent", "=>", "bl_item_y", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,00BC'", ",", "\"1\"", ",", ":parent", "=>", "bl_item_y", ")", "if", "field", ".", "control_points", ".", "length", ">", "0", "bl_item_mlcx", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "bl_seq", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,00B8'", ",", "\"MLCX\"", ",", ":parent", "=>", "bl_item_mlcx", ")", "num_leaves", "=", "field", ".", "control_points", ".", "first", ".", "mlc_leaves", ".", "to_i", "DICOM", "::", "Element", ".", "new", "(", "'300A,00BC'", ",", "num_leaves", ".", "to_s", ",", ":parent", "=>", "bl_item_mlcx", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,00BE'", ",", "\"#{RTP.leaf_boundaries(num_leaves).join(\"\\\\\")}\"", ",", ":parent", "=>", "bl_item_mlcx", ")", "end", "bl_seq", "end" ]
Creates a beam limiting device sequence in the given DICOM object. @param [DICOM::Item] beam_item the DICOM beam item in which to insert the sequence @param [Field] field the RTP field to fetch device parameters from @return [DICOM::Sequence] the constructed beam limiting device sequence
[ "Creates", "a", "beam", "limiting", "device", "sequence", "in", "the", "given", "DICOM", "object", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L525-L551
train
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.create_asym_item
def create_asym_item(cp, dcm_parent, axis, options={}) val1 = cp.send("dcm_collimator_#{axis.to_s}1", options[:scale]) val2 = cp.send("dcm_collimator_#{axis.to_s}2", options[:scale]) item = DICOM::Item.new(:parent => dcm_parent) # RT Beam Limiting Device Type: DICOM::Element.new('300A,00B8', "ASYM#{axis.to_s.upcase}", :parent => item) # Leaf/Jaw Positions: DICOM::Element.new('300A,011C', "#{val1}\\#{val2}", :parent => item) item end
ruby
def create_asym_item(cp, dcm_parent, axis, options={}) val1 = cp.send("dcm_collimator_#{axis.to_s}1", options[:scale]) val2 = cp.send("dcm_collimator_#{axis.to_s}2", options[:scale]) item = DICOM::Item.new(:parent => dcm_parent) # RT Beam Limiting Device Type: DICOM::Element.new('300A,00B8', "ASYM#{axis.to_s.upcase}", :parent => item) # Leaf/Jaw Positions: DICOM::Element.new('300A,011C', "#{val1}\\#{val2}", :parent => item) item end
[ "def", "create_asym_item", "(", "cp", ",", "dcm_parent", ",", "axis", ",", "options", "=", "{", "}", ")", "val1", "=", "cp", ".", "send", "(", "\"dcm_collimator_#{axis.to_s}1\"", ",", "options", "[", ":scale", "]", ")", "val2", "=", "cp", ".", "send", "(", "\"dcm_collimator_#{axis.to_s}2\"", ",", "options", "[", ":scale", "]", ")", "item", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "dcm_parent", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,00B8'", ",", "\"ASYM#{axis.to_s.upcase}\"", ",", ":parent", "=>", "item", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,011C'", ",", "\"#{val1}\\\\#{val2}\"", ",", ":parent", "=>", "item", ")", "item", "end" ]
Creates an ASYMX or ASYMY item. @param [ControlPoint] cp the RTP control point to fetch device parameters from @param [DICOM::Sequence] dcm_parent the DICOM sequence in which to insert the item @param [Symbol] axis the axis for the item (:x or :y) @return [DICOM::Item] the constructed ASYMX or ASYMY item
[ "Creates", "an", "ASYMX", "or", "ASYMY", "item", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L583-L592
train
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.create_dose_reference
def create_dose_reference(dcm, description) dr_seq = DICOM::Sequence.new('300A,0010', :parent => dcm) dr_item = DICOM::Item.new(:parent => dr_seq) # Dose Reference Number: DICOM::Element.new('300A,0012', '1', :parent => dr_item) # Dose Reference Structure Type: DICOM::Element.new('300A,0014', 'SITE', :parent => dr_item) # Dose Reference Description: DICOM::Element.new('300A,0016', description, :parent => dr_item) # Dose Reference Type: DICOM::Element.new('300A,0020', 'TARGET', :parent => dr_item) dr_seq end
ruby
def create_dose_reference(dcm, description) dr_seq = DICOM::Sequence.new('300A,0010', :parent => dcm) dr_item = DICOM::Item.new(:parent => dr_seq) # Dose Reference Number: DICOM::Element.new('300A,0012', '1', :parent => dr_item) # Dose Reference Structure Type: DICOM::Element.new('300A,0014', 'SITE', :parent => dr_item) # Dose Reference Description: DICOM::Element.new('300A,0016', description, :parent => dr_item) # Dose Reference Type: DICOM::Element.new('300A,0020', 'TARGET', :parent => dr_item) dr_seq end
[ "def", "create_dose_reference", "(", "dcm", ",", "description", ")", "dr_seq", "=", "DICOM", "::", "Sequence", ".", "new", "(", "'300A,0010'", ",", ":parent", "=>", "dcm", ")", "dr_item", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "dr_seq", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,0012'", ",", "'1'", ",", ":parent", "=>", "dr_item", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,0014'", ",", "'SITE'", ",", ":parent", "=>", "dr_item", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,0016'", ",", "description", ",", ":parent", "=>", "dr_item", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,0020'", ",", "'TARGET'", ",", ":parent", "=>", "dr_item", ")", "dr_seq", "end" ]
Creates a dose reference sequence in the given DICOM object. @param [DICOM::DObject] dcm the DICOM object in which to insert the sequence @param [String] description the value to use for Dose Reference Description @return [DICOM::Sequence] the constructed dose reference sequence
[ "Creates", "a", "dose", "reference", "sequence", "in", "the", "given", "DICOM", "object", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L619-L631
train
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.create_referenced_dose_reference
def create_referenced_dose_reference(cp_item) # Referenced Dose Reference Sequence: rd_seq = DICOM::Sequence.new('300C,0050', :parent => cp_item) rd_item = DICOM::Item.new(:parent => rd_seq) # Cumulative Dose Reference Coeffecient: DICOM::Element.new('300A,010C', '', :parent => rd_item) # Referenced Dose Reference Number: DICOM::Element.new('300C,0051', '1', :parent => rd_item) rd_seq end
ruby
def create_referenced_dose_reference(cp_item) # Referenced Dose Reference Sequence: rd_seq = DICOM::Sequence.new('300C,0050', :parent => cp_item) rd_item = DICOM::Item.new(:parent => rd_seq) # Cumulative Dose Reference Coeffecient: DICOM::Element.new('300A,010C', '', :parent => rd_item) # Referenced Dose Reference Number: DICOM::Element.new('300C,0051', '1', :parent => rd_item) rd_seq end
[ "def", "create_referenced_dose_reference", "(", "cp_item", ")", "rd_seq", "=", "DICOM", "::", "Sequence", ".", "new", "(", "'300C,0050'", ",", ":parent", "=>", "cp_item", ")", "rd_item", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "rd_seq", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,010C'", ",", "''", ",", ":parent", "=>", "rd_item", ")", "DICOM", "::", "Element", ".", "new", "(", "'300C,0051'", ",", "'1'", ",", ":parent", "=>", "rd_item", ")", "rd_seq", "end" ]
Creates a referenced dose reference sequence in the given DICOM object. @param [DICOM::Item] cp_item the DICOM item in which to insert the sequence @return [DICOM::Sequence] the constructed referenced dose reference sequence
[ "Creates", "a", "referenced", "dose", "reference", "sequence", "in", "the", "given", "DICOM", "object", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L638-L647
train
nicotaing/yaml_record
lib/yaml_record/base.rb
YamlRecord.Base.save
def save run_callbacks(:before_save) run_callbacks(:before_create) unless self.is_created existing_items = self.class.all if self.new_record? existing_items << self else # update existing record updated_item = existing_items.find { |item| item.id == self.id } return false unless updated_item updated_item.attributes = self.attributes end raw_data = existing_items ? existing_items.map { |item| item.persisted_attributes } : [] self.class.write_contents(raw_data) if self.valid? run_callbacks(:after_create) unless self.is_created run_callbacks(:after_save) true rescue IOError false end
ruby
def save run_callbacks(:before_save) run_callbacks(:before_create) unless self.is_created existing_items = self.class.all if self.new_record? existing_items << self else # update existing record updated_item = existing_items.find { |item| item.id == self.id } return false unless updated_item updated_item.attributes = self.attributes end raw_data = existing_items ? existing_items.map { |item| item.persisted_attributes } : [] self.class.write_contents(raw_data) if self.valid? run_callbacks(:after_create) unless self.is_created run_callbacks(:after_save) true rescue IOError false end
[ "def", "save", "run_callbacks", "(", ":before_save", ")", "run_callbacks", "(", ":before_create", ")", "unless", "self", ".", "is_created", "existing_items", "=", "self", ".", "class", ".", "all", "if", "self", ".", "new_record?", "existing_items", "<<", "self", "else", "updated_item", "=", "existing_items", ".", "find", "{", "|", "item", "|", "item", ".", "id", "==", "self", ".", "id", "}", "return", "false", "unless", "updated_item", "updated_item", ".", "attributes", "=", "self", ".", "attributes", "end", "raw_data", "=", "existing_items", "?", "existing_items", ".", "map", "{", "|", "item", "|", "item", ".", "persisted_attributes", "}", ":", "[", "]", "self", ".", "class", ".", "write_contents", "(", "raw_data", ")", "if", "self", ".", "valid?", "run_callbacks", "(", ":after_create", ")", "unless", "self", ".", "is_created", "run_callbacks", "(", ":after_save", ")", "true", "rescue", "IOError", "false", "end" ]
Saved YamlRecord instance to file Executes save and create callbacks Returns true if record saved; false otherwise === Example: @post.save => true
[ "Saved", "YamlRecord", "instance", "to", "file", "Executes", "save", "and", "create", "callbacks", "Returns", "true", "if", "record", "saved", ";", "false", "otherwise" ]
653a7f6b6c53f67bc91082a455914489fd3498fa
https://github.com/nicotaing/yaml_record/blob/653a7f6b6c53f67bc91082a455914489fd3498fa/lib/yaml_record/base.rb#L57-L78
train
nicotaing/yaml_record
lib/yaml_record/base.rb
YamlRecord.Base.destroy
def destroy run_callbacks(:before_destroy) new_data = self.class.all.reject { |item| item.persisted_attributes == self.persisted_attributes }.map { |item| item.persisted_attributes } self.class.write_contents(new_data) self.is_destroyed = true run_callbacks(:after_destroy) true rescue IOError false end
ruby
def destroy run_callbacks(:before_destroy) new_data = self.class.all.reject { |item| item.persisted_attributes == self.persisted_attributes }.map { |item| item.persisted_attributes } self.class.write_contents(new_data) self.is_destroyed = true run_callbacks(:after_destroy) true rescue IOError false end
[ "def", "destroy", "run_callbacks", "(", ":before_destroy", ")", "new_data", "=", "self", ".", "class", ".", "all", ".", "reject", "{", "|", "item", "|", "item", ".", "persisted_attributes", "==", "self", ".", "persisted_attributes", "}", ".", "map", "{", "|", "item", "|", "item", ".", "persisted_attributes", "}", "self", ".", "class", ".", "write_contents", "(", "new_data", ")", "self", ".", "is_destroyed", "=", "true", "run_callbacks", "(", ":after_destroy", ")", "true", "rescue", "IOError", "false", "end" ]
Remove a persisted YamlRecord object Returns true if destroyed; false otherwise === Example: @post = Post.create(:foo => "bar", :miso => "great") Post.all.size => 1 @post.destroy => true Post.all.size => 0
[ "Remove", "a", "persisted", "YamlRecord", "object", "Returns", "true", "if", "destroyed", ";", "false", "otherwise" ]
653a7f6b6c53f67bc91082a455914489fd3498fa
https://github.com/nicotaing/yaml_record/blob/653a7f6b6c53f67bc91082a455914489fd3498fa/lib/yaml_record/base.rb#L154-L163
train
seanedwards/cfer
lib/cfer/core/resource.rb
Cfer::Core.Resource.tag
def tag(k, v, **options) self[:Properties][:Tags] ||= [] self[:Properties][:Tags].delete_if { |kv| kv["Key"] == k } self[:Properties][:Tags].unshift({"Key" => k, "Value" => v}.merge(options)) end
ruby
def tag(k, v, **options) self[:Properties][:Tags] ||= [] self[:Properties][:Tags].delete_if { |kv| kv["Key"] == k } self[:Properties][:Tags].unshift({"Key" => k, "Value" => v}.merge(options)) end
[ "def", "tag", "(", "k", ",", "v", ",", "**", "options", ")", "self", "[", ":Properties", "]", "[", ":Tags", "]", "||=", "[", "]", "self", "[", ":Properties", "]", "[", ":Tags", "]", ".", "delete_if", "{", "|", "kv", "|", "kv", "[", "\"Key\"", "]", "==", "k", "}", "self", "[", ":Properties", "]", "[", ":Tags", "]", ".", "unshift", "(", "{", "\"Key\"", "=>", "k", ",", "\"Value\"", "=>", "v", "}", ".", "merge", "(", "options", ")", ")", "end" ]
Sets a tag on this resource. The resource must support the CloudFormation `Tags` property. @param k [String] The name of the tag to set @param v [String] The value for this tag @param options [Hash] An arbitrary set of additional properties to be added to this tag, for example `PropagateOnLaunch` on `AWS::AutoScaling::AutoScalingGroup`
[ "Sets", "a", "tag", "on", "this", "resource", ".", "The", "resource", "must", "support", "the", "CloudFormation", "Tags", "property", "." ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/core/resource.rb#L42-L46
train
seanedwards/cfer
lib/cfer/core/stack.rb
Cfer::Core.Stack.parameter
def parameter(name, options = {}) param = {} options.each do |key, v| next if v === nil k = key.to_s.camelize.to_sym param[k] = case k when :AllowedPattern if v.class == Regexp v.source end when :Default @parameters[name] ||= v end param[k] ||= v end param[:Type] ||= 'String' self[:Parameters][name] = param end
ruby
def parameter(name, options = {}) param = {} options.each do |key, v| next if v === nil k = key.to_s.camelize.to_sym param[k] = case k when :AllowedPattern if v.class == Regexp v.source end when :Default @parameters[name] ||= v end param[k] ||= v end param[:Type] ||= 'String' self[:Parameters][name] = param end
[ "def", "parameter", "(", "name", ",", "options", "=", "{", "}", ")", "param", "=", "{", "}", "options", ".", "each", "do", "|", "key", ",", "v", "|", "next", "if", "v", "===", "nil", "k", "=", "key", ".", "to_s", ".", "camelize", ".", "to_sym", "param", "[", "k", "]", "=", "case", "k", "when", ":AllowedPattern", "if", "v", ".", "class", "==", "Regexp", "v", ".", "source", "end", "when", ":Default", "@parameters", "[", "name", "]", "||=", "v", "end", "param", "[", "k", "]", "||=", "v", "end", "param", "[", ":Type", "]", "||=", "'String'", "self", "[", ":Parameters", "]", "[", "name", "]", "=", "param", "end" ]
Declares a CloudFormation parameter @param name [String] The parameter name @param options [Hash] @option options [String] :type The type for the CloudFormation parameter @option options [String] :default A value of the appropriate type for the template to use if no value is specified when a stack is created. If you define constraints for the parameter, you must specify a value that adheres to those constraints. @option options [String] :no_echo Whether to mask the parameter value whenever anyone makes a call that describes the stack. If you set the value to `true`, the parameter value is masked with asterisks (*****). @option options [String] :allowed_values An array containing the list of values allowed for the parameter. @option options [String] :allowed_pattern A regular expression that represents the patterns you want to allow for String types. @option options [Number] :max_length An integer value that determines the largest number of characters you want to allow for String types. @option options [Number] :min_length An integer value that determines the smallest number of characters you want to allow for String types. @option options [Number] :max_value A numeric value that determines the largest numeric value you want to allow for Number types. @option options [Number] :min_value A numeric value that determines the smallest numeric value you want to allow for Number types. @option options [String] :description A string of up to 4000 characters that describes the parameter. @option options [String] :constraint_description A string that explains the constraint when the constraint is violated. For example, without a constraint description, a parameter that has an allowed pattern of `[A-Za-z0-9]+` displays the following error message when the user specifies an invalid value: ```Malformed input-Parameter MyParameter must match pattern [A-Za-z0-9]+``` By adding a constraint description, such as must only contain upper- and lowercase letters, and numbers, you can display a customized error message: ```Malformed input-Parameter MyParameter must only contain upper and lower case letters and numbers```
[ "Declares", "a", "CloudFormation", "parameter" ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/core/stack.rb#L104-L123
train
seanedwards/cfer
lib/cfer/core/stack.rb
Cfer::Core.Stack.resource
def resource(name, type, options = {}, &block) Preconditions.check_argument(/[[:alnum:]]+/ =~ name, "Resource name must be alphanumeric") clazz = Cfer::Core::Resource.resource_class(type) rc = clazz.new(name, type, self, options, &block) self[:Resources][name] = rc rc.handle end
ruby
def resource(name, type, options = {}, &block) Preconditions.check_argument(/[[:alnum:]]+/ =~ name, "Resource name must be alphanumeric") clazz = Cfer::Core::Resource.resource_class(type) rc = clazz.new(name, type, self, options, &block) self[:Resources][name] = rc rc.handle end
[ "def", "resource", "(", "name", ",", "type", ",", "options", "=", "{", "}", ",", "&", "block", ")", "Preconditions", ".", "check_argument", "(", "/", "/", "=~", "name", ",", "\"Resource name must be alphanumeric\"", ")", "clazz", "=", "Cfer", "::", "Core", "::", "Resource", ".", "resource_class", "(", "type", ")", "rc", "=", "clazz", ".", "new", "(", "name", ",", "type", ",", "self", ",", "options", ",", "&", "block", ")", "self", "[", ":Resources", "]", "[", "name", "]", "=", "rc", "rc", ".", "handle", "end" ]
Creates a CloudFormation resource @param name [String] The name of the resource (must be alphanumeric) @param type [String] The type of CloudFormation resource to create. @param options [Hash] Additional attributes to add to the resource block (such as the `UpdatePolicy` for an `AWS::AutoScaling::AutoScalingGroup`)
[ "Creates", "a", "CloudFormation", "resource" ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/core/stack.rb#L141-L149
train
seanedwards/cfer
lib/cfer/core/stack.rb
Cfer::Core.Stack.include_template
def include_template(*files) include_base = options[:include_base] || File.dirname(caller.first.split(/:\d/,2).first) files.each do |file| path = File.join(include_base, file) include_file(path) end end
ruby
def include_template(*files) include_base = options[:include_base] || File.dirname(caller.first.split(/:\d/,2).first) files.each do |file| path = File.join(include_base, file) include_file(path) end end
[ "def", "include_template", "(", "*", "files", ")", "include_base", "=", "options", "[", ":include_base", "]", "||", "File", ".", "dirname", "(", "caller", ".", "first", ".", "split", "(", "/", "\\d", "/", ",", "2", ")", ".", "first", ")", "files", ".", "each", "do", "|", "file", "|", "path", "=", "File", ".", "join", "(", "include_base", ",", "file", ")", "include_file", "(", "path", ")", "end", "end" ]
Includes template code from one or more files, and evals it in the context of this stack. Filenames are relative to the file containing the invocation of this method.
[ "Includes", "template", "code", "from", "one", "or", "more", "files", "and", "evals", "it", "in", "the", "context", "of", "this", "stack", ".", "Filenames", "are", "relative", "to", "the", "file", "containing", "the", "invocation", "of", "this", "method", "." ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/core/stack.rb#L177-L183
train
seanedwards/cfer
lib/cfer/core/stack.rb
Cfer::Core.Stack.lookup_outputs
def lookup_outputs(stack) client = @options[:client] || raise(Cfer::Util::CferError, "Can not fetch stack outputs without a client") client.fetch_outputs(stack) end
ruby
def lookup_outputs(stack) client = @options[:client] || raise(Cfer::Util::CferError, "Can not fetch stack outputs without a client") client.fetch_outputs(stack) end
[ "def", "lookup_outputs", "(", "stack", ")", "client", "=", "@options", "[", ":client", "]", "||", "raise", "(", "Cfer", "::", "Util", "::", "CferError", ",", "\"Can not fetch stack outputs without a client\"", ")", "client", ".", "fetch_outputs", "(", "stack", ")", "end" ]
Looks up a hash of all outputs from another CloudFormation stack in the same region. @param stack [String] The name of the stack to fetch outputs from
[ "Looks", "up", "a", "hash", "of", "all", "outputs", "from", "another", "CloudFormation", "stack", "in", "the", "same", "region", "." ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/core/stack.rb#L194-L197
train
envato/rack_fake_s3
lib/rack_fake_s3/sorted_object_list.rb
RackFakeS3.SortedObjectList.list
def list(options) marker = options[:marker] prefix = options[:prefix] max_keys = options[:max_keys] || 1000 delimiter = options[:delimiter] ms = S3MatchSet.new marker_found = true pseudo = nil if marker marker_found = false if !@object_map[marker] pseudo = S3Object.new pseudo.name = marker @sorted_set << pseudo end end count = 0 @sorted_set.each do |s3_object| if marker_found && (!prefix or s3_object.name.index(prefix) == 0) count += 1 if count <= max_keys ms.matches << s3_object else is_truncated = true break end end if marker and marker == s3_object.name marker_found = true end end if pseudo @sorted_set.delete(pseudo) end return ms end
ruby
def list(options) marker = options[:marker] prefix = options[:prefix] max_keys = options[:max_keys] || 1000 delimiter = options[:delimiter] ms = S3MatchSet.new marker_found = true pseudo = nil if marker marker_found = false if !@object_map[marker] pseudo = S3Object.new pseudo.name = marker @sorted_set << pseudo end end count = 0 @sorted_set.each do |s3_object| if marker_found && (!prefix or s3_object.name.index(prefix) == 0) count += 1 if count <= max_keys ms.matches << s3_object else is_truncated = true break end end if marker and marker == s3_object.name marker_found = true end end if pseudo @sorted_set.delete(pseudo) end return ms end
[ "def", "list", "(", "options", ")", "marker", "=", "options", "[", ":marker", "]", "prefix", "=", "options", "[", ":prefix", "]", "max_keys", "=", "options", "[", ":max_keys", "]", "||", "1000", "delimiter", "=", "options", "[", ":delimiter", "]", "ms", "=", "S3MatchSet", ".", "new", "marker_found", "=", "true", "pseudo", "=", "nil", "if", "marker", "marker_found", "=", "false", "if", "!", "@object_map", "[", "marker", "]", "pseudo", "=", "S3Object", ".", "new", "pseudo", ".", "name", "=", "marker", "@sorted_set", "<<", "pseudo", "end", "end", "count", "=", "0", "@sorted_set", ".", "each", "do", "|", "s3_object", "|", "if", "marker_found", "&&", "(", "!", "prefix", "or", "s3_object", ".", "name", ".", "index", "(", "prefix", ")", "==", "0", ")", "count", "+=", "1", "if", "count", "<=", "max_keys", "ms", ".", "matches", "<<", "s3_object", "else", "is_truncated", "=", "true", "break", "end", "end", "if", "marker", "and", "marker", "==", "s3_object", ".", "name", "marker_found", "=", "true", "end", "end", "if", "pseudo", "@sorted_set", ".", "delete", "(", "pseudo", ")", "end", "return", "ms", "end" ]
Return back a set of matches based on the passed in options options: :marker : a string to start the lexographical search (it is not included in the result) :max_keys : a maximum number of results :prefix : a string to filter the results by :delimiter : not supported yet
[ "Return", "back", "a", "set", "of", "matches", "based", "on", "the", "passed", "in", "options" ]
d230c40579496acd8eccd62363c43b7329f6f27d
https://github.com/envato/rack_fake_s3/blob/d230c40579496acd8eccd62363c43b7329f6f27d/lib/rack_fake_s3/sorted_object_list.rb#L57-L98
train
locomote/gusteau
lib/gusteau/config.rb
Gusteau.Config.build_node
def build_node(node_name, env_hash, node_hash) node_config = { 'server' => node_hash.slice('host', 'port', 'user', 'password', 'platform', 'vagrant'), 'attributes' => (node_hash['attributes'] || {}).deep_merge(env_hash['attributes'] || {}), 'run_list' => node_hash['run_list'] || env_hash['run_list'], 'before' => env_hash['before'] || @config['before'], 'after' => env_hash['after'] || @config['after'] } node_config['server'].delete 'attributes' Gusteau::Node.new(node_name, node_config) end
ruby
def build_node(node_name, env_hash, node_hash) node_config = { 'server' => node_hash.slice('host', 'port', 'user', 'password', 'platform', 'vagrant'), 'attributes' => (node_hash['attributes'] || {}).deep_merge(env_hash['attributes'] || {}), 'run_list' => node_hash['run_list'] || env_hash['run_list'], 'before' => env_hash['before'] || @config['before'], 'after' => env_hash['after'] || @config['after'] } node_config['server'].delete 'attributes' Gusteau::Node.new(node_name, node_config) end
[ "def", "build_node", "(", "node_name", ",", "env_hash", ",", "node_hash", ")", "node_config", "=", "{", "'server'", "=>", "node_hash", ".", "slice", "(", "'host'", ",", "'port'", ",", "'user'", ",", "'password'", ",", "'platform'", ",", "'vagrant'", ")", ",", "'attributes'", "=>", "(", "node_hash", "[", "'attributes'", "]", "||", "{", "}", ")", ".", "deep_merge", "(", "env_hash", "[", "'attributes'", "]", "||", "{", "}", ")", ",", "'run_list'", "=>", "node_hash", "[", "'run_list'", "]", "||", "env_hash", "[", "'run_list'", "]", ",", "'before'", "=>", "env_hash", "[", "'before'", "]", "||", "@config", "[", "'before'", "]", ",", "'after'", "=>", "env_hash", "[", "'after'", "]", "||", "@config", "[", "'after'", "]", "}", "node_config", "[", "'server'", "]", ".", "delete", "'attributes'", "Gusteau", "::", "Node", ".", "new", "(", "node_name", ",", "node_config", ")", "end" ]
Node attributes get deep-merged with the environment ones Node run_list overrides the environment one Environment before hooks override global ones
[ "Node", "attributes", "get", "deep", "-", "merged", "with", "the", "environment", "ones", "Node", "run_list", "overrides", "the", "environment", "one", "Environment", "before", "hooks", "override", "global", "ones" ]
1c4d7ba0dcb9879c84c2d5b8499385399c1c6d77
https://github.com/locomote/gusteau/blob/1c4d7ba0dcb9879c84c2d5b8499385399c1c6d77/lib/gusteau/config.rb#L62-L72
train
envato/rack_fake_s3
lib/rack_fake_s3/server.rb
RackFakeS3.Servlet.normalize_request
def normalize_request(rack_req) host = rack_req.host s_req = Request.new s_req.path = path_for_rack_request(rack_req) s_req.is_path_style = true s_req.rack_request = rack_req if !@root_hostnames.include?(host) s_req.bucket = host.split(".")[0] s_req.is_path_style = false end s_req.http_verb = rack_req.request_method case rack_req.request_method when 'PUT' normalize_put(rack_req,s_req) when 'GET','HEAD' normalize_get(rack_req,s_req) when 'DELETE' normalize_delete(rack_req,s_req) when 'POST' normalize_post(rack_req,s_req) when 'OPTIONS' nomalize_options(rack_req,s_req) else return false end if s_req.type.nil? return false end return s_req end
ruby
def normalize_request(rack_req) host = rack_req.host s_req = Request.new s_req.path = path_for_rack_request(rack_req) s_req.is_path_style = true s_req.rack_request = rack_req if !@root_hostnames.include?(host) s_req.bucket = host.split(".")[0] s_req.is_path_style = false end s_req.http_verb = rack_req.request_method case rack_req.request_method when 'PUT' normalize_put(rack_req,s_req) when 'GET','HEAD' normalize_get(rack_req,s_req) when 'DELETE' normalize_delete(rack_req,s_req) when 'POST' normalize_post(rack_req,s_req) when 'OPTIONS' nomalize_options(rack_req,s_req) else return false end if s_req.type.nil? return false end return s_req end
[ "def", "normalize_request", "(", "rack_req", ")", "host", "=", "rack_req", ".", "host", "s_req", "=", "Request", ".", "new", "s_req", ".", "path", "=", "path_for_rack_request", "(", "rack_req", ")", "s_req", ".", "is_path_style", "=", "true", "s_req", ".", "rack_request", "=", "rack_req", "if", "!", "@root_hostnames", ".", "include?", "(", "host", ")", "s_req", ".", "bucket", "=", "host", ".", "split", "(", "\".\"", ")", "[", "0", "]", "s_req", ".", "is_path_style", "=", "false", "end", "s_req", ".", "http_verb", "=", "rack_req", ".", "request_method", "case", "rack_req", ".", "request_method", "when", "'PUT'", "normalize_put", "(", "rack_req", ",", "s_req", ")", "when", "'GET'", ",", "'HEAD'", "normalize_get", "(", "rack_req", ",", "s_req", ")", "when", "'DELETE'", "normalize_delete", "(", "rack_req", ",", "s_req", ")", "when", "'POST'", "normalize_post", "(", "rack_req", ",", "s_req", ")", "when", "'OPTIONS'", "nomalize_options", "(", "rack_req", ",", "s_req", ")", "else", "return", "false", "end", "if", "s_req", ".", "type", ".", "nil?", "return", "false", "end", "return", "s_req", "end" ]
This method takes a rack request and generates a normalized RackFakeS3 request
[ "This", "method", "takes", "a", "rack", "request", "and", "generates", "a", "normalized", "RackFakeS3", "request" ]
d230c40579496acd8eccd62363c43b7329f6f27d
https://github.com/envato/rack_fake_s3/blob/d230c40579496acd8eccd62363c43b7329f6f27d/lib/rack_fake_s3/server.rb#L356-L391
train
koraktor/metior
lib/metior/report.rb
Metior.Report.generate
def generate(target_dir, with_assets = true) target_dir = File.expand_path target_dir copy_assets target_dir if with_assets render.each do |view_name, output| file_name = File.join target_dir, view_name.to_s.downcase + '.html' begin output_file = File.open file_name, 'wb' output_file.write output ensure output_file.close end end end
ruby
def generate(target_dir, with_assets = true) target_dir = File.expand_path target_dir copy_assets target_dir if with_assets render.each do |view_name, output| file_name = File.join target_dir, view_name.to_s.downcase + '.html' begin output_file = File.open file_name, 'wb' output_file.write output ensure output_file.close end end end
[ "def", "generate", "(", "target_dir", ",", "with_assets", "=", "true", ")", "target_dir", "=", "File", ".", "expand_path", "target_dir", "copy_assets", "target_dir", "if", "with_assets", "render", ".", "each", "do", "|", "view_name", ",", "output", "|", "file_name", "=", "File", ".", "join", "target_dir", ",", "view_name", ".", "to_s", ".", "downcase", "+", "'.html'", "begin", "output_file", "=", "File", ".", "open", "file_name", ",", "'wb'", "output_file", ".", "write", "output", "ensure", "output_file", ".", "close", "end", "end", "end" ]
Creates a new report for the given repository and commit range @param [Repository] repository The repository to analyze @param [String, Range] range The commit range to analyze Generates this report's output into the given target directory This will generate individual HTML files for the main views of the report. @param [String] target_dir The target directory of the report @param [Boolean] with_assets If `false` the report's assets will not be copied to the target directory
[ "Creates", "a", "new", "report", "for", "the", "given", "repository", "and", "commit", "range" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/report.rb#L163-L176
train
koraktor/metior
lib/metior/report.rb
Metior.Report.copy_assets
def copy_assets(target_dir) FileUtils.mkdir_p target_dir self.class.assets.map do |asset| asset_path = self.class.find asset asset_dir = File.join target_dir, File.dirname(asset) FileUtils.mkdir_p asset_dir unless File.exists? asset_dir FileUtils.cp_r asset_path, asset_dir end end
ruby
def copy_assets(target_dir) FileUtils.mkdir_p target_dir self.class.assets.map do |asset| asset_path = self.class.find asset asset_dir = File.join target_dir, File.dirname(asset) FileUtils.mkdir_p asset_dir unless File.exists? asset_dir FileUtils.cp_r asset_path, asset_dir end end
[ "def", "copy_assets", "(", "target_dir", ")", "FileUtils", ".", "mkdir_p", "target_dir", "self", ".", "class", ".", "assets", ".", "map", "do", "|", "asset", "|", "asset_path", "=", "self", ".", "class", ".", "find", "asset", "asset_dir", "=", "File", ".", "join", "target_dir", ",", "File", ".", "dirname", "(", "asset", ")", "FileUtils", ".", "mkdir_p", "asset_dir", "unless", "File", ".", "exists?", "asset_dir", "FileUtils", ".", "cp_r", "asset_path", ",", "asset_dir", "end", "end" ]
Copies the assets coming with this report to the given target directory This will copy the files and directories that have been specified for the report from the report's path (or the report's ancestors) into the target directory. @param [String] target_dir The target directory of the report @see .assets
[ "Copies", "the", "assets", "coming", "with", "this", "report", "to", "the", "given", "target", "directory" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/report.rb#L221-L230
train
koraktor/metior
lib/metior/repository.rb
Metior.Repository.actor
def actor(actor) id = self.class::Actor.id_for(actor) @actors[id] ||= self.class::Actor.new(self, actor) end
ruby
def actor(actor) id = self.class::Actor.id_for(actor) @actors[id] ||= self.class::Actor.new(self, actor) end
[ "def", "actor", "(", "actor", ")", "id", "=", "self", ".", "class", "::", "Actor", ".", "id_for", "(", "actor", ")", "@actors", "[", "id", "]", "||=", "self", ".", "class", "::", "Actor", ".", "new", "(", "self", ",", "actor", ")", "end" ]
Creates a new repository instance with the given file system path @param [String] path The file system path of the repository Returns a single VCS specific actor object from the raw data of the actor provided by the VCS implementation The actor object is either created from the given raw data or retrieved from the cache using the VCS specific unique identifier of the actor. @param [Object] actor The raw data of the actor provided by the VCS @return [Actor] A object representing the actor @see Actor.id_for
[ "Creates", "a", "new", "repository", "instance", "with", "the", "given", "file", "system", "path" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/repository.rb#L44-L47
train
koraktor/metior
lib/metior/repository.rb
Metior.Repository.commits
def commits(range = current_branch) range = parse_range range commits = cached_commits range if commits.empty? base_commit, raw_commits = load_commits(range) commits = build_commits raw_commits unless base_commit.nil? base_commit = self.class::Commit.new(self, base_commit) base_commit.add_child commits.last.id @commits[base_commit.id] = base_commit end else if range.first == '' unless commits.last.parents.empty? raw_commits = load_commits(''..commits.last.id).last commits += build_commits raw_commits[0..-2] end else if commits.first.id != range.last raw_commits = load_commits(commits.first.id..range.last).last commits = build_commits(raw_commits) + commits end unless commits.last.parents.include? range.first raw_commits = load_commits(range.first..commits.last.id).last commits += build_commits raw_commits end end end CommitCollection.new commits, range end
ruby
def commits(range = current_branch) range = parse_range range commits = cached_commits range if commits.empty? base_commit, raw_commits = load_commits(range) commits = build_commits raw_commits unless base_commit.nil? base_commit = self.class::Commit.new(self, base_commit) base_commit.add_child commits.last.id @commits[base_commit.id] = base_commit end else if range.first == '' unless commits.last.parents.empty? raw_commits = load_commits(''..commits.last.id).last commits += build_commits raw_commits[0..-2] end else if commits.first.id != range.last raw_commits = load_commits(commits.first.id..range.last).last commits = build_commits(raw_commits) + commits end unless commits.last.parents.include? range.first raw_commits = load_commits(range.first..commits.last.id).last commits += build_commits raw_commits end end end CommitCollection.new commits, range end
[ "def", "commits", "(", "range", "=", "current_branch", ")", "range", "=", "parse_range", "range", "commits", "=", "cached_commits", "range", "if", "commits", ".", "empty?", "base_commit", ",", "raw_commits", "=", "load_commits", "(", "range", ")", "commits", "=", "build_commits", "raw_commits", "unless", "base_commit", ".", "nil?", "base_commit", "=", "self", ".", "class", "::", "Commit", ".", "new", "(", "self", ",", "base_commit", ")", "base_commit", ".", "add_child", "commits", ".", "last", ".", "id", "@commits", "[", "base_commit", ".", "id", "]", "=", "base_commit", "end", "else", "if", "range", ".", "first", "==", "''", "unless", "commits", ".", "last", ".", "parents", ".", "empty?", "raw_commits", "=", "load_commits", "(", "''", "..", "commits", ".", "last", ".", "id", ")", ".", "last", "commits", "+=", "build_commits", "raw_commits", "[", "0", "..", "-", "2", "]", "end", "else", "if", "commits", ".", "first", ".", "id", "!=", "range", ".", "last", "raw_commits", "=", "load_commits", "(", "commits", ".", "first", ".", "id", "..", "range", ".", "last", ")", ".", "last", "commits", "=", "build_commits", "(", "raw_commits", ")", "+", "commits", "end", "unless", "commits", ".", "last", ".", "parents", ".", "include?", "range", ".", "first", "raw_commits", "=", "load_commits", "(", "range", ".", "first", "..", "commits", ".", "last", ".", "id", ")", ".", "last", "commits", "+=", "build_commits", "raw_commits", "end", "end", "end", "CommitCollection", ".", "new", "commits", ",", "range", "end" ]
Loads all commits including their committers and authors from the given commit range @param [String, Range] range The range of commits for which the commits should be retrieved. This may be given as a string (`'master..development'`), a range (`'master'..'development'`) or as a single ref (`'master'`). A single ref name means all commits reachable from that ref. @return [CommitCollection] All commits from the given commit range
[ "Loads", "all", "commits", "including", "their", "committers", "and", "authors", "from", "the", "given", "commit", "range" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/repository.rb#L83-L114
train
koraktor/metior
lib/metior/repository.rb
Metior.Repository.file_stats
def file_stats(range = current_branch) support! :file_stats stats = {} commits(range).each_value do |commit| commit.added_files.each do |file| stats[file] = { :modifications => 0 } unless stats.key? file stats[file][:added_date] = commit.authored_date stats[file][:modifications] += 1 end commit.modified_files.each do |file| stats[file] = { :modifications => 0 } unless stats.key? file stats[file][:last_modified_date] = commit.authored_date stats[file][:modifications] += 1 end commit.deleted_files.each do |file| stats[file] = { :modifications => 0 } unless stats.key? file stats[file][:deleted_date] = commit.authored_date end end stats end
ruby
def file_stats(range = current_branch) support! :file_stats stats = {} commits(range).each_value do |commit| commit.added_files.each do |file| stats[file] = { :modifications => 0 } unless stats.key? file stats[file][:added_date] = commit.authored_date stats[file][:modifications] += 1 end commit.modified_files.each do |file| stats[file] = { :modifications => 0 } unless stats.key? file stats[file][:last_modified_date] = commit.authored_date stats[file][:modifications] += 1 end commit.deleted_files.each do |file| stats[file] = { :modifications => 0 } unless stats.key? file stats[file][:deleted_date] = commit.authored_date end end stats end
[ "def", "file_stats", "(", "range", "=", "current_branch", ")", "support!", ":file_stats", "stats", "=", "{", "}", "commits", "(", "range", ")", ".", "each_value", "do", "|", "commit", "|", "commit", ".", "added_files", ".", "each", "do", "|", "file", "|", "stats", "[", "file", "]", "=", "{", ":modifications", "=>", "0", "}", "unless", "stats", ".", "key?", "file", "stats", "[", "file", "]", "[", ":added_date", "]", "=", "commit", ".", "authored_date", "stats", "[", "file", "]", "[", ":modifications", "]", "+=", "1", "end", "commit", ".", "modified_files", ".", "each", "do", "|", "file", "|", "stats", "[", "file", "]", "=", "{", ":modifications", "=>", "0", "}", "unless", "stats", ".", "key?", "file", "stats", "[", "file", "]", "[", ":last_modified_date", "]", "=", "commit", ".", "authored_date", "stats", "[", "file", "]", "[", ":modifications", "]", "+=", "1", "end", "commit", ".", "deleted_files", ".", "each", "do", "|", "file", "|", "stats", "[", "file", "]", "=", "{", ":modifications", "=>", "0", "}", "unless", "stats", ".", "key?", "file", "stats", "[", "file", "]", "[", ":deleted_date", "]", "=", "commit", ".", "authored_date", "end", "end", "stats", "end" ]
This evaluates basic statistics about the files in a given commit range. @example repo.file_stats => { 'a_file.rb' => { :added_date => Tue Mar 29 16:13:47 +0200 2011, :deleted_date => Sun Jun 05 12:56:18 +0200 2011, :last_modified_date => Thu Apr 21 20:08:00 +0200 2011, :modifications => 9 } } @param [String, Range] range The range of commits for which the file stats should be retrieved. This may be given as a string (`'master..development'`), a range (`'master'..'development'`) or as a single ref (`'master'`). A single ref name means all commits reachable from that ref. @return [Hash<String, Hash<Symbol, Object>>] Each file is returned as a key in this hash. The value of this key is another hash containing the stats for this file. Depending on the state of the file this includes `:added_date`, `:last_modified_date`, `:last_modified_date` and `'master..development'`. @see Commit#added_files @see Commit#deleted_files @see Commit#modified_files
[ "This", "evaluates", "basic", "statistics", "about", "the", "files", "in", "a", "given", "commit", "range", "." ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/repository.rb#L179-L201
train
koraktor/metior
lib/metior/repository.rb
Metior.Repository.build_commits
def build_commits(raw_commits) child_commit_id = nil raw_commits.map do |commit| commit = self.class::Commit.new(self, commit) commit.add_child child_commit_id unless child_commit_id.nil? child_commit_id = commit.id @commits[commit.id] = commit commit end end
ruby
def build_commits(raw_commits) child_commit_id = nil raw_commits.map do |commit| commit = self.class::Commit.new(self, commit) commit.add_child child_commit_id unless child_commit_id.nil? child_commit_id = commit.id @commits[commit.id] = commit commit end end
[ "def", "build_commits", "(", "raw_commits", ")", "child_commit_id", "=", "nil", "raw_commits", ".", "map", "do", "|", "commit", "|", "commit", "=", "self", ".", "class", "::", "Commit", ".", "new", "(", "self", ",", "commit", ")", "commit", ".", "add_child", "child_commit_id", "unless", "child_commit_id", ".", "nil?", "child_commit_id", "=", "commit", ".", "id", "@commits", "[", "commit", ".", "id", "]", "=", "commit", "commit", "end", "end" ]
Builds VCS specific commit objects for each given commit's raw data that is provided by the VCS implementation The raw data will be transformed into commit objects that will also be saved into the commit cache. Authors and committers of the given commits will be created and stored into the cache or loaded from the cache if they already exist. Additionally this method will establish an association between the commits and their children. @param [Array<Object>] raw_commits The commits' raw data provided by the VCS implementation @return [Array<Commit>] The commit objects representing the given commits @see Commit @see Commit#add_child
[ "Builds", "VCS", "specific", "commit", "objects", "for", "each", "given", "commit", "s", "raw", "data", "that", "is", "provided", "by", "the", "VCS", "implementation" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/repository.rb#L344-L353
train
koraktor/metior
lib/metior/repository.rb
Metior.Repository.cached_commits
def cached_commits(range) commits = [] direction = nil if @commits.key? range.last current_commits = [@commits[range.last]] direction = :parents elsif @commits.key? range.first current_commits = [@commits[range.first]] direction = :children end unless direction.nil? while !current_commits.empty? do new_commits = [] current_commits.each do |commit| new_commits += commit.send direction commits << commit if commit.id != range.first if direction == :parents && new_commits.include?(range.first) new_commits = [] break end end unless new_commits.include? range.first current_commits = new_commits.uniq.map do |commit| commit = @commits[commit] commits.include?(commit) ? nil : commit end.compact end end end commits.sort_by { |c| c.committed_date }.reverse end
ruby
def cached_commits(range) commits = [] direction = nil if @commits.key? range.last current_commits = [@commits[range.last]] direction = :parents elsif @commits.key? range.first current_commits = [@commits[range.first]] direction = :children end unless direction.nil? while !current_commits.empty? do new_commits = [] current_commits.each do |commit| new_commits += commit.send direction commits << commit if commit.id != range.first if direction == :parents && new_commits.include?(range.first) new_commits = [] break end end unless new_commits.include? range.first current_commits = new_commits.uniq.map do |commit| commit = @commits[commit] commits.include?(commit) ? nil : commit end.compact end end end commits.sort_by { |c| c.committed_date }.reverse end
[ "def", "cached_commits", "(", "range", ")", "commits", "=", "[", "]", "direction", "=", "nil", "if", "@commits", ".", "key?", "range", ".", "last", "current_commits", "=", "[", "@commits", "[", "range", ".", "last", "]", "]", "direction", "=", ":parents", "elsif", "@commits", ".", "key?", "range", ".", "first", "current_commits", "=", "[", "@commits", "[", "range", ".", "first", "]", "]", "direction", "=", ":children", "end", "unless", "direction", ".", "nil?", "while", "!", "current_commits", ".", "empty?", "do", "new_commits", "=", "[", "]", "current_commits", ".", "each", "do", "|", "commit", "|", "new_commits", "+=", "commit", ".", "send", "direction", "commits", "<<", "commit", "if", "commit", ".", "id", "!=", "range", ".", "first", "if", "direction", "==", ":parents", "&&", "new_commits", ".", "include?", "(", "range", ".", "first", ")", "new_commits", "=", "[", "]", "break", "end", "end", "unless", "new_commits", ".", "include?", "range", ".", "first", "current_commits", "=", "new_commits", ".", "uniq", ".", "map", "do", "|", "commit", "|", "commit", "=", "@commits", "[", "commit", "]", "commits", ".", "include?", "(", "commit", ")", "?", "nil", ":", "commit", "end", ".", "compact", "end", "end", "end", "commits", ".", "sort_by", "{", "|", "c", "|", "c", ".", "committed_date", "}", ".", "reverse", "end" ]
Tries to retrieve as many commits as possible in the given commit range from the commit cache This method calls itself recursively to walk the given commit range either from the start to the end or vice versa depending on which commit could be found in the cache. @param [Range] range The range of commits which should be retrieved from the cache. This may be given a range of commit IDs (`'master'..'development'`). @return [Array<Commit>] A list of commit objects that could be retrieved from the cache @see Commit#children
[ "Tries", "to", "retrieve", "as", "many", "commits", "as", "possible", "in", "the", "given", "commit", "range", "from", "the", "commit", "cache" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/repository.rb#L368-L401
train
koraktor/metior
lib/metior/repository.rb
Metior.Repository.parse_range
def parse_range(range) unless range.is_a? Range range = range.to_s.split '..' range = ((range.size == 1) ? '' : range.first)..range.last end range = id_for_ref(range.first)..range.last if range.first != '' range.first..id_for_ref(range.last) end
ruby
def parse_range(range) unless range.is_a? Range range = range.to_s.split '..' range = ((range.size == 1) ? '' : range.first)..range.last end range = id_for_ref(range.first)..range.last if range.first != '' range.first..id_for_ref(range.last) end
[ "def", "parse_range", "(", "range", ")", "unless", "range", ".", "is_a?", "Range", "range", "=", "range", ".", "to_s", ".", "split", "'..'", "range", "=", "(", "(", "range", ".", "size", "==", "1", ")", "?", "''", ":", "range", ".", "first", ")", "..", "range", ".", "last", "end", "range", "=", "id_for_ref", "(", "range", ".", "first", ")", "..", "range", ".", "last", "if", "range", ".", "first", "!=", "''", "range", ".", "first", "..", "id_for_ref", "(", "range", ".", "last", ")", "end" ]
Parses a string or range of commit IDs or ref names into the coresponding range of unique commit IDs @param [String, Range] range The string that should be parsed for a range or an existing range @return [Range] The range of commit IDs parsed from the given parameter @see #id_for_ref
[ "Parses", "a", "string", "or", "range", "of", "commit", "IDs", "or", "ref", "names", "into", "the", "coresponding", "range", "of", "unique", "commit", "IDs" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/repository.rb#L457-L465
train
koraktor/metior
lib/metior/adapter.rb
Metior::Adapter.ClassMethods.register_for
def register_for(vcs) vcs = Metior.find_vcs vcs vcs.register_adapter id, self class_variable_set :@@vcs, vcs end
ruby
def register_for(vcs) vcs = Metior.find_vcs vcs vcs.register_adapter id, self class_variable_set :@@vcs, vcs end
[ "def", "register_for", "(", "vcs", ")", "vcs", "=", "Metior", ".", "find_vcs", "vcs", "vcs", ".", "register_adapter", "id", ",", "self", "class_variable_set", ":@@vcs", ",", "vcs", "end" ]
Registers this adapter with a VCS @param [Symbol] vcs_name The name of the VCS to register this adapter with
[ "Registers", "this", "adapter", "with", "a", "VCS" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter.rb#L56-L60
train
jrochkind/bento_search
app/models/bento_search/openurl_creator.rb
BentoSearch.OpenurlCreator.ensure_no_tags
def ensure_no_tags(str) return str unless str.html_safe? str = str.to_str # get it out of HTMLSafeBuffer, which messes things up str = strip_tags(str) str = HTMLEntities.new.decode(str) return str end
ruby
def ensure_no_tags(str) return str unless str.html_safe? str = str.to_str # get it out of HTMLSafeBuffer, which messes things up str = strip_tags(str) str = HTMLEntities.new.decode(str) return str end
[ "def", "ensure_no_tags", "(", "str", ")", "return", "str", "unless", "str", ".", "html_safe?", "str", "=", "str", ".", "to_str", "str", "=", "strip_tags", "(", "str", ")", "str", "=", "HTMLEntities", ".", "new", ".", "decode", "(", "str", ")", "return", "str", "end" ]
If the input is not marked html_safe?, just return it. Otherwise strip html tags from it AND replace HTML char entities
[ "If", "the", "input", "is", "not", "marked", "html_safe?", "just", "return", "it", ".", "Otherwise", "strip", "html", "tags", "from", "it", "AND", "replace", "HTML", "char", "entities" ]
f567ead386d4a2e283c03b787e7c0d620567c9de
https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/models/bento_search/openurl_creator.rb#L156-L165
train
pcorliss/ruby_route_53
lib/route53/dns_record.rb
Route53.DNSRecord.update
def update(name,type,ttl,values,comment=nil, zone_apex = nil) prev = self.clone @name = name unless name.nil? @type = type unless type.nil? @ttl = ttl unless ttl.nil? @values = values unless values.nil? @zone_apex = zone_apex unless zone_apex.nil? @zone.perform_actions([ {:action => "DELETE", :record => prev}, {:action => "CREATE", :record => self}, ],comment) end
ruby
def update(name,type,ttl,values,comment=nil, zone_apex = nil) prev = self.clone @name = name unless name.nil? @type = type unless type.nil? @ttl = ttl unless ttl.nil? @values = values unless values.nil? @zone_apex = zone_apex unless zone_apex.nil? @zone.perform_actions([ {:action => "DELETE", :record => prev}, {:action => "CREATE", :record => self}, ],comment) end
[ "def", "update", "(", "name", ",", "type", ",", "ttl", ",", "values", ",", "comment", "=", "nil", ",", "zone_apex", "=", "nil", ")", "prev", "=", "self", ".", "clone", "@name", "=", "name", "unless", "name", ".", "nil?", "@type", "=", "type", "unless", "type", ".", "nil?", "@ttl", "=", "ttl", "unless", "ttl", ".", "nil?", "@values", "=", "values", "unless", "values", ".", "nil?", "@zone_apex", "=", "zone_apex", "unless", "zone_apex", ".", "nil?", "@zone", ".", "perform_actions", "(", "[", "{", ":action", "=>", "\"DELETE\"", ",", ":record", "=>", "prev", "}", ",", "{", ":action", "=>", "\"CREATE\"", ",", ":record", "=>", "self", "}", ",", "]", ",", "comment", ")", "end" ]
Need to modify to a param hash
[ "Need", "to", "modify", "to", "a", "param", "hash" ]
f96fab52931f069ba4b5fddb291aa53c7412aa52
https://github.com/pcorliss/ruby_route_53/blob/f96fab52931f069ba4b5fddb291aa53c7412aa52/lib/route53/dns_record.rb#L66-L77
train
pcorliss/ruby_route_53
lib/route53/dns_record.rb
Route53.DNSRecord.update_dirty
def update_dirty(name,type,ttl,values,zone_apex = nil) prev = self.clone @name = name unless name.nil? @type = type unless type.nil? @ttl = ttl unless ttl.nil? @values = values unless values.nil? @zone_apex = zone_apex unless zone_apex.nil? return [{:action => "DELETE", :record => prev}, {:action => "CREATE", :record => self}] end
ruby
def update_dirty(name,type,ttl,values,zone_apex = nil) prev = self.clone @name = name unless name.nil? @type = type unless type.nil? @ttl = ttl unless ttl.nil? @values = values unless values.nil? @zone_apex = zone_apex unless zone_apex.nil? return [{:action => "DELETE", :record => prev}, {:action => "CREATE", :record => self}] end
[ "def", "update_dirty", "(", "name", ",", "type", ",", "ttl", ",", "values", ",", "zone_apex", "=", "nil", ")", "prev", "=", "self", ".", "clone", "@name", "=", "name", "unless", "name", ".", "nil?", "@type", "=", "type", "unless", "type", ".", "nil?", "@ttl", "=", "ttl", "unless", "ttl", ".", "nil?", "@values", "=", "values", "unless", "values", ".", "nil?", "@zone_apex", "=", "zone_apex", "unless", "zone_apex", ".", "nil?", "return", "[", "{", ":action", "=>", "\"DELETE\"", ",", ":record", "=>", "prev", "}", ",", "{", ":action", "=>", "\"CREATE\"", ",", ":record", "=>", "self", "}", "]", "end" ]
Returns the raw array so the developer can update large batches manually Need to modify to a param hash
[ "Returns", "the", "raw", "array", "so", "the", "developer", "can", "update", "large", "batches", "manually", "Need", "to", "modify", "to", "a", "param", "hash" ]
f96fab52931f069ba4b5fddb291aa53c7412aa52
https://github.com/pcorliss/ruby_route_53/blob/f96fab52931f069ba4b5fddb291aa53c7412aa52/lib/route53/dns_record.rb#L81-L90
train
koraktor/metior
lib/metior/collections/actor_collection.rb
Metior.ActorCollection.most_significant
def most_significant(count = 3) support! :line_stats authors = ActorCollection.new sort_by { |author| -author.modifications }.each do |author| authors << author break if authors.size == count end authors end
ruby
def most_significant(count = 3) support! :line_stats authors = ActorCollection.new sort_by { |author| -author.modifications }.each do |author| authors << author break if authors.size == count end authors end
[ "def", "most_significant", "(", "count", "=", "3", ")", "support!", ":line_stats", "authors", "=", "ActorCollection", ".", "new", "sort_by", "{", "|", "author", "|", "-", "author", ".", "modifications", "}", ".", "each", "do", "|", "author", "|", "authors", "<<", "author", "break", "if", "authors", ".", "size", "==", "count", "end", "authors", "end" ]
Returns up to the given number of actors in this collection with the biggest impact on the repository, i.e. changing the most code @param [Numeric] count The number of actors to return @return [ActorCollection] The given number of actors ordered by impact @see Actor#modifications
[ "Returns", "up", "to", "the", "given", "number", "of", "actors", "in", "this", "collection", "with", "the", "biggest", "impact", "on", "the", "repository", "i", ".", "e", ".", "changing", "the", "most", "code" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/actor_collection.rb#L47-L56
train
koraktor/metior
lib/metior/collections/actor_collection.rb
Metior.ActorCollection.top
def top(count = 3) authors = ActorCollection.new sort_by { |author| -author.authored_commits.size }.each do |author| authors << author break if authors.size == count end authors end
ruby
def top(count = 3) authors = ActorCollection.new sort_by { |author| -author.authored_commits.size }.each do |author| authors << author break if authors.size == count end authors end
[ "def", "top", "(", "count", "=", "3", ")", "authors", "=", "ActorCollection", ".", "new", "sort_by", "{", "|", "author", "|", "-", "author", ".", "authored_commits", ".", "size", "}", ".", "each", "do", "|", "author", "|", "authors", "<<", "author", "break", "if", "authors", ".", "size", "==", "count", "end", "authors", "end" ]
Returns up to the given number of actors in this collection with the most commits @param [Numeric] count The number of actors to return @return [ActorCollection] The given number of actors ordered by commit count @see Actor#commits
[ "Returns", "up", "to", "the", "given", "number", "of", "actors", "in", "this", "collection", "with", "the", "most", "commits" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/actor_collection.rb#L65-L72
train
koraktor/metior
lib/metior/collections/actor_collection.rb
Metior.ActorCollection.load_commits
def load_commits(commit_type, actor_id = nil) commits = CommitCollection.new if actor_id.nil? each { |actor| commits.merge! actor.send(commit_type) } elsif key? actor_id commits = self[actor_id].send commit_type end commits end
ruby
def load_commits(commit_type, actor_id = nil) commits = CommitCollection.new if actor_id.nil? each { |actor| commits.merge! actor.send(commit_type) } elsif key? actor_id commits = self[actor_id].send commit_type end commits end
[ "def", "load_commits", "(", "commit_type", ",", "actor_id", "=", "nil", ")", "commits", "=", "CommitCollection", ".", "new", "if", "actor_id", ".", "nil?", "each", "{", "|", "actor", "|", "commits", ".", "merge!", "actor", ".", "send", "(", "commit_type", ")", "}", "elsif", "key?", "actor_id", "commits", "=", "self", "[", "actor_id", "]", ".", "send", "commit_type", "end", "commits", "end" ]
Loads the commits authored or committed by all actors in this collection or a specific actor @param [:authored_commits, :committed_commits] commit_type The type of commits to load @param [Object] actor_id The ID of the actor, if only the commits of a specific actor should be returned @return [CommitCollection] All commits authored or committed by the actors in this collection or by a specific actor
[ "Loads", "the", "commits", "authored", "or", "committed", "by", "all", "actors", "in", "this", "collection", "or", "a", "specific", "actor" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/actor_collection.rb#L85-L93
train
koraktor/metior
lib/metior/adapter/octokit/repository.rb
Metior::Adapter::Octokit.Repository.load_commits
def load_commits(range) base_commit = nil commits = [] last_commit = nil loop do new_commits = ::Octokit.commits(@path, nil, :last_sha => last_commit, :per_page => 100, :top => range.last) break if new_commits.empty? base_commit_index = new_commits.find_index do |commit| commit.sha == range.first end unless range.first == '' unless base_commit_index.nil? if base_commit_index > 0 commits += new_commits[0..base_commit_index-1] end base_commit = new_commits[base_commit_index] break end commits += new_commits last_commit = new_commits.last.sha end [base_commit, commits] end
ruby
def load_commits(range) base_commit = nil commits = [] last_commit = nil loop do new_commits = ::Octokit.commits(@path, nil, :last_sha => last_commit, :per_page => 100, :top => range.last) break if new_commits.empty? base_commit_index = new_commits.find_index do |commit| commit.sha == range.first end unless range.first == '' unless base_commit_index.nil? if base_commit_index > 0 commits += new_commits[0..base_commit_index-1] end base_commit = new_commits[base_commit_index] break end commits += new_commits last_commit = new_commits.last.sha end [base_commit, commits] end
[ "def", "load_commits", "(", "range", ")", "base_commit", "=", "nil", "commits", "=", "[", "]", "last_commit", "=", "nil", "loop", "do", "new_commits", "=", "::", "Octokit", ".", "commits", "(", "@path", ",", "nil", ",", ":last_sha", "=>", "last_commit", ",", ":per_page", "=>", "100", ",", ":top", "=>", "range", ".", "last", ")", "break", "if", "new_commits", ".", "empty?", "base_commit_index", "=", "new_commits", ".", "find_index", "do", "|", "commit", "|", "commit", ".", "sha", "==", "range", ".", "first", "end", "unless", "range", ".", "first", "==", "''", "unless", "base_commit_index", ".", "nil?", "if", "base_commit_index", ">", "0", "commits", "+=", "new_commits", "[", "0", "..", "base_commit_index", "-", "1", "]", "end", "base_commit", "=", "new_commits", "[", "base_commit_index", "]", "break", "end", "commits", "+=", "new_commits", "last_commit", "=", "new_commits", ".", "last", ".", "sha", "end", "[", "base_commit", ",", "commits", "]", "end" ]
This method uses Octokit to load all commits from the given commit range @note GitHub API is currently limited to 60 calls a minute, so you won't be able to query branches with more than 2100 commits (35 commits per call). @param [String, Range] range The range of commits for which the commits should be loaded. This may be given as a string (`'master..development'`), a range (`'master'..'development'`) or as a single ref (`'master'`). A single ref name means all commits reachable from that ref. @return [Hashie::Mash, nil] The base commit of the requested range or `nil` if the the range starts at the beginning of the history @return [Array<Hashie::Mash>] All commits in the given commit range @see Octokit::Commits#commits
[ "This", "method", "uses", "Octokit", "to", "load", "all", "commits", "from", "the", "given", "commit", "range" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/octokit/repository.rb#L85-L108
train
danieldreier/autosign
lib/autosign/validator.rb
Autosign.Validator.validate
def validate(challenge_password, certname, raw_csr) @log.debug "running validate" fail unless challenge_password.is_a?(String) fail unless certname.is_a?(String) case perform_validation(challenge_password, certname, raw_csr) when true @log.debug "validated successfully" @log.info "Validated '#{certname}' using '#{name}' validator" return true when false @log.debug "validation failed" @log.debug "Unable to validate '#{certname}' using '#{name}' validator" return false else @log.error "perform_validation returned a non-boolean result" raise "perform_validation returned a non-boolean result" end end
ruby
def validate(challenge_password, certname, raw_csr) @log.debug "running validate" fail unless challenge_password.is_a?(String) fail unless certname.is_a?(String) case perform_validation(challenge_password, certname, raw_csr) when true @log.debug "validated successfully" @log.info "Validated '#{certname}' using '#{name}' validator" return true when false @log.debug "validation failed" @log.debug "Unable to validate '#{certname}' using '#{name}' validator" return false else @log.error "perform_validation returned a non-boolean result" raise "perform_validation returned a non-boolean result" end end
[ "def", "validate", "(", "challenge_password", ",", "certname", ",", "raw_csr", ")", "@log", ".", "debug", "\"running validate\"", "fail", "unless", "challenge_password", ".", "is_a?", "(", "String", ")", "fail", "unless", "certname", ".", "is_a?", "(", "String", ")", "case", "perform_validation", "(", "challenge_password", ",", "certname", ",", "raw_csr", ")", "when", "true", "@log", ".", "debug", "\"validated successfully\"", "@log", ".", "info", "\"Validated '#{certname}' using '#{name}' validator\"", "return", "true", "when", "false", "@log", ".", "debug", "\"validation failed\"", "@log", ".", "debug", "\"Unable to validate '#{certname}' using '#{name}' validator\"", "return", "false", "else", "@log", ".", "error", "\"perform_validation returned a non-boolean result\"", "raise", "\"perform_validation returned a non-boolean result\"", "end", "end" ]
wrapper method that wraps input validation and logging around the perform_validation method. Do not override or use this class in child classes. This is the class that gets called on validator objects.
[ "wrapper", "method", "that", "wraps", "input", "validation", "and", "logging", "around", "the", "perform_validation", "method", ".", "Do", "not", "override", "or", "use", "this", "class", "in", "child", "classes", ".", "This", "is", "the", "class", "that", "gets", "called", "on", "validator", "objects", "." ]
d457eeec5b2084ff63ee4555f7de97cf87be1aca
https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/validator.rb#L68-L86
train
danieldreier/autosign
lib/autosign/validator.rb
Autosign.Validator.settings
def settings @log.debug "merging settings" setting_sources = [get_override_settings, load_config, default_settings] merged_settings = setting_sources.inject({}) { |merged, hash| merged.deep_merge(hash) } @log.debug "using merged settings: " + merged_settings.to_s @log.debug "validating merged settings" if validate_settings(merged_settings) @log.debug "successfully validated merged settings" return merged_settings else @log.warn "validation of merged settings failed" @log.warn "unable to validate settings in #{self.name} validator" raise "settings validation error" end end
ruby
def settings @log.debug "merging settings" setting_sources = [get_override_settings, load_config, default_settings] merged_settings = setting_sources.inject({}) { |merged, hash| merged.deep_merge(hash) } @log.debug "using merged settings: " + merged_settings.to_s @log.debug "validating merged settings" if validate_settings(merged_settings) @log.debug "successfully validated merged settings" return merged_settings else @log.warn "validation of merged settings failed" @log.warn "unable to validate settings in #{self.name} validator" raise "settings validation error" end end
[ "def", "settings", "@log", ".", "debug", "\"merging settings\"", "setting_sources", "=", "[", "get_override_settings", ",", "load_config", ",", "default_settings", "]", "merged_settings", "=", "setting_sources", ".", "inject", "(", "{", "}", ")", "{", "|", "merged", ",", "hash", "|", "merged", ".", "deep_merge", "(", "hash", ")", "}", "@log", ".", "debug", "\"using merged settings: \"", "+", "merged_settings", ".", "to_s", "@log", ".", "debug", "\"validating merged settings\"", "if", "validate_settings", "(", "merged_settings", ")", "@log", ".", "debug", "\"successfully validated merged settings\"", "return", "merged_settings", "else", "@log", ".", "warn", "\"validation of merged settings failed\"", "@log", ".", "warn", "\"unable to validate settings in #{self.name} validator\"", "raise", "\"settings validation error\"", "end", "end" ]
provide a merged settings hash of default settings for a validator, config file settings for the validator, and override settings defined in the validator. Do not override this in child classes. If you need to set custom config settings, override the get_override_settings method. The section of the config file this reads from is the same as the name method returns. @return [Hash] of config settings
[ "provide", "a", "merged", "settings", "hash", "of", "default", "settings", "for", "a", "validator", "config", "file", "settings", "for", "the", "validator", "and", "override", "settings", "defined", "in", "the", "validator", "." ]
d457eeec5b2084ff63ee4555f7de97cf87be1aca
https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/validator.rb#L153-L167
train
danieldreier/autosign
lib/autosign/validator.rb
Autosign.Validator.load_config
def load_config @log.debug "loading validator-specific configuration" config = Autosign::Config.new if config.settings.to_hash[self.name].nil? @log.warn "Unable to load validator-specific configuration" @log.warn "Cannot load configuration section named '#{self.name}'" return {} else @log.debug "Set validator-specific settings from config file: " + config.settings.to_hash[self.name].to_s return config.settings.to_hash[self.name] end end
ruby
def load_config @log.debug "loading validator-specific configuration" config = Autosign::Config.new if config.settings.to_hash[self.name].nil? @log.warn "Unable to load validator-specific configuration" @log.warn "Cannot load configuration section named '#{self.name}'" return {} else @log.debug "Set validator-specific settings from config file: " + config.settings.to_hash[self.name].to_s return config.settings.to_hash[self.name] end end
[ "def", "load_config", "@log", ".", "debug", "\"loading validator-specific configuration\"", "config", "=", "Autosign", "::", "Config", ".", "new", "if", "config", ".", "settings", ".", "to_hash", "[", "self", ".", "name", "]", ".", "nil?", "@log", ".", "warn", "\"Unable to load validator-specific configuration\"", "@log", ".", "warn", "\"Cannot load configuration section named '#{self.name}'\"", "return", "{", "}", "else", "@log", ".", "debug", "\"Set validator-specific settings from config file: \"", "+", "config", ".", "settings", ".", "to_hash", "[", "self", ".", "name", "]", ".", "to_s", "return", "config", ".", "settings", ".", "to_hash", "[", "self", ".", "name", "]", "end", "end" ]
load any required configuration from the config file. Do not override this in child classes. @return [Hash] configuration settings from the validator's section of the config file
[ "load", "any", "required", "configuration", "from", "the", "config", "file", ".", "Do", "not", "override", "this", "in", "child", "classes", "." ]
d457eeec5b2084ff63ee4555f7de97cf87be1aca
https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/validator.rb#L193-L205
train
jrochkind/bento_search
app/models/bento_search/search_engine.rb
BentoSearch.SearchEngine.fill_in_search_metadata_for
def fill_in_search_metadata_for(results, normalized_arguments = {}) results.search_args = normalized_arguments results.start = normalized_arguments[:start] || 0 results.per_page = normalized_arguments[:per_page] results.engine_id = configuration.id results.display_configuration = configuration.for_display # We copy some configuraton info over to each Item, as a convenience # to display logic that may have decide what to do given only an item, # and may want to parameterize based on configuration. results.each do |item| item.engine_id = configuration.id item.decorator = configuration.lookup!("for_display.decorator") item.display_configuration = configuration.for_display end results end
ruby
def fill_in_search_metadata_for(results, normalized_arguments = {}) results.search_args = normalized_arguments results.start = normalized_arguments[:start] || 0 results.per_page = normalized_arguments[:per_page] results.engine_id = configuration.id results.display_configuration = configuration.for_display # We copy some configuraton info over to each Item, as a convenience # to display logic that may have decide what to do given only an item, # and may want to parameterize based on configuration. results.each do |item| item.engine_id = configuration.id item.decorator = configuration.lookup!("for_display.decorator") item.display_configuration = configuration.for_display end results end
[ "def", "fill_in_search_metadata_for", "(", "results", ",", "normalized_arguments", "=", "{", "}", ")", "results", ".", "search_args", "=", "normalized_arguments", "results", ".", "start", "=", "normalized_arguments", "[", ":start", "]", "||", "0", "results", ".", "per_page", "=", "normalized_arguments", "[", ":per_page", "]", "results", ".", "engine_id", "=", "configuration", ".", "id", "results", ".", "display_configuration", "=", "configuration", ".", "for_display", "results", ".", "each", "do", "|", "item", "|", "item", ".", "engine_id", "=", "configuration", ".", "id", "item", ".", "decorator", "=", "configuration", ".", "lookup!", "(", "\"for_display.decorator\"", ")", "item", ".", "display_configuration", "=", "configuration", ".", "for_display", "end", "results", "end" ]
SOME of the elements of Results to be returned that SearchEngine implementation fills in automatically post-search. Extracted into a method for DRY in error handling to try to fill these in even in errors. Also can be used as public method for de-serialized or mock results.
[ "SOME", "of", "the", "elements", "of", "Results", "to", "be", "returned", "that", "SearchEngine", "implementation", "fills", "in", "automatically", "post", "-", "search", ".", "Extracted", "into", "a", "method", "for", "DRY", "in", "error", "handling", "to", "try", "to", "fill", "these", "in", "even", "in", "errors", ".", "Also", "can", "be", "used", "as", "public", "method", "for", "de", "-", "serialized", "or", "mock", "results", "." ]
f567ead386d4a2e283c03b787e7c0d620567c9de
https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/models/bento_search/search_engine.rb#L300-L318
train
healthfinch/allscripts-unity-client
lib/allscripts_unity_client/json_unity_request.rb
AllscriptsUnityClient.JSONUnityRequest.to_hash
def to_hash action = @parameters[:action] userid = @parameters[:userid] appname = @parameters[:appname] || @appname patientid = @parameters[:patientid] token = @parameters[:token] || @security_token parameter1 = process_date(@parameters[:parameter1]) || '' parameter2 = process_date(@parameters[:parameter2]) || '' parameter3 = process_date(@parameters[:parameter3]) || '' parameter4 = process_date(@parameters[:parameter4]) || '' parameter5 = process_date(@parameters[:parameter5]) || '' parameter6 = process_date(@parameters[:parameter6]) || '' data = Utilities::encode_data(@parameters[:data]) || '' { 'Action' => action, 'AppUserID' => userid, 'Appname' => appname, 'PatientID' => patientid, 'Token' => token, 'Parameter1' => parameter1, 'Parameter2' => parameter2, 'Parameter3' => parameter3, 'Parameter4' => parameter4, 'Parameter5' => parameter5, 'Parameter6' => parameter6, 'Data' => data } end
ruby
def to_hash action = @parameters[:action] userid = @parameters[:userid] appname = @parameters[:appname] || @appname patientid = @parameters[:patientid] token = @parameters[:token] || @security_token parameter1 = process_date(@parameters[:parameter1]) || '' parameter2 = process_date(@parameters[:parameter2]) || '' parameter3 = process_date(@parameters[:parameter3]) || '' parameter4 = process_date(@parameters[:parameter4]) || '' parameter5 = process_date(@parameters[:parameter5]) || '' parameter6 = process_date(@parameters[:parameter6]) || '' data = Utilities::encode_data(@parameters[:data]) || '' { 'Action' => action, 'AppUserID' => userid, 'Appname' => appname, 'PatientID' => patientid, 'Token' => token, 'Parameter1' => parameter1, 'Parameter2' => parameter2, 'Parameter3' => parameter3, 'Parameter4' => parameter4, 'Parameter5' => parameter5, 'Parameter6' => parameter6, 'Data' => data } end
[ "def", "to_hash", "action", "=", "@parameters", "[", ":action", "]", "userid", "=", "@parameters", "[", ":userid", "]", "appname", "=", "@parameters", "[", ":appname", "]", "||", "@appname", "patientid", "=", "@parameters", "[", ":patientid", "]", "token", "=", "@parameters", "[", ":token", "]", "||", "@security_token", "parameter1", "=", "process_date", "(", "@parameters", "[", ":parameter1", "]", ")", "||", "''", "parameter2", "=", "process_date", "(", "@parameters", "[", ":parameter2", "]", ")", "||", "''", "parameter3", "=", "process_date", "(", "@parameters", "[", ":parameter3", "]", ")", "||", "''", "parameter4", "=", "process_date", "(", "@parameters", "[", ":parameter4", "]", ")", "||", "''", "parameter5", "=", "process_date", "(", "@parameters", "[", ":parameter5", "]", ")", "||", "''", "parameter6", "=", "process_date", "(", "@parameters", "[", ":parameter6", "]", ")", "||", "''", "data", "=", "Utilities", "::", "encode_data", "(", "@parameters", "[", ":data", "]", ")", "||", "''", "{", "'Action'", "=>", "action", ",", "'AppUserID'", "=>", "userid", ",", "'Appname'", "=>", "appname", ",", "'PatientID'", "=>", "patientid", ",", "'Token'", "=>", "token", ",", "'Parameter1'", "=>", "parameter1", ",", "'Parameter2'", "=>", "parameter2", ",", "'Parameter3'", "=>", "parameter3", ",", "'Parameter4'", "=>", "parameter4", ",", "'Parameter5'", "=>", "parameter5", ",", "'Parameter6'", "=>", "parameter6", ",", "'Data'", "=>", "data", "}", "end" ]
Convert the parameters to a Hash for Faraday with all possible dates converted to the Organization's localtime.
[ "Convert", "the", "parameters", "to", "a", "Hash", "for", "Faraday", "with", "all", "possible", "dates", "converted", "to", "the", "Organization", "s", "localtime", "." ]
fd9b7148cb6fe806a3f9dba70c138ba8c5e75985
https://github.com/healthfinch/allscripts-unity-client/blob/fd9b7148cb6fe806a3f9dba70c138ba8c5e75985/lib/allscripts_unity_client/json_unity_request.rb#L8-L36
train
healthfinch/allscripts-unity-client
lib/allscripts_unity_client/client.rb
AllscriptsUnityClient.Client.get_encounter_list
def get_encounter_list( userid, patientid, encounter_type = nil, when_param = nil, nostradamus = 0, show_past_flag = true, billing_provider_user_name = nil, show_all = false) magic_parameters = { action: 'GetEncounterList', userid: userid, patientid: patientid, parameter1: encounter_type, parameter2: when_param, parameter3: nostradamus, parameter4: unity_boolean_parameter(show_past_flag), parameter5: billing_provider_user_name, # According to the developer guide this parameter is no longer # used. parameter6: show_all ? 'all' : nil } response = magic(magic_parameters) unless response.is_a?(Array) response = [ response ] end # Remove nil encounters response.delete_if do |value| value[:id] == '0' && value[:patientid] == '0' end end
ruby
def get_encounter_list( userid, patientid, encounter_type = nil, when_param = nil, nostradamus = 0, show_past_flag = true, billing_provider_user_name = nil, show_all = false) magic_parameters = { action: 'GetEncounterList', userid: userid, patientid: patientid, parameter1: encounter_type, parameter2: when_param, parameter3: nostradamus, parameter4: unity_boolean_parameter(show_past_flag), parameter5: billing_provider_user_name, # According to the developer guide this parameter is no longer # used. parameter6: show_all ? 'all' : nil } response = magic(magic_parameters) unless response.is_a?(Array) response = [ response ] end # Remove nil encounters response.delete_if do |value| value[:id] == '0' && value[:patientid] == '0' end end
[ "def", "get_encounter_list", "(", "userid", ",", "patientid", ",", "encounter_type", "=", "nil", ",", "when_param", "=", "nil", ",", "nostradamus", "=", "0", ",", "show_past_flag", "=", "true", ",", "billing_provider_user_name", "=", "nil", ",", "show_all", "=", "false", ")", "magic_parameters", "=", "{", "action", ":", "'GetEncounterList'", ",", "userid", ":", "userid", ",", "patientid", ":", "patientid", ",", "parameter1", ":", "encounter_type", ",", "parameter2", ":", "when_param", ",", "parameter3", ":", "nostradamus", ",", "parameter4", ":", "unity_boolean_parameter", "(", "show_past_flag", ")", ",", "parameter5", ":", "billing_provider_user_name", ",", "parameter6", ":", "show_all", "?", "'all'", ":", "nil", "}", "response", "=", "magic", "(", "magic_parameters", ")", "unless", "response", ".", "is_a?", "(", "Array", ")", "response", "=", "[", "response", "]", "end", "response", ".", "delete_if", "do", "|", "value", "|", "value", "[", ":id", "]", "==", "'0'", "&&", "value", "[", ":patientid", "]", "==", "'0'", "end", "end" ]
GetEncounterList helper method. @param [Object] userid @param [Object] patientid @param [String, nil] encounter_type encounter type to filter on. A value of `nil` filters nothing. Defaults to `nil`. @param [Object] when_param @param [Fixnum, nil] nostradamus how many days to look into the future. Defaults to `0`. @param [Object] show_past_flag whether to show previous encounters. All truthy values aside from the string `"N"` are considered to be true (or `"Y"`) all other values are considered to be false (or `"N"`). Defaults to `true`. @param [Object] billing_provider_user_name filter by user name. Defaults to `nil`. @param [Object] show_all @return [Array<Hash>] the filtered encounter list.
[ "GetEncounterList", "helper", "method", "." ]
fd9b7148cb6fe806a3f9dba70c138ba8c5e75985
https://github.com/healthfinch/allscripts-unity-client/blob/fd9b7148cb6fe806a3f9dba70c138ba8c5e75985/lib/allscripts_unity_client/client.rb#L233-L266
train