repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
guard/rb-inotify
lib/rb-inotify/notifier.rb
INotify.Notifier.process
def process read_events.each do |event| event.callback! event.flags.include?(:ignored) && event.notifier.watchers.delete(event.watcher_id) end end
ruby
def process read_events.each do |event| event.callback! event.flags.include?(:ignored) && event.notifier.watchers.delete(event.watcher_id) end end
[ "def", "process", "read_events", ".", "each", "do", "|", "event", "|", "event", ".", "callback!", "event", ".", "flags", ".", "include?", "(", ":ignored", ")", "&&", "event", ".", "notifier", ".", "watchers", ".", "delete", "(", "event", ".", "watcher_id", ")", "end", "end" ]
Blocks until there are one or more filesystem events that this notifier has watchers registered for. Once there are events, the appropriate callbacks are called and this function returns. @see #run
[ "Blocks", "until", "there", "are", "one", "or", "more", "filesystem", "events", "that", "this", "notifier", "has", "watchers", "registered", "for", ".", "Once", "there", "are", "events", "the", "appropriate", "callbacks", "are", "called", "and", "this", "function", "returns", "." ]
3fae270905c7bd259e69fe420dbdcd59bb47fa3d
https://github.com/guard/rb-inotify/blob/3fae270905c7bd259e69fe420dbdcd59bb47fa3d/lib/rb-inotify/notifier.rb#L251-L256
train
chefspec/fauxhai
lib/fauxhai/mocker.rb
Fauxhai.Mocker.data
def data @fauxhai_data ||= lambda do # If a path option was specified, use it if @options[:path] filepath = File.expand_path(@options[:path]) unless File.exist?(filepath) raise Fauxhai::Exception::InvalidPlatform.new("You specified a path to a JSON file on the local system that does not exist: '#{filepath}'") end else filepath = File.join(platform_path, "#{version}.json") end if File.exist?(filepath) parse_and_validate(File.read(filepath)) elsif @options[:github_fetching] # Try loading from github (in case someone submitted a PR with a new file, but we haven't # yet updated the gem version). Cache the response locally so it's faster next time. begin response = open("#{RAW_BASE}/lib/fauxhai/platforms/#{platform}/#{version}.json") rescue OpenURI::HTTPError raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and an HTTP error was encountered when fetching from Github. #{PLATFORM_LIST_MESSAGE}") end if response.status.first.to_i == 200 response_body = response.read path = Pathname.new(filepath) FileUtils.mkdir_p(path.dirname) begin File.open(filepath, 'w') { |f| f.write(response_body) } rescue Errno::EACCES # a pretty common problem in CI systems puts "Fetched '#{platform}/#{version}' from GitHub, but could not write to the local path: #{filepath}. Fix the local file permissions to avoid downloading this file every run." end return parse_and_validate(response_body) else raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and an Github fetching returned http error code #{response.status.first.to_i}! #{PLATFORM_LIST_MESSAGE}") end else raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and Github fetching is disabled! #{PLATFORM_LIST_MESSAGE}") end end.call end
ruby
def data @fauxhai_data ||= lambda do # If a path option was specified, use it if @options[:path] filepath = File.expand_path(@options[:path]) unless File.exist?(filepath) raise Fauxhai::Exception::InvalidPlatform.new("You specified a path to a JSON file on the local system that does not exist: '#{filepath}'") end else filepath = File.join(platform_path, "#{version}.json") end if File.exist?(filepath) parse_and_validate(File.read(filepath)) elsif @options[:github_fetching] # Try loading from github (in case someone submitted a PR with a new file, but we haven't # yet updated the gem version). Cache the response locally so it's faster next time. begin response = open("#{RAW_BASE}/lib/fauxhai/platforms/#{platform}/#{version}.json") rescue OpenURI::HTTPError raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and an HTTP error was encountered when fetching from Github. #{PLATFORM_LIST_MESSAGE}") end if response.status.first.to_i == 200 response_body = response.read path = Pathname.new(filepath) FileUtils.mkdir_p(path.dirname) begin File.open(filepath, 'w') { |f| f.write(response_body) } rescue Errno::EACCES # a pretty common problem in CI systems puts "Fetched '#{platform}/#{version}' from GitHub, but could not write to the local path: #{filepath}. Fix the local file permissions to avoid downloading this file every run." end return parse_and_validate(response_body) else raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and an Github fetching returned http error code #{response.status.first.to_i}! #{PLATFORM_LIST_MESSAGE}") end else raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and Github fetching is disabled! #{PLATFORM_LIST_MESSAGE}") end end.call end
[ "def", "data", "@fauxhai_data", "||=", "lambda", "do", "if", "@options", "[", ":path", "]", "filepath", "=", "File", ".", "expand_path", "(", "@options", "[", ":path", "]", ")", "unless", "File", ".", "exist?", "(", "filepath", ")", "raise", "Fauxhai", "::", "Exception", "::", "InvalidPlatform", ".", "new", "(", "\"You specified a path to a JSON file on the local system that does not exist: '#{filepath}'\"", ")", "end", "else", "filepath", "=", "File", ".", "join", "(", "platform_path", ",", "\"#{version}.json\"", ")", "end", "if", "File", ".", "exist?", "(", "filepath", ")", "parse_and_validate", "(", "File", ".", "read", "(", "filepath", ")", ")", "elsif", "@options", "[", ":github_fetching", "]", "begin", "response", "=", "open", "(", "\"#{RAW_BASE}/lib/fauxhai/platforms/#{platform}/#{version}.json\"", ")", "rescue", "OpenURI", "::", "HTTPError", "raise", "Fauxhai", "::", "Exception", "::", "InvalidPlatform", ".", "new", "(", "\"Could not find platform '#{platform}/#{version}' on the local disk and an HTTP error was encountered when fetching from Github. #{PLATFORM_LIST_MESSAGE}\"", ")", "end", "if", "response", ".", "status", ".", "first", ".", "to_i", "==", "200", "response_body", "=", "response", ".", "read", "path", "=", "Pathname", ".", "new", "(", "filepath", ")", "FileUtils", ".", "mkdir_p", "(", "path", ".", "dirname", ")", "begin", "File", ".", "open", "(", "filepath", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "response_body", ")", "}", "rescue", "Errno", "::", "EACCES", "puts", "\"Fetched '#{platform}/#{version}' from GitHub, but could not write to the local path: #{filepath}. Fix the local file permissions to avoid downloading this file every run.\"", "end", "return", "parse_and_validate", "(", "response_body", ")", "else", "raise", "Fauxhai", "::", "Exception", "::", "InvalidPlatform", ".", "new", "(", "\"Could not find platform '#{platform}/#{version}' on the local disk and an Github fetching returned http error code #{response.status.first.to_i}! #{PLATFORM_LIST_MESSAGE}\"", ")", "end", "else", "raise", "Fauxhai", "::", "Exception", "::", "InvalidPlatform", ".", "new", "(", "\"Could not find platform '#{platform}/#{version}' on the local disk and Github fetching is disabled! #{PLATFORM_LIST_MESSAGE}\"", ")", "end", "end", ".", "call", "end" ]
Create a new Ohai Mock with fauxhai. @param [Hash] options the options for the mocker @option options [String] :platform the platform to mock @option options [String] :version the version of the platform to mock @option options [String] :path the path to a local JSON file @option options [Bool] :github_fetching whether to try loading from Github
[ "Create", "a", "new", "Ohai", "Mock", "with", "fauxhai", "." ]
c73522490738f254920a4c344822524fef1ee7d0
https://github.com/chefspec/fauxhai/blob/c73522490738f254920a4c344822524fef1ee7d0/lib/fauxhai/mocker.rb#L31-L73
train
chefspec/fauxhai
lib/fauxhai/mocker.rb
Fauxhai.Mocker.parse_and_validate
def parse_and_validate(unparsed_data) parsed_data = JSON.parse(unparsed_data) if parsed_data['deprecated'] STDERR.puts "WARNING: Fauxhai platform data for #{parsed_data['platform']} #{parsed_data['platform_version']} is deprecated and will be removed in the 7.0 release 3/2019. #{PLATFORM_LIST_MESSAGE}" end parsed_data end
ruby
def parse_and_validate(unparsed_data) parsed_data = JSON.parse(unparsed_data) if parsed_data['deprecated'] STDERR.puts "WARNING: Fauxhai platform data for #{parsed_data['platform']} #{parsed_data['platform_version']} is deprecated and will be removed in the 7.0 release 3/2019. #{PLATFORM_LIST_MESSAGE}" end parsed_data end
[ "def", "parse_and_validate", "(", "unparsed_data", ")", "parsed_data", "=", "JSON", ".", "parse", "(", "unparsed_data", ")", "if", "parsed_data", "[", "'deprecated'", "]", "STDERR", ".", "puts", "\"WARNING: Fauxhai platform data for #{parsed_data['platform']} #{parsed_data['platform_version']} is deprecated and will be removed in the 7.0 release 3/2019. #{PLATFORM_LIST_MESSAGE}\"", "end", "parsed_data", "end" ]
As major releases of Ohai ship it's difficult and sometimes impossible to regenerate all fauxhai data. This allows us to deprecate old releases and eventually remove them while giving end users ample warning.
[ "As", "major", "releases", "of", "Ohai", "ship", "it", "s", "difficult", "and", "sometimes", "impossible", "to", "regenerate", "all", "fauxhai", "data", ".", "This", "allows", "us", "to", "deprecate", "old", "releases", "and", "eventually", "remove", "them", "while", "giving", "end", "users", "ample", "warning", "." ]
c73522490738f254920a4c344822524fef1ee7d0
https://github.com/chefspec/fauxhai/blob/c73522490738f254920a4c344822524fef1ee7d0/lib/fauxhai/mocker.rb#L80-L86
train
jwilger/the_help
lib/the_help/service_caller.rb
TheHelp.ServiceCaller.call_service
def call_service(service, **args, &block) service_args = { context: service_context, logger: service_logger }.merge(args) service_logger.debug("#{self.class.name}/#{__id__} called service " \ "#{service.name}") service.call(**service_args, &block) end
ruby
def call_service(service, **args, &block) service_args = { context: service_context, logger: service_logger }.merge(args) service_logger.debug("#{self.class.name}/#{__id__} called service " \ "#{service.name}") service.call(**service_args, &block) end
[ "def", "call_service", "(", "service", ",", "**", "args", ",", "&", "block", ")", "service_args", "=", "{", "context", ":", "service_context", ",", "logger", ":", "service_logger", "}", ".", "merge", "(", "args", ")", "service_logger", ".", "debug", "(", "\"#{self.class.name}/#{__id__} called service \"", "\"#{service.name}\"", ")", "service", ".", "call", "(", "**", "service_args", ",", "&", "block", ")", "end" ]
Calls the specified service @param service [Class<TheHelp::Service>] @param args [Hash<Symbol, Object>] Any additional keyword arguments are passed directly to the service. @return [self]
[ "Calls", "the", "specified", "service" ]
4ca6dff0f1960a096657ac421a8b4e384c92deb8
https://github.com/jwilger/the_help/blob/4ca6dff0f1960a096657ac421a8b4e384c92deb8/lib/the_help/service_caller.rb#L35-L43
train
ManageIQ/awesome_spawn
lib/awesome_spawn/command_line_builder.rb
AwesomeSpawn.CommandLineBuilder.build
def build(command, params = nil) params = assemble_params(sanitize(params)) params.empty? ? command.to_s : "#{command} #{params}" end
ruby
def build(command, params = nil) params = assemble_params(sanitize(params)) params.empty? ? command.to_s : "#{command} #{params}" end
[ "def", "build", "(", "command", ",", "params", "=", "nil", ")", "params", "=", "assemble_params", "(", "sanitize", "(", "params", ")", ")", "params", ".", "empty?", "?", "command", ".", "to_s", ":", "\"#{command} #{params}\"", "end" ]
Build the full command line. @param [String] command The command to run @param [Hash,Array] params Optional command line parameters. They can be passed as a Hash or associative Array. The values are sanitized to prevent command line injection. Keys as Symbols are prefixed with `--`, and `_` is replaced with `-`. - `{:k => "value"}` generates `-k value` - `[[:k, "value"]]` generates `-k value` - `{:k= => "value"}` generates `-k=value` - `[[:k=, "value"]]` generates `-k=value` <br /><br /> - `{:key => "value"}` generates `--key value` - `[[:key, "value"]]` generates `--key value` - `{:key= => "value"}` generates `--key=value` - `[[:key=, "value"]]` generates `--key=value` <br /><br /> - `{"--key" => "value"}` generates `--key value` - `[["--key", "value"]]` generates `--key value` - `{"--key=" => "value"}` generates `--key=value` - `[["--key=", "value"]]` generates `--key=value` <br /><br /> - `{:key_name => "value"}` generates `--key-name value` - `[[:key_name, "value"]]` generates `--key-name value` - `{:key_name= => "value"}` generates `--key-name=value` - `[[:key_name=, "value"]]` generates `--key-name=value` <br /><br /> - `{"-f" => ["file1", "file2"]}` generates `-f file1 file2` - `[["-f", "file1", "file2"]]` generates `-f file1 file2` <br /><br /> - `{:key => nil}` generates `--key` - `[[:key, nil]]` generates `--key` - `[[:key]]` generates `--key` <br /><br /> - `{nil => ["file1", "file2"]}` generates `file1 file2` - `[[nil, ["file1", "file2"]]]` generates `file1 file2` - `[[nil, "file1", "file2"]]` generates `file1 file2` - `[["file1", "file2"]]` generates `file1 file2` @return [String] The full command line
[ "Build", "the", "full", "command", "line", "." ]
7cbf922be564271ce958a75a4e8660d9eef93823
https://github.com/ManageIQ/awesome_spawn/blob/7cbf922be564271ce958a75a4e8660d9eef93823/lib/awesome_spawn/command_line_builder.rb#L46-L49
train
lancejpollard/authlogic-connect
lib/authlogic_connect/common/user.rb
AuthlogicConnect::Common::User.InstanceMethods.save
def save(options = {}, &block) self.errors.clear # log_state options = {} if options == false options[:validate] = true unless options.has_key?(:validate) save_options = ActiveRecord::VERSION::MAJOR < 3 ? options[:validate] : options # kill the block if we're starting authentication authenticate_via_protocol(block_given?, options) do |start_authentication| block = nil if start_authentication # redirecting # forces you to validate, only if a block is given result = super(save_options) # validate! unless block.nil? cleanup_authentication_session(options) yield(result) end result end end
ruby
def save(options = {}, &block) self.errors.clear # log_state options = {} if options == false options[:validate] = true unless options.has_key?(:validate) save_options = ActiveRecord::VERSION::MAJOR < 3 ? options[:validate] : options # kill the block if we're starting authentication authenticate_via_protocol(block_given?, options) do |start_authentication| block = nil if start_authentication # redirecting # forces you to validate, only if a block is given result = super(save_options) # validate! unless block.nil? cleanup_authentication_session(options) yield(result) end result end end
[ "def", "save", "(", "options", "=", "{", "}", ",", "&", "block", ")", "self", ".", "errors", ".", "clear", "options", "=", "{", "}", "if", "options", "==", "false", "options", "[", ":validate", "]", "=", "true", "unless", "options", ".", "has_key?", "(", ":validate", ")", "save_options", "=", "ActiveRecord", "::", "VERSION", "::", "MAJOR", "<", "3", "?", "options", "[", ":validate", "]", ":", "options", "authenticate_via_protocol", "(", "block_given?", ",", "options", ")", "do", "|", "start_authentication", "|", "block", "=", "nil", "if", "start_authentication", "result", "=", "super", "(", "save_options", ")", "unless", "block", ".", "nil?", "cleanup_authentication_session", "(", "options", ")", "yield", "(", "result", ")", "end", "result", "end", "end" ]
core save method coordinating how to save the user. we dont' want to ru validations based on the authentication mission we are trying to accomplish. instead, we just return save as false. the next time around, when we recieve the callback, we will run the validations. when you call 'current_user_session' in ApplicationController, it leads to calling 'save' on this User object via "session.record.save", from the 'persisting?' method. So we don't want any of this to occur when that save is called, and the only way to check currently is to check if there is a block_given?
[ "core", "save", "method", "coordinating", "how", "to", "save", "the", "user", ".", "we", "dont", "want", "to", "ru", "validations", "based", "on", "the", "authentication", "mission", "we", "are", "trying", "to", "accomplish", ".", "instead", "we", "just", "return", "save", "as", "false", ".", "the", "next", "time", "around", "when", "we", "recieve", "the", "callback", "we", "will", "run", "the", "validations", ".", "when", "you", "call", "current_user_session", "in", "ApplicationController", "it", "leads", "to", "calling", "save", "on", "this", "User", "object", "via", "session", ".", "record", ".", "save", "from", "the", "persisting?", "method", ".", "So", "we", "don", "t", "want", "any", "of", "this", "to", "occur", "when", "that", "save", "is", "called", "and", "the", "only", "way", "to", "check", "currently", "is", "to", "check", "if", "there", "is", "a", "block_given?" ]
3b1959ec07f1a9c4164753fea5a5cb1079b88257
https://github.com/lancejpollard/authlogic-connect/blob/3b1959ec07f1a9c4164753fea5a5cb1079b88257/lib/authlogic_connect/common/user.rb#L55-L73
train
lancejpollard/authlogic-connect
lib/authlogic_connect/oauth/user.rb
AuthlogicConnect::Oauth::User.InstanceMethods.save_oauth_session
def save_oauth_session super auth_session[:auth_attributes] = attributes.reject!{|k, v| v.blank? || !self.respond_to?(k)} unless is_auth_session? end
ruby
def save_oauth_session super auth_session[:auth_attributes] = attributes.reject!{|k, v| v.blank? || !self.respond_to?(k)} unless is_auth_session? end
[ "def", "save_oauth_session", "super", "auth_session", "[", ":auth_attributes", "]", "=", "attributes", ".", "reject!", "{", "|", "k", ",", "v", "|", "v", ".", "blank?", "||", "!", "self", ".", "respond_to?", "(", "k", ")", "}", "unless", "is_auth_session?", "end" ]
user adds a few extra things to this method from Process modules work like inheritance
[ "user", "adds", "a", "few", "extra", "things", "to", "this", "method", "from", "Process", "modules", "work", "like", "inheritance" ]
3b1959ec07f1a9c4164753fea5a5cb1079b88257
https://github.com/lancejpollard/authlogic-connect/blob/3b1959ec07f1a9c4164753fea5a5cb1079b88257/lib/authlogic_connect/oauth/user.rb#L33-L36
train
lancejpollard/authlogic-connect
lib/authlogic_connect/oauth/user.rb
AuthlogicConnect::Oauth::User.InstanceMethods.complete_oauth_transaction
def complete_oauth_transaction token = token_class.new(oauth_token_and_secret) old_token = token_class.find_by_key_or_token(token.key, token.token) token = old_token if old_token if has_token?(oauth_provider) self.errors.add(:tokens, "you have already created an account using your #{token_class.service_name} account, so it") else self.access_tokens << token end end
ruby
def complete_oauth_transaction token = token_class.new(oauth_token_and_secret) old_token = token_class.find_by_key_or_token(token.key, token.token) token = old_token if old_token if has_token?(oauth_provider) self.errors.add(:tokens, "you have already created an account using your #{token_class.service_name} account, so it") else self.access_tokens << token end end
[ "def", "complete_oauth_transaction", "token", "=", "token_class", ".", "new", "(", "oauth_token_and_secret", ")", "old_token", "=", "token_class", ".", "find_by_key_or_token", "(", "token", ".", "key", ",", "token", ".", "token", ")", "token", "=", "old_token", "if", "old_token", "if", "has_token?", "(", "oauth_provider", ")", "self", ".", "errors", ".", "add", "(", ":tokens", ",", "\"you have already created an account using your #{token_class.service_name} account, so it\"", ")", "else", "self", ".", "access_tokens", "<<", "token", "end", "end" ]
single implementation method for oauth. this is called after we get the callback url and we are saving the user to the database. it is called by the validation chain.
[ "single", "implementation", "method", "for", "oauth", ".", "this", "is", "called", "after", "we", "get", "the", "callback", "url", "and", "we", "are", "saving", "the", "user", "to", "the", "database", ".", "it", "is", "called", "by", "the", "validation", "chain", "." ]
3b1959ec07f1a9c4164753fea5a5cb1079b88257
https://github.com/lancejpollard/authlogic-connect/blob/3b1959ec07f1a9c4164753fea5a5cb1079b88257/lib/authlogic_connect/oauth/user.rb#L51-L61
train
ondra-m/ruby-spark
lib/spark/command_builder.rb
Spark.CommandBuilder.serialize_function
def serialize_function(func) case func when String serialize_function_from_string(func) when Symbol serialize_function_from_symbol(func) when Proc serialize_function_from_proc(func) when Method serialize_function_from_method(func) else raise Spark::CommandError, 'You must enter String, Symbol, Proc or Method.' end end
ruby
def serialize_function(func) case func when String serialize_function_from_string(func) when Symbol serialize_function_from_symbol(func) when Proc serialize_function_from_proc(func) when Method serialize_function_from_method(func) else raise Spark::CommandError, 'You must enter String, Symbol, Proc or Method.' end end
[ "def", "serialize_function", "(", "func", ")", "case", "func", "when", "String", "serialize_function_from_string", "(", "func", ")", "when", "Symbol", "serialize_function_from_symbol", "(", "func", ")", "when", "Proc", "serialize_function_from_proc", "(", "func", ")", "when", "Method", "serialize_function_from_method", "(", "func", ")", "else", "raise", "Spark", "::", "CommandError", ",", "'You must enter String, Symbol, Proc or Method.'", "end", "end" ]
Serialized can be Proc and Method === Func * *string:* already serialized proc * *proc:* proc * *symbol:* name of method * *method:* Method class
[ "Serialized", "can", "be", "Proc", "and", "Method" ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/command_builder.rb#L87-L100
train
ondra-m/ruby-spark
lib/spark/command_builder.rb
Spark.CommandBuilder.serialize_function_from_method
def serialize_function_from_method(meth) if pry? meth = Pry::Method.new(meth) end {type: 'method', name: meth.name, content: meth.source} rescue raise Spark::SerializeError, 'Method can not be serialized. Use full path or Proc.' end
ruby
def serialize_function_from_method(meth) if pry? meth = Pry::Method.new(meth) end {type: 'method', name: meth.name, content: meth.source} rescue raise Spark::SerializeError, 'Method can not be serialized. Use full path or Proc.' end
[ "def", "serialize_function_from_method", "(", "meth", ")", "if", "pry?", "meth", "=", "Pry", "::", "Method", ".", "new", "(", "meth", ")", "end", "{", "type", ":", "'method'", ",", "name", ":", "meth", ".", "name", ",", "content", ":", "meth", ".", "source", "}", "rescue", "raise", "Spark", "::", "SerializeError", ",", "'Method can not be serialized. Use full path or Proc.'", "end" ]
Serialize method as string def test(x) x*x end serialize_function_from_method(method(:test)) # => "def test(x)\n x*x\nend\n"
[ "Serialize", "method", "as", "string" ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/command_builder.rb#L130-L138
train
ondra-m/ruby-spark
lib/spark/config.rb
Spark.Config.from_file
def from_file(file) check_read_only if file && File.exist?(file) file = File.expand_path(file) RubyUtils.loadPropertiesFile(spark_conf, file) end end
ruby
def from_file(file) check_read_only if file && File.exist?(file) file = File.expand_path(file) RubyUtils.loadPropertiesFile(spark_conf, file) end end
[ "def", "from_file", "(", "file", ")", "check_read_only", "if", "file", "&&", "File", ".", "exist?", "(", "file", ")", "file", "=", "File", ".", "expand_path", "(", "file", ")", "RubyUtils", ".", "loadPropertiesFile", "(", "spark_conf", ",", "file", ")", "end", "end" ]
Initialize java SparkConf and load default configuration.
[ "Initialize", "java", "SparkConf", "and", "load", "default", "configuration", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/config.rb#L22-L29
train
ondra-m/ruby-spark
lib/spark/config.rb
Spark.Config.get
def get(key) value = spark_conf.get(key.to_s) case TYPES[key] when :boolean parse_boolean(value) when :integer parse_integer(value) else value end rescue nil end
ruby
def get(key) value = spark_conf.get(key.to_s) case TYPES[key] when :boolean parse_boolean(value) when :integer parse_integer(value) else value end rescue nil end
[ "def", "get", "(", "key", ")", "value", "=", "spark_conf", ".", "get", "(", "key", ".", "to_s", ")", "case", "TYPES", "[", "key", "]", "when", ":boolean", "parse_boolean", "(", "value", ")", "when", ":integer", "parse_integer", "(", "value", ")", "else", "value", "end", "rescue", "nil", "end" ]
Rescue from NoSuchElementException
[ "Rescue", "from", "NoSuchElementException" ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/config.rb#L85-L98
train
ondra-m/ruby-spark
lib/spark/config.rb
Spark.Config.load_executor_envs
def load_executor_envs prefix = 'SPARK_RUBY_EXECUTOR_ENV_' envs = ENV.select{|key, _| key.start_with?(prefix)} envs.each do |key, value| key = key.dup # ENV keys are frozen key.slice!(0, prefix.size) set("spark.ruby.executor.env.#{key}", value) end end
ruby
def load_executor_envs prefix = 'SPARK_RUBY_EXECUTOR_ENV_' envs = ENV.select{|key, _| key.start_with?(prefix)} envs.each do |key, value| key = key.dup # ENV keys are frozen key.slice!(0, prefix.size) set("spark.ruby.executor.env.#{key}", value) end end
[ "def", "load_executor_envs", "prefix", "=", "'SPARK_RUBY_EXECUTOR_ENV_'", "envs", "=", "ENV", ".", "select", "{", "|", "key", ",", "_", "|", "key", ".", "start_with?", "(", "prefix", ")", "}", "envs", ".", "each", "do", "|", "key", ",", "value", "|", "key", "=", "key", ".", "dup", "key", ".", "slice!", "(", "0", ",", "prefix", ".", "size", ")", "set", "(", "\"spark.ruby.executor.env.#{key}\"", ",", "value", ")", "end", "end" ]
Load environment variables for executor from ENV. == Examples: SPARK_RUBY_EXECUTOR_ENV_KEY1="1" SPARK_RUBY_EXECUTOR_ENV_KEY2="2"
[ "Load", "environment", "variables", "for", "executor", "from", "ENV", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/config.rb#L208-L218
train
ondra-m/ruby-spark
lib/spark/worker/worker.rb
Worker.Base.compute
def compute before_start # Load split index @split_index = socket.read_int # Load files SparkFiles.root_directory = socket.read_string # Load broadcast count = socket.read_int count.times do Spark::Broadcast.register(socket.read_long, socket.read_string) end # Load command @command = socket.read_data # Load iterator @iterator = @command.deserializer.load_from_io(socket).lazy # Compute @iterator = @command.execute(@iterator, @split_index) # Result is not iterable @iterator = [@iterator] unless @iterator.respond_to?(:each) # Send result @command.serializer.dump_to_io(@iterator, socket) end
ruby
def compute before_start # Load split index @split_index = socket.read_int # Load files SparkFiles.root_directory = socket.read_string # Load broadcast count = socket.read_int count.times do Spark::Broadcast.register(socket.read_long, socket.read_string) end # Load command @command = socket.read_data # Load iterator @iterator = @command.deserializer.load_from_io(socket).lazy # Compute @iterator = @command.execute(@iterator, @split_index) # Result is not iterable @iterator = [@iterator] unless @iterator.respond_to?(:each) # Send result @command.serializer.dump_to_io(@iterator, socket) end
[ "def", "compute", "before_start", "@split_index", "=", "socket", ".", "read_int", "SparkFiles", ".", "root_directory", "=", "socket", ".", "read_string", "count", "=", "socket", ".", "read_int", "count", ".", "times", "do", "Spark", "::", "Broadcast", ".", "register", "(", "socket", ".", "read_long", ",", "socket", ".", "read_string", ")", "end", "@command", "=", "socket", ".", "read_data", "@iterator", "=", "@command", ".", "deserializer", ".", "load_from_io", "(", "socket", ")", ".", "lazy", "@iterator", "=", "@command", ".", "execute", "(", "@iterator", ",", "@split_index", ")", "@iterator", "=", "[", "@iterator", "]", "unless", "@iterator", ".", "respond_to?", "(", ":each", ")", "@command", ".", "serializer", ".", "dump_to_io", "(", "@iterator", ",", "socket", ")", "end" ]
These methods must be on one method because iterator is Lazy which mean that exception can be raised at `serializer` or `compute`
[ "These", "methods", "must", "be", "on", "one", "method", "because", "iterator", "is", "Lazy", "which", "mean", "that", "exception", "can", "be", "raised", "at", "serializer", "or", "compute" ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/worker/worker.rb#L57-L86
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.inspect
def inspect comms = @command.commands.join(' -> ') result = %{#<#{self.class.name}:0x#{object_id}} result << %{ (#{comms})} unless comms.empty? result << %{ (cached)} if cached? result << %{\n} result << %{ Serializer: "#{serializer}"\n} result << %{Deserializer: "#{deserializer}"} result << %{>} result end
ruby
def inspect comms = @command.commands.join(' -> ') result = %{#<#{self.class.name}:0x#{object_id}} result << %{ (#{comms})} unless comms.empty? result << %{ (cached)} if cached? result << %{\n} result << %{ Serializer: "#{serializer}"\n} result << %{Deserializer: "#{deserializer}"} result << %{>} result end
[ "def", "inspect", "comms", "=", "@command", ".", "commands", ".", "join", "(", "' -> '", ")", "result", "=", "%{#<#{self.class.name}:0x#{object_id}}", "result", "<<", "%{ (#{comms})}", "unless", "comms", ".", "empty?", "result", "<<", "%{ (cached)}", "if", "cached?", "result", "<<", "%{\\n}", "result", "<<", "%{ Serializer: \"#{serializer}\"\\n}", "result", "<<", "%{Deserializer: \"#{deserializer}\"}", "result", "<<", "%{>}", "result", "end" ]
Initializing RDD, this method is root of all Pipelined RDD - its unique If you call some operations on this class it will be computed in Java == Parameters: jrdd:: org.apache.spark.api.java.JavaRDD context:: {Spark::Context} serializer:: {Spark::Serializer}
[ "Initializing", "RDD", "this", "method", "is", "root", "of", "all", "Pipelined", "RDD", "-", "its", "unique", "If", "you", "call", "some", "operations", "on", "this", "class", "it", "will", "be", "computed", "in", "Java" ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L37-L48
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.take
def take(count) buffer = [] parts_count = self.partitions_size # No parts was scanned, yet last_scanned = -1 while buffer.empty? last_scanned += 1 buffer += context.run_job_with_command(self, [last_scanned], true, Spark::Command::Take, 0, -1) end # Assumption. Depend on batch_size and how Spark divided data. items_per_part = buffer.size left = count - buffer.size while left > 0 && last_scanned < parts_count parts_to_take = (left.to_f/items_per_part).ceil parts_for_scanned = Array.new(parts_to_take) do last_scanned += 1 end # We cannot take exact number of items because workers are isolated from each other. # => once you take e.g. 50% from last part and left is still > 0 then its very # difficult merge new items items = context.run_job_with_command(self, parts_for_scanned, true, Spark::Command::Take, left, last_scanned) buffer += items left = count - buffer.size # Average size of all parts items_per_part = [items_per_part, items.size].reduce(0){|sum, x| sum + x.to_f/2} end buffer.slice!(0, count) end
ruby
def take(count) buffer = [] parts_count = self.partitions_size # No parts was scanned, yet last_scanned = -1 while buffer.empty? last_scanned += 1 buffer += context.run_job_with_command(self, [last_scanned], true, Spark::Command::Take, 0, -1) end # Assumption. Depend on batch_size and how Spark divided data. items_per_part = buffer.size left = count - buffer.size while left > 0 && last_scanned < parts_count parts_to_take = (left.to_f/items_per_part).ceil parts_for_scanned = Array.new(parts_to_take) do last_scanned += 1 end # We cannot take exact number of items because workers are isolated from each other. # => once you take e.g. 50% from last part and left is still > 0 then its very # difficult merge new items items = context.run_job_with_command(self, parts_for_scanned, true, Spark::Command::Take, left, last_scanned) buffer += items left = count - buffer.size # Average size of all parts items_per_part = [items_per_part, items.size].reduce(0){|sum, x| sum + x.to_f/2} end buffer.slice!(0, count) end
[ "def", "take", "(", "count", ")", "buffer", "=", "[", "]", "parts_count", "=", "self", ".", "partitions_size", "last_scanned", "=", "-", "1", "while", "buffer", ".", "empty?", "last_scanned", "+=", "1", "buffer", "+=", "context", ".", "run_job_with_command", "(", "self", ",", "[", "last_scanned", "]", ",", "true", ",", "Spark", "::", "Command", "::", "Take", ",", "0", ",", "-", "1", ")", "end", "items_per_part", "=", "buffer", ".", "size", "left", "=", "count", "-", "buffer", ".", "size", "while", "left", ">", "0", "&&", "last_scanned", "<", "parts_count", "parts_to_take", "=", "(", "left", ".", "to_f", "/", "items_per_part", ")", ".", "ceil", "parts_for_scanned", "=", "Array", ".", "new", "(", "parts_to_take", ")", "do", "last_scanned", "+=", "1", "end", "items", "=", "context", ".", "run_job_with_command", "(", "self", ",", "parts_for_scanned", ",", "true", ",", "Spark", "::", "Command", "::", "Take", ",", "left", ",", "last_scanned", ")", "buffer", "+=", "items", "left", "=", "count", "-", "buffer", ".", "size", "items_per_part", "=", "[", "items_per_part", ",", "items", ".", "size", "]", ".", "reduce", "(", "0", ")", "{", "|", "sum", ",", "x", "|", "sum", "+", "x", ".", "to_f", "/", "2", "}", "end", "buffer", ".", "slice!", "(", "0", ",", "count", ")", "end" ]
Take the first num elements of the RDD. It works by first scanning one partition, and use the results from that partition to estimate the number of additional partitions needed to satisfy the limit. == Example: rdd = $sc.parallelize(0..100, 20) rdd.take(5) # => [0, 1, 2, 3, 4]
[ "Take", "the", "first", "num", "elements", "of", "the", "RDD", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L247-L281
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.aggregate
def aggregate(zero_value, seq_op, comb_op) _reduce(Spark::Command::Aggregate, seq_op, comb_op, zero_value) end
ruby
def aggregate(zero_value, seq_op, comb_op) _reduce(Spark::Command::Aggregate, seq_op, comb_op, zero_value) end
[ "def", "aggregate", "(", "zero_value", ",", "seq_op", ",", "comb_op", ")", "_reduce", "(", "Spark", "::", "Command", "::", "Aggregate", ",", "seq_op", ",", "comb_op", ",", "zero_value", ")", "end" ]
Aggregate the elements of each partition, and then the results for all the partitions, using given combine functions and a neutral "zero value". This function can return a different result type. We need one operation for merging. Result must be an Array otherwise Serializer Array's zero value will be send as multiple values and not just one. == Example: # 1 2 3 4 5 => 15 + 1 = 16 # 6 7 8 9 10 => 40 + 1 = 41 # 16 * 41 = 656 seq = lambda{|x,y| x+y} com = lambda{|x,y| x*y} rdd = $sc.parallelize(1..10, 2) rdd.aggregate(1, seq, com) # => 656
[ "Aggregate", "the", "elements", "of", "each", "partition", "and", "then", "the", "results", "for", "all", "the", "partitions", "using", "given", "combine", "functions", "and", "a", "neutral", "zero", "value", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L342-L344
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.coalesce
def coalesce(num_partitions) if self.is_a?(PipelinedRDD) deser = @command.serializer else deser = @command.deserializer end new_jrdd = jrdd.coalesce(num_partitions) RDD.new(new_jrdd, context, @command.serializer, deser) end
ruby
def coalesce(num_partitions) if self.is_a?(PipelinedRDD) deser = @command.serializer else deser = @command.deserializer end new_jrdd = jrdd.coalesce(num_partitions) RDD.new(new_jrdd, context, @command.serializer, deser) end
[ "def", "coalesce", "(", "num_partitions", ")", "if", "self", ".", "is_a?", "(", "PipelinedRDD", ")", "deser", "=", "@command", ".", "serializer", "else", "deser", "=", "@command", ".", "deserializer", "end", "new_jrdd", "=", "jrdd", ".", "coalesce", "(", "num_partitions", ")", "RDD", ".", "new", "(", "new_jrdd", ",", "context", ",", "@command", ".", "serializer", ",", "deser", ")", "end" ]
Return a new RDD that is reduced into num_partitions partitions. == Example: rdd = $sc.parallelize(0..10, 3) rdd.coalesce(2).glom.collect # => [[0, 1, 2], [3, 4, 5, 6, 7, 8, 9, 10]]
[ "Return", "a", "new", "RDD", "that", "is", "reduced", "into", "num_partitions", "partitions", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L683-L692
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.shuffle
def shuffle(seed=nil) seed ||= Random.new_seed new_rdd_from_command(Spark::Command::Shuffle, seed) end
ruby
def shuffle(seed=nil) seed ||= Random.new_seed new_rdd_from_command(Spark::Command::Shuffle, seed) end
[ "def", "shuffle", "(", "seed", "=", "nil", ")", "seed", "||=", "Random", ".", "new_seed", "new_rdd_from_command", "(", "Spark", "::", "Command", "::", "Shuffle", ",", "seed", ")", "end" ]
Return a shuffled RDD. == Example: rdd = $sc.parallelize(0..10) rdd.shuffle.collect # => [3, 10, 6, 7, 8, 0, 4, 2, 9, 1, 5]
[ "Return", "a", "shuffled", "RDD", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L733-L737
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.reserialize
def reserialize(new_serializer) if serializer == new_serializer return self end new_command = @command.deep_copy new_command.serializer = new_serializer PipelinedRDD.new(self, new_command) end
ruby
def reserialize(new_serializer) if serializer == new_serializer return self end new_command = @command.deep_copy new_command.serializer = new_serializer PipelinedRDD.new(self, new_command) end
[ "def", "reserialize", "(", "new_serializer", ")", "if", "serializer", "==", "new_serializer", "return", "self", "end", "new_command", "=", "@command", ".", "deep_copy", "new_command", ".", "serializer", "=", "new_serializer", "PipelinedRDD", ".", "new", "(", "self", ",", "new_command", ")", "end" ]
Return a new RDD with different serializer. This method is useful during union and join operations. == Example: rdd = $sc.parallelize([1, 2, 3], nil, serializer: "marshal") rdd = rdd.map(lambda{|x| x.to_s}) rdd.reserialize("oj").collect # => ["1", "2", "3"]
[ "Return", "a", "new", "RDD", "with", "different", "serializer", ".", "This", "method", "is", "useful", "during", "union", "and", "join", "operations", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L765-L774
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.intersection
def intersection(other) mapping_function = 'lambda{|item| [item, nil]}' filter_function = 'lambda{|(key, values)| values.size > 1}' self.map(mapping_function) .cogroup(other.map(mapping_function)) .filter(filter_function) .keys end
ruby
def intersection(other) mapping_function = 'lambda{|item| [item, nil]}' filter_function = 'lambda{|(key, values)| values.size > 1}' self.map(mapping_function) .cogroup(other.map(mapping_function)) .filter(filter_function) .keys end
[ "def", "intersection", "(", "other", ")", "mapping_function", "=", "'lambda{|item| [item, nil]}'", "filter_function", "=", "'lambda{|(key, values)| values.size > 1}'", "self", ".", "map", "(", "mapping_function", ")", ".", "cogroup", "(", "other", ".", "map", "(", "mapping_function", ")", ")", ".", "filter", "(", "filter_function", ")", ".", "keys", "end" ]
Return the intersection of this RDD and another one. The output will not contain any duplicate elements, even if the input RDDs did. == Example: rdd1 = $sc.parallelize([1,2,3,4,5]) rdd2 = $sc.parallelize([1,4,5,6,7]) rdd1.intersection(rdd2).collect # => [1, 4, 5]
[ "Return", "the", "intersection", "of", "this", "RDD", "and", "another", "one", ".", "The", "output", "will", "not", "contain", "any", "duplicate", "elements", "even", "if", "the", "input", "RDDs", "did", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L785-L793
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.partition_by
def partition_by(num_partitions, partition_func=nil) num_partitions ||= default_reduce_partitions partition_func ||= 'lambda{|x| Spark::Digest.portable_hash(x.to_s)}' _partition_by(num_partitions, Spark::Command::PartitionBy::Basic, partition_func) end
ruby
def partition_by(num_partitions, partition_func=nil) num_partitions ||= default_reduce_partitions partition_func ||= 'lambda{|x| Spark::Digest.portable_hash(x.to_s)}' _partition_by(num_partitions, Spark::Command::PartitionBy::Basic, partition_func) end
[ "def", "partition_by", "(", "num_partitions", ",", "partition_func", "=", "nil", ")", "num_partitions", "||=", "default_reduce_partitions", "partition_func", "||=", "'lambda{|x| Spark::Digest.portable_hash(x.to_s)}'", "_partition_by", "(", "num_partitions", ",", "Spark", "::", "Command", "::", "PartitionBy", "::", "Basic", ",", "partition_func", ")", "end" ]
Return a copy of the RDD partitioned using the specified partitioner. == Example: rdd = $sc.parallelize(["1","2","3","4","5"]).map(lambda {|x| [x, 1]}) rdd.partitionBy(2).glom.collect # => [[["3", 1], ["4", 1]], [["1", 1], ["2", 1], ["5", 1]]]
[ "Return", "a", "copy", "of", "the", "RDD", "partitioned", "using", "the", "specified", "partitioner", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L802-L807
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.take_sample
def take_sample(with_replacement, num, seed=nil) if num < 0 raise Spark::RDDError, 'Size have to be greater than 0' elsif num == 0 return [] end # Taken from scala num_st_dev = 10.0 # Number of items initial_count = self.count return [] if initial_count == 0 # Create new generator seed ||= Random.new_seed rng = Random.new(seed) # Shuffle elements if requested num if greater than array size if !with_replacement && num >= initial_count return self.shuffle(seed).collect end # Max num max_sample_size = Integer::MAX - (num_st_dev * Math.sqrt(Integer::MAX)).to_i if num > max_sample_size raise Spark::RDDError, "Size can not be greate than #{max_sample_size}" end # Approximate fraction with tolerance fraction = compute_fraction(num, initial_count, with_replacement) # Compute first samled subset samples = self.sample(with_replacement, fraction, seed).collect # If the first sample didn't turn out large enough, keep trying to take samples; # this shouldn't happen often because we use a big multiplier for their initial size. index = 0 while samples.size < num log_warning("Needed to re-sample due to insufficient sample size. Repeat #{index}") samples = self.sample(with_replacement, fraction, rng.rand(0..Integer::MAX)).collect index += 1 end samples.shuffle!(random: rng) samples[0, num] end
ruby
def take_sample(with_replacement, num, seed=nil) if num < 0 raise Spark::RDDError, 'Size have to be greater than 0' elsif num == 0 return [] end # Taken from scala num_st_dev = 10.0 # Number of items initial_count = self.count return [] if initial_count == 0 # Create new generator seed ||= Random.new_seed rng = Random.new(seed) # Shuffle elements if requested num if greater than array size if !with_replacement && num >= initial_count return self.shuffle(seed).collect end # Max num max_sample_size = Integer::MAX - (num_st_dev * Math.sqrt(Integer::MAX)).to_i if num > max_sample_size raise Spark::RDDError, "Size can not be greate than #{max_sample_size}" end # Approximate fraction with tolerance fraction = compute_fraction(num, initial_count, with_replacement) # Compute first samled subset samples = self.sample(with_replacement, fraction, seed).collect # If the first sample didn't turn out large enough, keep trying to take samples; # this shouldn't happen often because we use a big multiplier for their initial size. index = 0 while samples.size < num log_warning("Needed to re-sample due to insufficient sample size. Repeat #{index}") samples = self.sample(with_replacement, fraction, rng.rand(0..Integer::MAX)).collect index += 1 end samples.shuffle!(random: rng) samples[0, num] end
[ "def", "take_sample", "(", "with_replacement", ",", "num", ",", "seed", "=", "nil", ")", "if", "num", "<", "0", "raise", "Spark", "::", "RDDError", ",", "'Size have to be greater than 0'", "elsif", "num", "==", "0", "return", "[", "]", "end", "num_st_dev", "=", "10.0", "initial_count", "=", "self", ".", "count", "return", "[", "]", "if", "initial_count", "==", "0", "seed", "||=", "Random", ".", "new_seed", "rng", "=", "Random", ".", "new", "(", "seed", ")", "if", "!", "with_replacement", "&&", "num", ">=", "initial_count", "return", "self", ".", "shuffle", "(", "seed", ")", ".", "collect", "end", "max_sample_size", "=", "Integer", "::", "MAX", "-", "(", "num_st_dev", "*", "Math", ".", "sqrt", "(", "Integer", "::", "MAX", ")", ")", ".", "to_i", "if", "num", ">", "max_sample_size", "raise", "Spark", "::", "RDDError", ",", "\"Size can not be greate than #{max_sample_size}\"", "end", "fraction", "=", "compute_fraction", "(", "num", ",", "initial_count", ",", "with_replacement", ")", "samples", "=", "self", ".", "sample", "(", "with_replacement", ",", "fraction", ",", "seed", ")", ".", "collect", "index", "=", "0", "while", "samples", ".", "size", "<", "num", "log_warning", "(", "\"Needed to re-sample due to insufficient sample size. Repeat #{index}\"", ")", "samples", "=", "self", ".", "sample", "(", "with_replacement", ",", "fraction", ",", "rng", ".", "rand", "(", "0", "..", "Integer", "::", "MAX", ")", ")", ".", "collect", "index", "+=", "1", "end", "samples", ".", "shuffle!", "(", "random", ":", "rng", ")", "samples", "[", "0", ",", "num", "]", "end" ]
Return a fixed-size sampled subset of this RDD in an array == Examples: rdd = $sc.parallelize(0..100) rdd.take_sample(true, 10) # => [90, 84, 74, 44, 27, 22, 72, 96, 80, 54] rdd.take_sample(false, 10) # => [5, 35, 30, 48, 22, 33, 40, 75, 42, 32]
[ "Return", "a", "fixed", "-", "size", "sampled", "subset", "of", "this", "RDD", "in", "an", "array" ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L837-L884
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.group_by_key
def group_by_key(num_partitions=nil) create_combiner = 'lambda{|item| [item]}' merge_value = 'lambda{|combiner, item| combiner << item; combiner}' merge_combiners = 'lambda{|combiner_1, combiner_2| combiner_1 += combiner_2; combiner_1}' combine_by_key(create_combiner, merge_value, merge_combiners, num_partitions) end
ruby
def group_by_key(num_partitions=nil) create_combiner = 'lambda{|item| [item]}' merge_value = 'lambda{|combiner, item| combiner << item; combiner}' merge_combiners = 'lambda{|combiner_1, combiner_2| combiner_1 += combiner_2; combiner_1}' combine_by_key(create_combiner, merge_value, merge_combiners, num_partitions) end
[ "def", "group_by_key", "(", "num_partitions", "=", "nil", ")", "create_combiner", "=", "'lambda{|item| [item]}'", "merge_value", "=", "'lambda{|combiner, item| combiner << item; combiner}'", "merge_combiners", "=", "'lambda{|combiner_1, combiner_2| combiner_1 += combiner_2; combiner_1}'", "combine_by_key", "(", "create_combiner", ",", "merge_value", ",", "merge_combiners", ",", "num_partitions", ")", "end" ]
Group the values for each key in the RDD into a single sequence. Allows controlling the partitioning of the resulting key-value pair RDD by passing a Partitioner. Note: If you are grouping in order to perform an aggregation (such as a sum or average) over each key, using reduce_by_key or combine_by_key will provide much better performance. == Example: rdd = $sc.parallelize([["a", 1], ["a", 2], ["b", 3]]) rdd.group_by_key.collect # => [["a", [1, 2]], ["b", [3]]]
[ "Group", "the", "values", "for", "each", "key", "in", "the", "RDD", "into", "a", "single", "sequence", ".", "Allows", "controlling", "the", "partitioning", "of", "the", "resulting", "key", "-", "value", "pair", "RDD", "by", "passing", "a", "Partitioner", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L989-L995
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.aggregate_by_key
def aggregate_by_key(zero_value, seq_func, comb_func, num_partitions=nil) _combine_by_key( [Spark::Command::CombineByKey::CombineWithZero, zero_value, seq_func], [Spark::Command::CombineByKey::Merge, comb_func], num_partitions ) end
ruby
def aggregate_by_key(zero_value, seq_func, comb_func, num_partitions=nil) _combine_by_key( [Spark::Command::CombineByKey::CombineWithZero, zero_value, seq_func], [Spark::Command::CombineByKey::Merge, comb_func], num_partitions ) end
[ "def", "aggregate_by_key", "(", "zero_value", ",", "seq_func", ",", "comb_func", ",", "num_partitions", "=", "nil", ")", "_combine_by_key", "(", "[", "Spark", "::", "Command", "::", "CombineByKey", "::", "CombineWithZero", ",", "zero_value", ",", "seq_func", "]", ",", "[", "Spark", "::", "Command", "::", "CombineByKey", "::", "Merge", ",", "comb_func", "]", ",", "num_partitions", ")", "end" ]
Aggregate the values of each key, using given combine functions and a neutral zero value. == Example: def combine(x,y) x+y end def merge(x,y) x*y end rdd = $sc.parallelize([["a", 1], ["b", 2], ["a", 3], ["a", 4], ["c", 5]], 2) rdd.aggregate_by_key(1, method(:combine), method(:merge)) # => [["b", 3], ["a", 16], ["c", 6]]
[ "Aggregate", "the", "values", "of", "each", "key", "using", "given", "combine", "functions", "and", "a", "neutral", "zero", "value", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L1026-L1032
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.cogroup
def cogroup(*others) unioned = self others.each do |other| unioned = unioned.union(other) end unioned.group_by_key end
ruby
def cogroup(*others) unioned = self others.each do |other| unioned = unioned.union(other) end unioned.group_by_key end
[ "def", "cogroup", "(", "*", "others", ")", "unioned", "=", "self", "others", ".", "each", "do", "|", "other", "|", "unioned", "=", "unioned", ".", "union", "(", "other", ")", "end", "unioned", ".", "group_by_key", "end" ]
For each key k in `this` or `other`, return a resulting RDD that contains a tuple with the list of values for that key in `this` as well as `other`. == Example: rdd1 = $sc.parallelize([["a", 1], ["a", 2], ["b", 3]]) rdd2 = $sc.parallelize([["a", 4], ["a", 5], ["b", 6]]) rdd3 = $sc.parallelize([["a", 7], ["a", 8], ["b", 9]]) rdd1.cogroup(rdd2, rdd3).collect # => [["a", [1, 2, 4, 5, 7, 8]], ["b", [3, 6, 9]]]
[ "For", "each", "key", "k", "in", "this", "or", "other", "return", "a", "resulting", "RDD", "that", "contains", "a", "tuple", "with", "the", "list", "of", "values", "for", "that", "key", "in", "this", "as", "well", "as", "other", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L1057-L1064
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.subtract
def subtract(other, num_partitions=nil) mapping_function = 'lambda{|x| [x,nil]}' self.map(mapping_function) .subtract_by_key(other.map(mapping_function), num_partitions) .keys end
ruby
def subtract(other, num_partitions=nil) mapping_function = 'lambda{|x| [x,nil]}' self.map(mapping_function) .subtract_by_key(other.map(mapping_function), num_partitions) .keys end
[ "def", "subtract", "(", "other", ",", "num_partitions", "=", "nil", ")", "mapping_function", "=", "'lambda{|x| [x,nil]}'", "self", ".", "map", "(", "mapping_function", ")", ".", "subtract_by_key", "(", "other", ".", "map", "(", "mapping_function", ")", ",", "num_partitions", ")", ".", "keys", "end" ]
Return an RDD with the elements from self that are not in other. == Example: rdd1 = $sc.parallelize([["a", 1], ["a", 2], ["b", 3], ["c", 4]]) rdd2 = $sc.parallelize([["a", 2], ["c", 6]]) rdd1.subtract(rdd2).collect # => [["a", 1], ["b", 3], ["c", 4]]
[ "Return", "an", "RDD", "with", "the", "elements", "from", "self", "that", "are", "not", "in", "other", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L1094-L1100
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD.sort_by
def sort_by(key_function=nil, ascending=true, num_partitions=nil) key_function ||= 'lambda{|x| x}' num_partitions ||= default_reduce_partitions command_klass = Spark::Command::SortByKey # Allow spill data to disk due to memory limit # spilling = config['spark.shuffle.spill'] || false spilling = false memory = '' # Set spilling to false if worker has unlimited memory if memory.empty? spilling = false memory = nil else memory = to_memory_size(memory) end # Sorting should do one worker if num_partitions == 1 rdd = self rdd = rdd.coalesce(1) if partitions_size > 1 return rdd.new_rdd_from_command(command_klass, key_function, ascending, spilling, memory, serializer) end # Compute boundary of collection # Collection should be evenly distributed # 20.0 is from scala RangePartitioner (for roughly balanced output partitions) count = self.count sample_size = num_partitions * 20.0 fraction = [sample_size / [count, 1].max, 1.0].min samples = self.sample(false, fraction, 1).map(key_function).collect samples.sort! # Reverse is much faster than reverse sort_by samples.reverse! if !ascending # Determine part bounds bounds = determine_bounds(samples, num_partitions) shuffled = _partition_by(num_partitions, Spark::Command::PartitionBy::Sorting, key_function, bounds, ascending, num_partitions) shuffled.new_rdd_from_command(command_klass, key_function, ascending, spilling, memory, serializer) end
ruby
def sort_by(key_function=nil, ascending=true, num_partitions=nil) key_function ||= 'lambda{|x| x}' num_partitions ||= default_reduce_partitions command_klass = Spark::Command::SortByKey # Allow spill data to disk due to memory limit # spilling = config['spark.shuffle.spill'] || false spilling = false memory = '' # Set spilling to false if worker has unlimited memory if memory.empty? spilling = false memory = nil else memory = to_memory_size(memory) end # Sorting should do one worker if num_partitions == 1 rdd = self rdd = rdd.coalesce(1) if partitions_size > 1 return rdd.new_rdd_from_command(command_klass, key_function, ascending, spilling, memory, serializer) end # Compute boundary of collection # Collection should be evenly distributed # 20.0 is from scala RangePartitioner (for roughly balanced output partitions) count = self.count sample_size = num_partitions * 20.0 fraction = [sample_size / [count, 1].max, 1.0].min samples = self.sample(false, fraction, 1).map(key_function).collect samples.sort! # Reverse is much faster than reverse sort_by samples.reverse! if !ascending # Determine part bounds bounds = determine_bounds(samples, num_partitions) shuffled = _partition_by(num_partitions, Spark::Command::PartitionBy::Sorting, key_function, bounds, ascending, num_partitions) shuffled.new_rdd_from_command(command_klass, key_function, ascending, spilling, memory, serializer) end
[ "def", "sort_by", "(", "key_function", "=", "nil", ",", "ascending", "=", "true", ",", "num_partitions", "=", "nil", ")", "key_function", "||=", "'lambda{|x| x}'", "num_partitions", "||=", "default_reduce_partitions", "command_klass", "=", "Spark", "::", "Command", "::", "SortByKey", "spilling", "=", "false", "memory", "=", "''", "if", "memory", ".", "empty?", "spilling", "=", "false", "memory", "=", "nil", "else", "memory", "=", "to_memory_size", "(", "memory", ")", "end", "if", "num_partitions", "==", "1", "rdd", "=", "self", "rdd", "=", "rdd", ".", "coalesce", "(", "1", ")", "if", "partitions_size", ">", "1", "return", "rdd", ".", "new_rdd_from_command", "(", "command_klass", ",", "key_function", ",", "ascending", ",", "spilling", ",", "memory", ",", "serializer", ")", "end", "count", "=", "self", ".", "count", "sample_size", "=", "num_partitions", "*", "20.0", "fraction", "=", "[", "sample_size", "/", "[", "count", ",", "1", "]", ".", "max", ",", "1.0", "]", ".", "min", "samples", "=", "self", ".", "sample", "(", "false", ",", "fraction", ",", "1", ")", ".", "map", "(", "key_function", ")", ".", "collect", "samples", ".", "sort!", "samples", ".", "reverse!", "if", "!", "ascending", "bounds", "=", "determine_bounds", "(", "samples", ",", "num_partitions", ")", "shuffled", "=", "_partition_by", "(", "num_partitions", ",", "Spark", "::", "Command", "::", "PartitionBy", "::", "Sorting", ",", "key_function", ",", "bounds", ",", "ascending", ",", "num_partitions", ")", "shuffled", ".", "new_rdd_from_command", "(", "command_klass", ",", "key_function", ",", "ascending", ",", "spilling", ",", "memory", ",", "serializer", ")", "end" ]
Sorts this RDD by the given key_function This is a different implementation than spark. Sort by doesn't use key_by method first. It can be slower but take less memory and you can always use map.sort_by_key == Example: rdd = $sc.parallelize(["aaaaaaa", "cc", "b", "eeee", "ddd"]) rdd.sort_by.collect # => ["aaaaaaa", "b", "cc", "ddd", "eeee"] rdd.sort_by(lambda{|x| x.size}).collect # => ["b", "cc", "ddd", "eeee", "aaaaaaa"]
[ "Sorts", "this", "RDD", "by", "the", "given", "key_function" ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L1139-L1181
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD._reduce
def _reduce(klass, seq_op, comb_op, zero_value=nil) if seq_op.nil? # Partitions are already reduced rdd = self else rdd = new_rdd_from_command(klass, seq_op, zero_value) end # Send all results to one worker and combine results rdd = rdd.coalesce(1).compact # Add the same function to new RDD comm = rdd.add_command(klass, comb_op, zero_value) comm.deserializer = @command.serializer # Value is returned in array PipelinedRDD.new(rdd, comm).collect[0] end
ruby
def _reduce(klass, seq_op, comb_op, zero_value=nil) if seq_op.nil? # Partitions are already reduced rdd = self else rdd = new_rdd_from_command(klass, seq_op, zero_value) end # Send all results to one worker and combine results rdd = rdd.coalesce(1).compact # Add the same function to new RDD comm = rdd.add_command(klass, comb_op, zero_value) comm.deserializer = @command.serializer # Value is returned in array PipelinedRDD.new(rdd, comm).collect[0] end
[ "def", "_reduce", "(", "klass", ",", "seq_op", ",", "comb_op", ",", "zero_value", "=", "nil", ")", "if", "seq_op", ".", "nil?", "rdd", "=", "self", "else", "rdd", "=", "new_rdd_from_command", "(", "klass", ",", "seq_op", ",", "zero_value", ")", "end", "rdd", "=", "rdd", ".", "coalesce", "(", "1", ")", ".", "compact", "comm", "=", "rdd", ".", "add_command", "(", "klass", ",", "comb_op", ",", "zero_value", ")", "comm", ".", "deserializer", "=", "@command", ".", "serializer", "PipelinedRDD", ".", "new", "(", "rdd", ",", "comm", ")", ".", "collect", "[", "0", "]", "end" ]
This is base method for reduce operation. Is used by reduce, fold and aggregation. Only difference is that fold has zero value.
[ "This", "is", "base", "method", "for", "reduce", "operation", ".", "Is", "used", "by", "reduce", "fold", "and", "aggregation", ".", "Only", "difference", "is", "that", "fold", "has", "zero", "value", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L1301-L1318
train
ondra-m/ruby-spark
lib/spark/rdd.rb
Spark.RDD._combine_by_key
def _combine_by_key(combine, merge, num_partitions) num_partitions ||= default_reduce_partitions # Combine key combined = new_rdd_from_command(combine.shift, *combine) # Merge items shuffled = combined.partition_by(num_partitions) merge_comm = shuffled.add_command(merge.shift, *merge) PipelinedRDD.new(shuffled, merge_comm) end
ruby
def _combine_by_key(combine, merge, num_partitions) num_partitions ||= default_reduce_partitions # Combine key combined = new_rdd_from_command(combine.shift, *combine) # Merge items shuffled = combined.partition_by(num_partitions) merge_comm = shuffled.add_command(merge.shift, *merge) PipelinedRDD.new(shuffled, merge_comm) end
[ "def", "_combine_by_key", "(", "combine", ",", "merge", ",", "num_partitions", ")", "num_partitions", "||=", "default_reduce_partitions", "combined", "=", "new_rdd_from_command", "(", "combine", ".", "shift", ",", "*", "combine", ")", "shuffled", "=", "combined", ".", "partition_by", "(", "num_partitions", ")", "merge_comm", "=", "shuffled", ".", "add_command", "(", "merge", ".", "shift", ",", "*", "merge", ")", "PipelinedRDD", ".", "new", "(", "shuffled", ",", "merge_comm", ")", "end" ]
For using a different combine_by_key == Used for: * combine_by_key * fold_by_key (with zero value)
[ "For", "using", "a", "different", "combine_by_key" ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L1341-L1352
train
ondra-m/ruby-spark
lib/spark/logger.rb
Spark.Logger.disable
def disable jlogger.setLevel(level_off) JLogger.getLogger('org').setLevel(level_off) JLogger.getLogger('akka').setLevel(level_off) JLogger.getRootLogger.setLevel(level_off) end
ruby
def disable jlogger.setLevel(level_off) JLogger.getLogger('org').setLevel(level_off) JLogger.getLogger('akka').setLevel(level_off) JLogger.getRootLogger.setLevel(level_off) end
[ "def", "disable", "jlogger", ".", "setLevel", "(", "level_off", ")", "JLogger", ".", "getLogger", "(", "'org'", ")", ".", "setLevel", "(", "level_off", ")", "JLogger", ".", "getLogger", "(", "'akka'", ")", ".", "setLevel", "(", "level_off", ")", "JLogger", ".", "getRootLogger", ".", "setLevel", "(", "level_off", ")", "end" ]
Disable all Spark log
[ "Disable", "all", "Spark", "log" ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/logger.rb#L18-L23
train
ondra-m/ruby-spark
lib/spark/context.rb
Spark.Context.accumulator
def accumulator(value, accum_param=:+, zero_value=0) Spark::Accumulator.new(value, accum_param, zero_value) end
ruby
def accumulator(value, accum_param=:+, zero_value=0) Spark::Accumulator.new(value, accum_param, zero_value) end
[ "def", "accumulator", "(", "value", ",", "accum_param", "=", ":+", ",", "zero_value", "=", "0", ")", "Spark", "::", "Accumulator", ".", "new", "(", "value", ",", "accum_param", ",", "zero_value", ")", "end" ]
Create an Accumulator with the given initial value, using a given accum_param helper object to define how to add values of the data type if provided. == Example: accum = $sc.accumulator(7) rdd = $sc.parallelize(0..5, 4) rdd = rdd.bind(accum: accum) rdd = rdd.map_partitions(lambda{|_| accum.add(1) }) rdd = rdd.collect accum.value # => 11
[ "Create", "an", "Accumulator", "with", "the", "given", "initial", "value", "using", "a", "given", "accum_param", "helper", "object", "to", "define", "how", "to", "add", "values", "of", "the", "data", "type", "if", "provided", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/context.rb#L188-L190
train
ondra-m/ruby-spark
lib/spark/context.rb
Spark.Context.parallelize
def parallelize(data, num_slices=nil, serializer=nil) num_slices ||= default_parallelism serializer ||= default_serializer serializer.check_each(data) # Through file file = Tempfile.new('to_parallelize', temp_dir) serializer.dump_to_io(data, file) file.close # not unlink jrdd = RubyRDD.readRDDFromFile(jcontext, file.path, num_slices) Spark::RDD.new(jrdd, self, serializer) ensure file && file.unlink end
ruby
def parallelize(data, num_slices=nil, serializer=nil) num_slices ||= default_parallelism serializer ||= default_serializer serializer.check_each(data) # Through file file = Tempfile.new('to_parallelize', temp_dir) serializer.dump_to_io(data, file) file.close # not unlink jrdd = RubyRDD.readRDDFromFile(jcontext, file.path, num_slices) Spark::RDD.new(jrdd, self, serializer) ensure file && file.unlink end
[ "def", "parallelize", "(", "data", ",", "num_slices", "=", "nil", ",", "serializer", "=", "nil", ")", "num_slices", "||=", "default_parallelism", "serializer", "||=", "default_serializer", "serializer", ".", "check_each", "(", "data", ")", "file", "=", "Tempfile", ".", "new", "(", "'to_parallelize'", ",", "temp_dir", ")", "serializer", ".", "dump_to_io", "(", "data", ",", "file", ")", "file", ".", "close", "jrdd", "=", "RubyRDD", ".", "readRDDFromFile", "(", "jcontext", ",", "file", ".", "path", ",", "num_slices", ")", "Spark", "::", "RDD", ".", "new", "(", "jrdd", ",", "self", ",", "serializer", ")", "ensure", "file", "&&", "file", ".", "unlink", "end" ]
Distribute a local Ruby collection to form an RDD Direct method can be slow so be careful, this method update data inplace == Parameters: data:: Range or Array num_slices:: number of slice serializer:: custom serializer (default: serializer based on configuration) == Examples: $sc.parallelize(["1", "2", "3"]).map(lambda{|x| x.to_i}).collect #=> [1, 2, 3] $sc.parallelize(1..3).map(:to_s).collect #=> ["1", "2", "3"]
[ "Distribute", "a", "local", "Ruby", "collection", "to", "form", "an", "RDD", "Direct", "method", "can", "be", "slow", "so", "be", "careful", "this", "method", "update", "data", "inplace" ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/context.rb#L207-L222
train
ondra-m/ruby-spark
lib/spark/context.rb
Spark.Context.run_job
def run_job(rdd, f, partitions=nil, allow_local=false) run_job_with_command(rdd, partitions, allow_local, Spark::Command::MapPartitions, f) end
ruby
def run_job(rdd, f, partitions=nil, allow_local=false) run_job_with_command(rdd, partitions, allow_local, Spark::Command::MapPartitions, f) end
[ "def", "run_job", "(", "rdd", ",", "f", ",", "partitions", "=", "nil", ",", "allow_local", "=", "false", ")", "run_job_with_command", "(", "rdd", ",", "partitions", ",", "allow_local", ",", "Spark", "::", "Command", "::", "MapPartitions", ",", "f", ")", "end" ]
Executes the given partition function f on the specified set of partitions, returning the result as an array of elements. If partitions is not specified, this will run over all partitions. == Example: rdd = $sc.parallelize(0..10, 5) $sc.run_job(rdd, lambda{|x| x.to_s}, [0,2]) # => ["[0, 1]", "[4, 5]"]
[ "Executes", "the", "given", "partition", "function", "f", "on", "the", "specified", "set", "of", "partitions", "returning", "the", "result", "as", "an", "array", "of", "elements", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/context.rb#L278-L280
train
ondra-m/ruby-spark
lib/spark/context.rb
Spark.Context.run_job_with_command
def run_job_with_command(rdd, partitions, allow_local, command, *args) if !partitions.nil? && !partitions.is_a?(Array) raise Spark::ContextError, 'Partitions must be nil or Array' end partitions_size = rdd.partitions_size # Execute all parts if partitions.nil? partitions = (0...partitions_size).to_a end # Can happend when you use coalesce partitions.delete_if {|part| part >= partitions_size} # Rjb represent Fixnum as Integer but Jruby as Long partitions = to_java_array_list(convert_to_java_int(partitions)) # File for result file = Tempfile.new('collect', temp_dir) mapped = rdd.new_rdd_from_command(command, *args) RubyRDD.runJob(rdd.context.sc, mapped.jrdd, partitions, allow_local, file.path) mapped.collect_from_file(file) end
ruby
def run_job_with_command(rdd, partitions, allow_local, command, *args) if !partitions.nil? && !partitions.is_a?(Array) raise Spark::ContextError, 'Partitions must be nil or Array' end partitions_size = rdd.partitions_size # Execute all parts if partitions.nil? partitions = (0...partitions_size).to_a end # Can happend when you use coalesce partitions.delete_if {|part| part >= partitions_size} # Rjb represent Fixnum as Integer but Jruby as Long partitions = to_java_array_list(convert_to_java_int(partitions)) # File for result file = Tempfile.new('collect', temp_dir) mapped = rdd.new_rdd_from_command(command, *args) RubyRDD.runJob(rdd.context.sc, mapped.jrdd, partitions, allow_local, file.path) mapped.collect_from_file(file) end
[ "def", "run_job_with_command", "(", "rdd", ",", "partitions", ",", "allow_local", ",", "command", ",", "*", "args", ")", "if", "!", "partitions", ".", "nil?", "&&", "!", "partitions", ".", "is_a?", "(", "Array", ")", "raise", "Spark", "::", "ContextError", ",", "'Partitions must be nil or Array'", "end", "partitions_size", "=", "rdd", ".", "partitions_size", "if", "partitions", ".", "nil?", "partitions", "=", "(", "0", "...", "partitions_size", ")", ".", "to_a", "end", "partitions", ".", "delete_if", "{", "|", "part", "|", "part", ">=", "partitions_size", "}", "partitions", "=", "to_java_array_list", "(", "convert_to_java_int", "(", "partitions", ")", ")", "file", "=", "Tempfile", ".", "new", "(", "'collect'", ",", "temp_dir", ")", "mapped", "=", "rdd", ".", "new_rdd_from_command", "(", "command", ",", "*", "args", ")", "RubyRDD", ".", "runJob", "(", "rdd", ".", "context", ".", "sc", ",", "mapped", ".", "jrdd", ",", "partitions", ",", "allow_local", ",", "file", ".", "path", ")", "mapped", ".", "collect_from_file", "(", "file", ")", "end" ]
Execute the given command on specific set of partitions.
[ "Execute", "the", "given", "command", "on", "specific", "set", "of", "partitions", "." ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/context.rb#L284-L309
train
ondra-m/ruby-spark
lib/spark/stat_counter.rb
Spark.StatCounter.merge
def merge(other) if other.is_a?(Spark::StatCounter) merge_stat_counter(other) elsif other.respond_to?(:each) merge_array(other) else merge_value(other) end self end
ruby
def merge(other) if other.is_a?(Spark::StatCounter) merge_stat_counter(other) elsif other.respond_to?(:each) merge_array(other) else merge_value(other) end self end
[ "def", "merge", "(", "other", ")", "if", "other", ".", "is_a?", "(", "Spark", "::", "StatCounter", ")", "merge_stat_counter", "(", "other", ")", "elsif", "other", ".", "respond_to?", "(", ":each", ")", "merge_array", "(", "other", ")", "else", "merge_value", "(", "other", ")", "end", "self", "end" ]
min of our values
[ "min", "of", "our", "values" ]
d1b9787642fe582dee906de3c6bb9407ded27145
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/stat_counter.rb#L20-L30
train
magnetis/caze
lib/caze.rb
Caze.ClassMethods.raise_use_case_error
def raise_use_case_error(use_case, error) name = error.class.name.split('::').last klass = define_use_case_error(use_case, name) wrapped = klass.new(error.message) wrapped.set_backtrace(error.backtrace) raise wrapped end
ruby
def raise_use_case_error(use_case, error) name = error.class.name.split('::').last klass = define_use_case_error(use_case, name) wrapped = klass.new(error.message) wrapped.set_backtrace(error.backtrace) raise wrapped end
[ "def", "raise_use_case_error", "(", "use_case", ",", "error", ")", "name", "=", "error", ".", "class", ".", "name", ".", "split", "(", "'::'", ")", ".", "last", "klass", "=", "define_use_case_error", "(", "use_case", ",", "name", ")", "wrapped", "=", "klass", ".", "new", "(", "error", ".", "message", ")", "wrapped", ".", "set_backtrace", "(", "error", ".", "backtrace", ")", "raise", "wrapped", "end" ]
This method intends to inject the error inside the context of the use case, so we can identify the use case from it was raised
[ "This", "method", "intends", "to", "inject", "the", "error", "inside", "the", "context", "of", "the", "use", "case", "so", "we", "can", "identify", "the", "use", "case", "from", "it", "was", "raised" ]
04a827f1efa1ad7a5ab91ce7cd2644f92b5621e0
https://github.com/magnetis/caze/blob/04a827f1efa1ad7a5ab91ce7cd2644f92b5621e0/lib/caze.rb#L66-L74
train
mbryzek/schema-evolution-manager
lib/schema-evolution-manager/db.rb
SchemaEvolutionManager.Db.bootstrap!
def bootstrap! scripts = Scripts.new(self, Scripts::BOOTSTRAP_SCRIPTS) dir = File.join(Library.base_dir, "scripts") scripts.each_pending(dir) do |filename, path| psql_file(filename, path) scripts.record_as_run!(filename) end end
ruby
def bootstrap! scripts = Scripts.new(self, Scripts::BOOTSTRAP_SCRIPTS) dir = File.join(Library.base_dir, "scripts") scripts.each_pending(dir) do |filename, path| psql_file(filename, path) scripts.record_as_run!(filename) end end
[ "def", "bootstrap!", "scripts", "=", "Scripts", ".", "new", "(", "self", ",", "Scripts", "::", "BOOTSTRAP_SCRIPTS", ")", "dir", "=", "File", ".", "join", "(", "Library", ".", "base_dir", ",", "\"scripts\"", ")", "scripts", ".", "each_pending", "(", "dir", ")", "do", "|", "filename", ",", "path", "|", "psql_file", "(", "filename", ",", "path", ")", "scripts", ".", "record_as_run!", "(", "filename", ")", "end", "end" ]
Installs schema_evolution_manager. Automatically upgrades schema_evolution_manager.
[ "Installs", "schema_evolution_manager", ".", "Automatically", "upgrades", "schema_evolution_manager", "." ]
eda4f9bd653c2248492b43256daf5e2a41bfff7e
https://github.com/mbryzek/schema-evolution-manager/blob/eda4f9bd653c2248492b43256daf5e2a41bfff7e/lib/schema-evolution-manager/db.rb#L19-L26
train
mbryzek/schema-evolution-manager
lib/schema-evolution-manager/db.rb
SchemaEvolutionManager.Db.psql_command
def psql_command(sql_command) Preconditions.assert_class(sql_command, String) command = "psql --no-align --tuples-only --no-psqlrc --command \"%s\" %s" % [sql_command, @url] Library.system_or_error(command) end
ruby
def psql_command(sql_command) Preconditions.assert_class(sql_command, String) command = "psql --no-align --tuples-only --no-psqlrc --command \"%s\" %s" % [sql_command, @url] Library.system_or_error(command) end
[ "def", "psql_command", "(", "sql_command", ")", "Preconditions", ".", "assert_class", "(", "sql_command", ",", "String", ")", "command", "=", "\"psql --no-align --tuples-only --no-psqlrc --command \\\"%s\\\" %s\"", "%", "[", "sql_command", ",", "@url", "]", "Library", ".", "system_or_error", "(", "command", ")", "end" ]
executes a simple sql command.
[ "executes", "a", "simple", "sql", "command", "." ]
eda4f9bd653c2248492b43256daf5e2a41bfff7e
https://github.com/mbryzek/schema-evolution-manager/blob/eda4f9bd653c2248492b43256daf5e2a41bfff7e/lib/schema-evolution-manager/db.rb#L29-L33
train
mbryzek/schema-evolution-manager
lib/schema-evolution-manager/migration_file.rb
SchemaEvolutionManager.MigrationFile.parse_attribute_values
def parse_attribute_values values = [] each_property do |name, value| values << AttributeValue.new(name, value) end DEFAULTS.each do |default| if values.find { |v| v.attribute.name == default.attribute.name }.nil? values << default end end values end
ruby
def parse_attribute_values values = [] each_property do |name, value| values << AttributeValue.new(name, value) end DEFAULTS.each do |default| if values.find { |v| v.attribute.name == default.attribute.name }.nil? values << default end end values end
[ "def", "parse_attribute_values", "values", "=", "[", "]", "each_property", "do", "|", "name", ",", "value", "|", "values", "<<", "AttributeValue", ".", "new", "(", "name", ",", "value", ")", "end", "DEFAULTS", ".", "each", "do", "|", "default", "|", "if", "values", ".", "find", "{", "|", "v", "|", "v", ".", "attribute", ".", "name", "==", "default", ".", "attribute", ".", "name", "}", ".", "nil?", "values", "<<", "default", "end", "end", "values", "end" ]
Returns a list of AttributeValues from the file itself, including all defaults set by SEM. AttributeValues are defined in comments in the file.
[ "Returns", "a", "list", "of", "AttributeValues", "from", "the", "file", "itself", "including", "all", "defaults", "set", "by", "SEM", ".", "AttributeValues", "are", "defined", "in", "comments", "in", "the", "file", "." ]
eda4f9bd653c2248492b43256daf5e2a41bfff7e
https://github.com/mbryzek/schema-evolution-manager/blob/eda4f9bd653c2248492b43256daf5e2a41bfff7e/lib/schema-evolution-manager/migration_file.rb#L60-L73
train
mbryzek/schema-evolution-manager
lib/schema-evolution-manager/scripts.rb
SchemaEvolutionManager.Scripts.each_pending
def each_pending(dir) files = {} Scripts.all(dir).each do |path| name = File.basename(path) files[name] = path end scripts_previously_run(files.keys).each do |filename| files.delete(filename) end files.keys.sort.each do |filename| ## We have to recheck if this script is still pending. Some ## upgrade scripts may modify the scripts table themselves. This ## is actually useful in cases like when we migrated gilt from ## util_schema => schema_evolution_manager schema if !has_run?(filename) yield filename, files[filename] end end end
ruby
def each_pending(dir) files = {} Scripts.all(dir).each do |path| name = File.basename(path) files[name] = path end scripts_previously_run(files.keys).each do |filename| files.delete(filename) end files.keys.sort.each do |filename| ## We have to recheck if this script is still pending. Some ## upgrade scripts may modify the scripts table themselves. This ## is actually useful in cases like when we migrated gilt from ## util_schema => schema_evolution_manager schema if !has_run?(filename) yield filename, files[filename] end end end
[ "def", "each_pending", "(", "dir", ")", "files", "=", "{", "}", "Scripts", ".", "all", "(", "dir", ")", ".", "each", "do", "|", "path", "|", "name", "=", "File", ".", "basename", "(", "path", ")", "files", "[", "name", "]", "=", "path", "end", "scripts_previously_run", "(", "files", ".", "keys", ")", ".", "each", "do", "|", "filename", "|", "files", ".", "delete", "(", "filename", ")", "end", "files", ".", "keys", ".", "sort", ".", "each", "do", "|", "filename", "|", "if", "!", "has_run?", "(", "filename", ")", "yield", "filename", ",", "files", "[", "filename", "]", "end", "end", "end" ]
For each sql script that needs to be applied to this database, yields a pair of |filename, fullpath| in proper order db = Db.new(host, user, name) scripts = Scripts.new(db) scripts.each_pending do |filename, path| puts filename end
[ "For", "each", "sql", "script", "that", "needs", "to", "be", "applied", "to", "this", "database", "yields", "a", "pair", "of", "|filename", "fullpath|", "in", "proper", "order" ]
eda4f9bd653c2248492b43256daf5e2a41bfff7e
https://github.com/mbryzek/schema-evolution-manager/blob/eda4f9bd653c2248492b43256daf5e2a41bfff7e/lib/schema-evolution-manager/scripts.rb#L41-L61
train
mbryzek/schema-evolution-manager
lib/schema-evolution-manager/scripts.rb
SchemaEvolutionManager.Scripts.has_run?
def has_run?(filename) if @db.schema_schema_evolution_manager_exists? query = "select count(*) from %s.%s where filename = '%s'" % [Db.schema_name, @table_name, filename] @db.psql_command(query).to_i > 0 else false end end
ruby
def has_run?(filename) if @db.schema_schema_evolution_manager_exists? query = "select count(*) from %s.%s where filename = '%s'" % [Db.schema_name, @table_name, filename] @db.psql_command(query).to_i > 0 else false end end
[ "def", "has_run?", "(", "filename", ")", "if", "@db", ".", "schema_schema_evolution_manager_exists?", "query", "=", "\"select count(*) from %s.%s where filename = '%s'\"", "%", "[", "Db", ".", "schema_name", ",", "@table_name", ",", "filename", "]", "@db", ".", "psql_command", "(", "query", ")", ".", "to_i", ">", "0", "else", "false", "end", "end" ]
True if this script has already been applied to the db. False otherwise.
[ "True", "if", "this", "script", "has", "already", "been", "applied", "to", "the", "db", ".", "False", "otherwise", "." ]
eda4f9bd653c2248492b43256daf5e2a41bfff7e
https://github.com/mbryzek/schema-evolution-manager/blob/eda4f9bd653c2248492b43256daf5e2a41bfff7e/lib/schema-evolution-manager/scripts.rb#L65-L72
train
mbryzek/schema-evolution-manager
lib/schema-evolution-manager/scripts.rb
SchemaEvolutionManager.Scripts.record_as_run!
def record_as_run!(filename) Preconditions.check_state(filename.match(/^\d\d\d\d\d\d+\-\d\d\d\d\d\d\.sql$/), "Invalid filename[#{filename}]. Must be like: 20120503-173242.sql") command = "insert into %s.%s (filename) select '%s' where not exists (select 1 from %s.%s where filename = '%s')" % [Db.schema_name, @table_name, filename, Db.schema_name, @table_name, filename] @db.psql_command(command) end
ruby
def record_as_run!(filename) Preconditions.check_state(filename.match(/^\d\d\d\d\d\d+\-\d\d\d\d\d\d\.sql$/), "Invalid filename[#{filename}]. Must be like: 20120503-173242.sql") command = "insert into %s.%s (filename) select '%s' where not exists (select 1 from %s.%s where filename = '%s')" % [Db.schema_name, @table_name, filename, Db.schema_name, @table_name, filename] @db.psql_command(command) end
[ "def", "record_as_run!", "(", "filename", ")", "Preconditions", ".", "check_state", "(", "filename", ".", "match", "(", "/", "\\d", "\\d", "\\d", "\\d", "\\d", "\\d", "\\-", "\\d", "\\d", "\\d", "\\d", "\\d", "\\d", "\\.", "/", ")", ",", "\"Invalid filename[#{filename}]. Must be like: 20120503-173242.sql\"", ")", "command", "=", "\"insert into %s.%s (filename) select '%s' where not exists (select 1 from %s.%s where filename = '%s')\"", "%", "[", "Db", ".", "schema_name", ",", "@table_name", ",", "filename", ",", "Db", ".", "schema_name", ",", "@table_name", ",", "filename", "]", "@db", ".", "psql_command", "(", "command", ")", "end" ]
Inserts a record to indiciate that we have loaded the specified file.
[ "Inserts", "a", "record", "to", "indiciate", "that", "we", "have", "loaded", "the", "specified", "file", "." ]
eda4f9bd653c2248492b43256daf5e2a41bfff7e
https://github.com/mbryzek/schema-evolution-manager/blob/eda4f9bd653c2248492b43256daf5e2a41bfff7e/lib/schema-evolution-manager/scripts.rb#L75-L80
train
mbryzek/schema-evolution-manager
lib/schema-evolution-manager/scripts.rb
SchemaEvolutionManager.Scripts.scripts_previously_run
def scripts_previously_run(scripts) if scripts.empty? || [email protected]_schema_evolution_manager_exists? [] else sql = "select filename from %s.%s where filename in (%s)" % [Db.schema_name, @table_name, "'" + scripts.join("', '") + "'"] @db.psql_command(sql).strip.split end end
ruby
def scripts_previously_run(scripts) if scripts.empty? || [email protected]_schema_evolution_manager_exists? [] else sql = "select filename from %s.%s where filename in (%s)" % [Db.schema_name, @table_name, "'" + scripts.join("', '") + "'"] @db.psql_command(sql).strip.split end end
[ "def", "scripts_previously_run", "(", "scripts", ")", "if", "scripts", ".", "empty?", "||", "!", "@db", ".", "schema_schema_evolution_manager_exists?", "[", "]", "else", "sql", "=", "\"select filename from %s.%s where filename in (%s)\"", "%", "[", "Db", ".", "schema_name", ",", "@table_name", ",", "\"'\"", "+", "scripts", ".", "join", "(", "\"', '\"", ")", "+", "\"'\"", "]", "@db", ".", "psql_command", "(", "sql", ")", ".", "strip", ".", "split", "end", "end" ]
Fetch the list of scripts that have already been applied to this database.
[ "Fetch", "the", "list", "of", "scripts", "that", "have", "already", "been", "applied", "to", "this", "database", "." ]
eda4f9bd653c2248492b43256daf5e2a41bfff7e
https://github.com/mbryzek/schema-evolution-manager/blob/eda4f9bd653c2248492b43256daf5e2a41bfff7e/lib/schema-evolution-manager/scripts.rb#L85-L92
train
mbryzek/schema-evolution-manager
lib/schema-evolution-manager/install_template.rb
SchemaEvolutionManager.InstallTemplate.generate
def generate template = Template.new template.add('timestamp', Time.now.to_s) template.add('lib_dir', @lib_dir) template.add('bin_dir', @bin_dir) template.parse(TEMPLATE) end
ruby
def generate template = Template.new template.add('timestamp', Time.now.to_s) template.add('lib_dir', @lib_dir) template.add('bin_dir', @bin_dir) template.parse(TEMPLATE) end
[ "def", "generate", "template", "=", "Template", ".", "new", "template", ".", "add", "(", "'timestamp'", ",", "Time", ".", "now", ".", "to_s", ")", "template", ".", "add", "(", "'lib_dir'", ",", "@lib_dir", ")", "template", ".", "add", "(", "'bin_dir'", ",", "@bin_dir", ")", "template", ".", "parse", "(", "TEMPLATE", ")", "end" ]
Generates the actual contents of the install file
[ "Generates", "the", "actual", "contents", "of", "the", "install", "file" ]
eda4f9bd653c2248492b43256daf5e2a41bfff7e
https://github.com/mbryzek/schema-evolution-manager/blob/eda4f9bd653c2248492b43256daf5e2a41bfff7e/lib/schema-evolution-manager/install_template.rb#L12-L18
train
yohasebe/wp2txt
lib/wp2txt.rb
Wp2txt.Runner.fill_buffer
def fill_buffer while true do begin new_lines = @file_pointer.read(10485760) rescue => e return nil end return nil unless new_lines # temp_buf is filled with text split by "\n" temp_buf = [] ss = StringScanner.new(new_lines) while ss.scan(/.*?\n/m) temp_buf << ss[0] end temp_buf << ss.rest unless ss.eos? new_first_line = temp_buf.shift if new_first_line[-1, 1] == "\n" # new_first_line.index("\n") @buffer.last << new_first_line @buffer << "" else @buffer.last << new_first_line end @buffer += temp_buf unless temp_buf.empty? if @buffer.last[-1, 1] == "\n" # @buffer.last.index("\n") @buffer << "" end break if @buffer.size > 1 end return true end
ruby
def fill_buffer while true do begin new_lines = @file_pointer.read(10485760) rescue => e return nil end return nil unless new_lines # temp_buf is filled with text split by "\n" temp_buf = [] ss = StringScanner.new(new_lines) while ss.scan(/.*?\n/m) temp_buf << ss[0] end temp_buf << ss.rest unless ss.eos? new_first_line = temp_buf.shift if new_first_line[-1, 1] == "\n" # new_first_line.index("\n") @buffer.last << new_first_line @buffer << "" else @buffer.last << new_first_line end @buffer += temp_buf unless temp_buf.empty? if @buffer.last[-1, 1] == "\n" # @buffer.last.index("\n") @buffer << "" end break if @buffer.size > 1 end return true end
[ "def", "fill_buffer", "while", "true", "do", "begin", "new_lines", "=", "@file_pointer", ".", "read", "(", "10485760", ")", "rescue", "=>", "e", "return", "nil", "end", "return", "nil", "unless", "new_lines", "temp_buf", "=", "[", "]", "ss", "=", "StringScanner", ".", "new", "(", "new_lines", ")", "while", "ss", ".", "scan", "(", "/", "\\n", "/m", ")", "temp_buf", "<<", "ss", "[", "0", "]", "end", "temp_buf", "<<", "ss", ".", "rest", "unless", "ss", ".", "eos?", "new_first_line", "=", "temp_buf", ".", "shift", "if", "new_first_line", "[", "-", "1", ",", "1", "]", "==", "\"\\n\"", "@buffer", ".", "last", "<<", "new_first_line", "@buffer", "<<", "\"\"", "else", "@buffer", ".", "last", "<<", "new_first_line", "end", "@buffer", "+=", "temp_buf", "unless", "temp_buf", ".", "empty?", "if", "@buffer", ".", "last", "[", "-", "1", ",", "1", "]", "==", "\"\\n\"", "@buffer", "<<", "\"\"", "end", "break", "if", "@buffer", ".", "size", ">", "1", "end", "return", "true", "end" ]
read text data from bz2 compressed file by 1 megabyte
[ "read", "text", "data", "from", "bz2", "compressed", "file", "by", "1", "megabyte" ]
0938ddd3b076611ce37c8f9decc58cf97589c06c
https://github.com/yohasebe/wp2txt/blob/0938ddd3b076611ce37c8f9decc58cf97589c06c/lib/wp2txt.rb#L146-L177
train
chrisvfritz/language_filter
lib/language_filter.rb
LanguageFilter.Filter.replace
def replace(word) case @replacement when :vowels then word.gsub(/[aeiou]/i, '*') when :stars then '*' * word.size when :nonconsonants then word.gsub(/[^bcdfghjklmnpqrstvwxyz]/i, '*') when :default, :garbled then '$@!#%' else raise LanguageFilter::UnknownReplacement.new("#{@replacement} is not a known replacement type.") end end
ruby
def replace(word) case @replacement when :vowels then word.gsub(/[aeiou]/i, '*') when :stars then '*' * word.size when :nonconsonants then word.gsub(/[^bcdfghjklmnpqrstvwxyz]/i, '*') when :default, :garbled then '$@!#%' else raise LanguageFilter::UnknownReplacement.new("#{@replacement} is not a known replacement type.") end end
[ "def", "replace", "(", "word", ")", "case", "@replacement", "when", ":vowels", "then", "word", ".", "gsub", "(", "/", "/i", ",", "'*'", ")", "when", ":stars", "then", "'*'", "*", "word", ".", "size", "when", ":nonconsonants", "then", "word", ".", "gsub", "(", "/", "/i", ",", "'*'", ")", "when", ":default", ",", ":garbled", "then", "'$@!#%'", "else", "raise", "LanguageFilter", "::", "UnknownReplacement", ".", "new", "(", "\"#{@replacement} is not a known replacement type.\"", ")", "end", "end" ]
This was moved to private because users should just use sanitize for any content
[ "This", "was", "moved", "to", "private", "because", "users", "should", "just", "use", "sanitize", "for", "any", "content" ]
084fe0654e4cb18e0a145fad1006dcf98bf4011c
https://github.com/chrisvfritz/language_filter/blob/084fe0654e4cb18e0a145fad1006dcf98bf4011c/lib/language_filter.rb#L258-L266
train
benbalter/jekyll-readme-index
lib/jekyll/static_file_ext.rb
Jekyll.StaticFile.to_page
def to_page page = Jekyll::Page.new(@site, @base, @dir, @name) page.data["permalink"] = File.dirname(url) + "/" page end
ruby
def to_page page = Jekyll::Page.new(@site, @base, @dir, @name) page.data["permalink"] = File.dirname(url) + "/" page end
[ "def", "to_page", "page", "=", "Jekyll", "::", "Page", ".", "new", "(", "@site", ",", "@base", ",", "@dir", ",", "@name", ")", "page", ".", "data", "[", "\"permalink\"", "]", "=", "File", ".", "dirname", "(", "url", ")", "+", "\"/\"", "page", "end" ]
Convert this static file to a Page
[ "Convert", "this", "static", "file", "to", "a", "Page" ]
19897e9250c3e410c5fc461b6f5737902bb7208f
https://github.com/benbalter/jekyll-readme-index/blob/19897e9250c3e410c5fc461b6f5737902bb7208f/lib/jekyll/static_file_ext.rb#L6-L10
train
sue445/apple_system_status
lib/apple_system_status/crawler.rb
AppleSystemStatus.Crawler.perform
def perform(country: nil, title: nil) @session.visit(apple_url(country)) response = { title: @session.find(".section-date .date-copy").text.strip, services: [], } MAX_RETRY_COUNT.times do services = fetch_services if services.empty? # wait until the page is fully loaded sleep 1 else response[:services] = services break end end raise "Not found services" if response[:services].empty? unless self.class.blank_string?(title) response[:services].select! { |service| service[:title] == title } end response[:services].sort_by! { |service| service[:title] } response end
ruby
def perform(country: nil, title: nil) @session.visit(apple_url(country)) response = { title: @session.find(".section-date .date-copy").text.strip, services: [], } MAX_RETRY_COUNT.times do services = fetch_services if services.empty? # wait until the page is fully loaded sleep 1 else response[:services] = services break end end raise "Not found services" if response[:services].empty? unless self.class.blank_string?(title) response[:services].select! { |service| service[:title] == title } end response[:services].sort_by! { |service| service[:title] } response end
[ "def", "perform", "(", "country", ":", "nil", ",", "title", ":", "nil", ")", "@session", ".", "visit", "(", "apple_url", "(", "country", ")", ")", "response", "=", "{", "title", ":", "@session", ".", "find", "(", "\".section-date .date-copy\"", ")", ".", "text", ".", "strip", ",", "services", ":", "[", "]", ",", "}", "MAX_RETRY_COUNT", ".", "times", "do", "services", "=", "fetch_services", "if", "services", ".", "empty?", "sleep", "1", "else", "response", "[", ":services", "]", "=", "services", "break", "end", "end", "raise", "\"Not found services\"", "if", "response", "[", ":services", "]", ".", "empty?", "unless", "self", ".", "class", ".", "blank_string?", "(", "title", ")", "response", "[", ":services", "]", ".", "select!", "{", "|", "service", "|", "service", "[", ":title", "]", "==", "title", "}", "end", "response", "[", ":services", "]", ".", "sort_by!", "{", "|", "service", "|", "service", "[", ":title", "]", "}", "response", "end" ]
crawl apple system status page @param country [String] country code. (e.g. jp, ca, fr. default. us) @param title [String] If specified, narrow the service title @return [Hash] @example response format { title: , services: [ { title: , description: , status: } ] }
[ "crawl", "apple", "system", "status", "page" ]
9675c02e2157081f7e7a607e740430c67b0a603a
https://github.com/sue445/apple_system_status/blob/9675c02e2157081f7e7a607e740430c67b0a603a/lib/apple_system_status/crawler.rb#L55-L84
train
14113/fio_api
lib/base/list.rb
FioAPI.List.fetch_and_deserialize_response
def fetch_and_deserialize_response(path) self.request = FioAPI::Request.get(path, parser: ListResponseDeserializer) self.response = request.parsed_response request end
ruby
def fetch_and_deserialize_response(path) self.request = FioAPI::Request.get(path, parser: ListResponseDeserializer) self.response = request.parsed_response request end
[ "def", "fetch_and_deserialize_response", "(", "path", ")", "self", ".", "request", "=", "FioAPI", "::", "Request", ".", "get", "(", "path", ",", "parser", ":", "ListResponseDeserializer", ")", "self", ".", "response", "=", "request", ".", "parsed_response", "request", "end" ]
Create request object ot provided uri and instantiate list deserializer. Request uri and deserialize response to response object with account info and transactions list. == Parameters: args:: Parts of uri == Returns: List insatnce with account info and transactions list
[ "Create", "request", "object", "ot", "provided", "uri", "and", "instantiate", "list", "deserializer", ".", "Request", "uri", "and", "deserialize", "response", "to", "response", "object", "with", "account", "info", "and", "transactions", "list", "." ]
f982c27332ef629929aff03f93e8df9c7516414c
https://github.com/14113/fio_api/blob/f982c27332ef629929aff03f93e8df9c7516414c/lib/base/list.rb#L88-L92
train
archangel/archangel
app/helpers/archangel/flash_helper.rb
Archangel.FlashHelper.flash_class_for
def flash_class_for(flash_type) flash_type = flash_type.to_s.downcase.parameterize { success: "success", error: "danger", alert: "warning", notice: "info" }.fetch(flash_type.to_sym, flash_type) end
ruby
def flash_class_for(flash_type) flash_type = flash_type.to_s.downcase.parameterize { success: "success", error: "danger", alert: "warning", notice: "info" }.fetch(flash_type.to_sym, flash_type) end
[ "def", "flash_class_for", "(", "flash_type", ")", "flash_type", "=", "flash_type", ".", "to_s", ".", "downcase", ".", "parameterize", "{", "success", ":", "\"success\"", ",", "error", ":", "\"danger\"", ",", "alert", ":", "\"warning\"", ",", "notice", ":", "\"info\"", "}", ".", "fetch", "(", "flash_type", ".", "to_sym", ",", "flash_type", ")", "end" ]
Converts Rails flash message type to Bootstrap flash message type @param flash_type [String,Symbol] the flash message type @return [String] flash message type
[ "Converts", "Rails", "flash", "message", "type", "to", "Bootstrap", "flash", "message", "type" ]
f84a9e3a0003f64a6057f8f4db1e05163a7d43b6
https://github.com/archangel/archangel/blob/f84a9e3a0003f64a6057f8f4db1e05163a7d43b6/app/helpers/archangel/flash_helper.rb#L14-L20
train
artsy/momentum
lib/momentum/opsworks.rb
Momentum::OpsWorks.Deployer.execute_recipe!
def execute_recipe!(stack_name, layer, recipe, app_name = Momentum.config[:app_base_name]) raise "No recipe provided" unless recipe stack = Momentum::OpsWorks.get_stack(@ow, stack_name) app = Momentum::OpsWorks.get_app(@ow, stack, app_name) layer_names = layer ? [layer] : Momentum.config[:app_layers] layers = Momentum::OpsWorks.get_layers(@ow, stack, layer_names) instance_ids = layers.inject([]) { |ids, l| ids + Momentum::OpsWorks.get_online_instance_ids(@ow, layer_id: l[:layer_id]) } raise 'No online instances found!' if instance_ids.empty? @ow.create_deployment( stack_id: stack[:stack_id], app_id: app[:app_id], command: { name: 'execute_recipes', args: { 'recipes' => [recipe.to_s] } }, instance_ids: instance_ids ) end
ruby
def execute_recipe!(stack_name, layer, recipe, app_name = Momentum.config[:app_base_name]) raise "No recipe provided" unless recipe stack = Momentum::OpsWorks.get_stack(@ow, stack_name) app = Momentum::OpsWorks.get_app(@ow, stack, app_name) layer_names = layer ? [layer] : Momentum.config[:app_layers] layers = Momentum::OpsWorks.get_layers(@ow, stack, layer_names) instance_ids = layers.inject([]) { |ids, l| ids + Momentum::OpsWorks.get_online_instance_ids(@ow, layer_id: l[:layer_id]) } raise 'No online instances found!' if instance_ids.empty? @ow.create_deployment( stack_id: stack[:stack_id], app_id: app[:app_id], command: { name: 'execute_recipes', args: { 'recipes' => [recipe.to_s] } }, instance_ids: instance_ids ) end
[ "def", "execute_recipe!", "(", "stack_name", ",", "layer", ",", "recipe", ",", "app_name", "=", "Momentum", ".", "config", "[", ":app_base_name", "]", ")", "raise", "\"No recipe provided\"", "unless", "recipe", "stack", "=", "Momentum", "::", "OpsWorks", ".", "get_stack", "(", "@ow", ",", "stack_name", ")", "app", "=", "Momentum", "::", "OpsWorks", ".", "get_app", "(", "@ow", ",", "stack", ",", "app_name", ")", "layer_names", "=", "layer", "?", "[", "layer", "]", ":", "Momentum", ".", "config", "[", ":app_layers", "]", "layers", "=", "Momentum", "::", "OpsWorks", ".", "get_layers", "(", "@ow", ",", "stack", ",", "layer_names", ")", "instance_ids", "=", "layers", ".", "inject", "(", "[", "]", ")", "{", "|", "ids", ",", "l", "|", "ids", "+", "Momentum", "::", "OpsWorks", ".", "get_online_instance_ids", "(", "@ow", ",", "layer_id", ":", "l", "[", ":layer_id", "]", ")", "}", "raise", "'No online instances found!'", "if", "instance_ids", ".", "empty?", "@ow", ".", "create_deployment", "(", "stack_id", ":", "stack", "[", ":stack_id", "]", ",", "app_id", ":", "app", "[", ":app_id", "]", ",", "command", ":", "{", "name", ":", "'execute_recipes'", ",", "args", ":", "{", "'recipes'", "=>", "[", "recipe", ".", "to_s", "]", "}", "}", ",", "instance_ids", ":", "instance_ids", ")", "end" ]
wait up to 15 minutes
[ "wait", "up", "to", "15", "minutes" ]
61b9926a783c3a3fc4f105334d1e291273132392
https://github.com/artsy/momentum/blob/61b9926a783c3a3fc4f105334d1e291273132392/lib/momentum/opsworks.rb#L68-L87
train
fixrb/fix
lib/fix/on.rb
Fix.On.it
def it(*, &spec) i = It.new(described, challenges, helpers) result = i.verify(&spec) if configuration.fetch(:verbose, true) print result.to_char(configuration.fetch(:color, false)) end results << result end
ruby
def it(*, &spec) i = It.new(described, challenges, helpers) result = i.verify(&spec) if configuration.fetch(:verbose, true) print result.to_char(configuration.fetch(:color, false)) end results << result end
[ "def", "it", "(", "*", ",", "&", "spec", ")", "i", "=", "It", ".", "new", "(", "described", ",", "challenges", ",", "helpers", ")", "result", "=", "i", ".", "verify", "(", "&", "spec", ")", "if", "configuration", ".", "fetch", "(", ":verbose", ",", "true", ")", "print", "result", ".", "to_char", "(", "configuration", ".", "fetch", "(", ":color", ",", "false", ")", ")", "end", "results", "<<", "result", "end" ]
Add it method to the DSL. @api public @example It must eql "FOO" it { MUST equal 'FOO' } @param spec [Proc] A spec to compare against the computed actual value. @return [Array] List of results.
[ "Add", "it", "method", "to", "the", "DSL", "." ]
7023dce0c28eb92db7a2dbafe56e81246f215e31
https://github.com/fixrb/fix/blob/7023dce0c28eb92db7a2dbafe56e81246f215e31/lib/fix/on.rb#L62-L72
train
fixrb/fix
lib/fix/on.rb
Fix.On.on
def on(method_name, *args, &block) o = On.new(described, results, (challenges + [Defi.send(method_name, *args)]), helpers.dup, configuration) o.instance_eval(&block) end
ruby
def on(method_name, *args, &block) o = On.new(described, results, (challenges + [Defi.send(method_name, *args)]), helpers.dup, configuration) o.instance_eval(&block) end
[ "def", "on", "(", "method_name", ",", "*", "args", ",", "&", "block", ")", "o", "=", "On", ".", "new", "(", "described", ",", "results", ",", "(", "challenges", "+", "[", "Defi", ".", "send", "(", "method_name", ",", "*", "args", ")", "]", ")", ",", "helpers", ".", "dup", ",", "configuration", ")", "o", ".", "instance_eval", "(", "&", "block", ")", "end" ]
Add on method to the DSL. @api public @example On +2, it must equal 44. on(:+, 2) do it { MUST equal 44 } end @param method_name [Symbol] The identifier of a method. @param args [Array] A list of arguments. @param block [Proc] A spec to compare against the computed value. @return [Array] List of results.
[ "Add", "on", "method", "to", "the", "DSL", "." ]
7023dce0c28eb92db7a2dbafe56e81246f215e31
https://github.com/fixrb/fix/blob/7023dce0c28eb92db7a2dbafe56e81246f215e31/lib/fix/on.rb#L88-L96
train
fixrb/fix
lib/fix/on.rb
Fix.On.context
def context(*, &block) o = On.new(described, [], challenges, helpers.dup, configuration) results.concat(Aw.fork! { o.instance_eval(&block) }) end
ruby
def context(*, &block) o = On.new(described, [], challenges, helpers.dup, configuration) results.concat(Aw.fork! { o.instance_eval(&block) }) end
[ "def", "context", "(", "*", ",", "&", "block", ")", "o", "=", "On", ".", "new", "(", "described", ",", "[", "]", ",", "challenges", ",", "helpers", ".", "dup", ",", "configuration", ")", "results", ".", "concat", "(", "Aw", ".", "fork!", "{", "o", ".", "instance_eval", "(", "&", "block", ")", "}", ")", "end" ]
Add context method to the DSL, to build an isolated scope. @api public @example Context when logged in. context 'when logged in' do it { MUST equal 200 } end @param block [Proc] A block of specs to test in isolation. @return [Array] List of results.
[ "Add", "context", "method", "to", "the", "DSL", "to", "build", "an", "isolated", "scope", "." ]
7023dce0c28eb92db7a2dbafe56e81246f215e31
https://github.com/fixrb/fix/blob/7023dce0c28eb92db7a2dbafe56e81246f215e31/lib/fix/on.rb#L127-L135
train
aastronautss/emittance
lib/emittance/watcher.rb
Emittance.Watcher.watch
def watch(identifier, callback_method = nil, **params, &callback) if callback _dispatcher(params).register identifier, params, &callback else _dispatcher(params).register_method_call identifier, self, callback_method, params end end
ruby
def watch(identifier, callback_method = nil, **params, &callback) if callback _dispatcher(params).register identifier, params, &callback else _dispatcher(params).register_method_call identifier, self, callback_method, params end end
[ "def", "watch", "(", "identifier", ",", "callback_method", "=", "nil", ",", "**", "params", ",", "&", "callback", ")", "if", "callback", "_dispatcher", "(", "params", ")", ".", "register", "identifier", ",", "params", ",", "&", "callback", "else", "_dispatcher", "(", "params", ")", ".", "register_method_call", "identifier", ",", "self", ",", "callback_method", ",", "params", "end", "end" ]
Watch for an event, identified by its class' identifier. If a callback method is provided, then it will call that method on the caller of +watch+ when the event happens. Otherwise, it will run the callback block. @param identifier [Symbol] the event's identifier @param callback_method [Symbol] one option for adding a callback--the method on the object to call when the event fires @param params [Hash] any parameters related to the registration of a watcher @param callback [Block] the other option for adding a callback--the block you wish to be executed when the event fires @return [Proc] the block that will run when the event fires
[ "Watch", "for", "an", "event", "identified", "by", "its", "class", "identifier", ".", "If", "a", "callback", "method", "is", "provided", "then", "it", "will", "call", "that", "method", "on", "the", "caller", "of", "+", "watch", "+", "when", "the", "event", "happens", ".", "Otherwise", "it", "will", "run", "the", "callback", "block", "." ]
3ff045c4b3f35c1ca7743bc09bcb1fff7934204c
https://github.com/aastronautss/emittance/blob/3ff045c4b3f35c1ca7743bc09bcb1fff7934204c/lib/emittance/watcher.rb#L18-L24
train
archangel/archangel
app/services/archangel/render_service.rb
Archangel.RenderService.call
def call liquid = ::Liquid::Template.parse(template) liquid.send(:render, stringify_assigns, liquid_options).html_safe end
ruby
def call liquid = ::Liquid::Template.parse(template) liquid.send(:render, stringify_assigns, liquid_options).html_safe end
[ "def", "call", "liquid", "=", "::", "Liquid", "::", "Template", ".", "parse", "(", "template", ")", "liquid", ".", "send", "(", ":render", ",", "stringify_assigns", ",", "liquid_options", ")", ".", "html_safe", "end" ]
Render the Liquid content @return [String] the rendered content
[ "Render", "the", "Liquid", "content" ]
f84a9e3a0003f64a6057f8f4db1e05163a7d43b6
https://github.com/archangel/archangel/blob/f84a9e3a0003f64a6057f8f4db1e05163a7d43b6/app/services/archangel/render_service.rb#L59-L62
train
archangel/archangel
app/helpers/archangel/application_helper.rb
Archangel.ApplicationHelper.frontend_resource_path
def frontend_resource_path(resource) permalink_path = proc do |permalink| archangel.frontend_page_path(permalink).gsub("%2F", "/") end return permalink_path.call(resource) unless resource.class == Page return archangel.frontend_root_path if resource.homepage? permalink_path.call(resource.permalink) end
ruby
def frontend_resource_path(resource) permalink_path = proc do |permalink| archangel.frontend_page_path(permalink).gsub("%2F", "/") end return permalink_path.call(resource) unless resource.class == Page return archangel.frontend_root_path if resource.homepage? permalink_path.call(resource.permalink) end
[ "def", "frontend_resource_path", "(", "resource", ")", "permalink_path", "=", "proc", "do", "|", "permalink", "|", "archangel", ".", "frontend_page_path", "(", "permalink", ")", ".", "gsub", "(", "\"%2F\"", ",", "\"/\"", ")", "end", "return", "permalink_path", ".", "call", "(", "resource", ")", "unless", "resource", ".", "class", "==", "Page", "return", "archangel", ".", "frontend_root_path", "if", "resource", ".", "homepage?", "permalink_path", ".", "call", "(", "resource", ".", "permalink", ")", "end" ]
Frontend resource permalink. Same as `frontend_page_path` except it prints out nested resources in a nice way. Example <%= frontend_resource_path('foo/bar') %> #=> /foo/bar <%= frontend_resource_path(@page) %> #=> /foo/bar @return [String] frontend resource permalink
[ "Frontend", "resource", "permalink", "." ]
f84a9e3a0003f64a6057f8f4db1e05163a7d43b6
https://github.com/archangel/archangel/blob/f84a9e3a0003f64a6057f8f4db1e05163a7d43b6/app/helpers/archangel/application_helper.rb#L20-L29
train
YotpoLtd/seoshop-api
lib/seoshop-api/client.rb
Seoshop.Client.get
def get(url, params = {}) params = params.inject({}){|memo,(k,v)| memo[k.to_s] = v; memo} preform(url, :get, params: params) do return connection.get(url, params) end end
ruby
def get(url, params = {}) params = params.inject({}){|memo,(k,v)| memo[k.to_s] = v; memo} preform(url, :get, params: params) do return connection.get(url, params) end end
[ "def", "get", "(", "url", ",", "params", "=", "{", "}", ")", "params", "=", "params", ".", "inject", "(", "{", "}", ")", "{", "|", "memo", ",", "(", "k", ",", "v", ")", "|", "memo", "[", "k", ".", "to_s", "]", "=", "v", ";", "memo", "}", "preform", "(", "url", ",", ":get", ",", "params", ":", "params", ")", "do", "return", "connection", ".", "get", "(", "url", ",", "params", ")", "end", "end" ]
Does a GET request to the url with the params @param url [String] the relative path in the Seoshop API @param params [Hash] the url params that should be passed in the request
[ "Does", "a", "GET", "request", "to", "the", "url", "with", "the", "params" ]
7b1ea990824222be8c4543384c97b5640b97e433
https://github.com/YotpoLtd/seoshop-api/blob/7b1ea990824222be8c4543384c97b5640b97e433/lib/seoshop-api/client.rb#L73-L78
train
YotpoLtd/seoshop-api
lib/seoshop-api/client.rb
Seoshop.Client.post
def post(url, params) params = convert_hash_keys(params) preform(url, :post, params: params) do return connection.post(url, params) end end
ruby
def post(url, params) params = convert_hash_keys(params) preform(url, :post, params: params) do return connection.post(url, params) end end
[ "def", "post", "(", "url", ",", "params", ")", "params", "=", "convert_hash_keys", "(", "params", ")", "preform", "(", "url", ",", ":post", ",", "params", ":", "params", ")", "do", "return", "connection", ".", "post", "(", "url", ",", "params", ")", "end", "end" ]
Does a POST request to the url with the params @param url [String] the relative path in the Seoshop API @param params [Hash] the body of the request
[ "Does", "a", "POST", "request", "to", "the", "url", "with", "the", "params" ]
7b1ea990824222be8c4543384c97b5640b97e433
https://github.com/YotpoLtd/seoshop-api/blob/7b1ea990824222be8c4543384c97b5640b97e433/lib/seoshop-api/client.rb#L85-L90
train
YotpoLtd/seoshop-api
lib/seoshop-api/client.rb
Seoshop.Client.put
def put(url, params) params = convert_hash_keys(params) preform(url, :put, params: params) do return connection.put(url, params) end end
ruby
def put(url, params) params = convert_hash_keys(params) preform(url, :put, params: params) do return connection.put(url, params) end end
[ "def", "put", "(", "url", ",", "params", ")", "params", "=", "convert_hash_keys", "(", "params", ")", "preform", "(", "url", ",", ":put", ",", "params", ":", "params", ")", "do", "return", "connection", ".", "put", "(", "url", ",", "params", ")", "end", "end" ]
Does a PUT request to the url with the params @param url [String] the relative path in the Seoshop API @param params [Hash] the body of the request
[ "Does", "a", "PUT", "request", "to", "the", "url", "with", "the", "params" ]
7b1ea990824222be8c4543384c97b5640b97e433
https://github.com/YotpoLtd/seoshop-api/blob/7b1ea990824222be8c4543384c97b5640b97e433/lib/seoshop-api/client.rb#L97-L102
train
archangel/archangel
lib/archangel/liquid_view.rb
Archangel.LiquidView.render
def render(template, local_assigns = {}) default_controller.headers["Content-Type"] ||= "text/html; charset=utf-8" assigns = default_assigns(local_assigns) options = { registers: default_registers } Archangel::RenderService.call(template, assigns, options) end
ruby
def render(template, local_assigns = {}) default_controller.headers["Content-Type"] ||= "text/html; charset=utf-8" assigns = default_assigns(local_assigns) options = { registers: default_registers } Archangel::RenderService.call(template, assigns, options) end
[ "def", "render", "(", "template", ",", "local_assigns", "=", "{", "}", ")", "default_controller", ".", "headers", "[", "\"Content-Type\"", "]", "||=", "\"text/html; charset=utf-8\"", "assigns", "=", "default_assigns", "(", "local_assigns", ")", "options", "=", "{", "registers", ":", "default_registers", "}", "Archangel", "::", "RenderService", ".", "call", "(", "template", ",", "assigns", ",", "options", ")", "end" ]
Render Liquid content @param template [String] the content @param local_assigns [Hash] the local assigned variables @return [String] the rendered content
[ "Render", "Liquid", "content" ]
f84a9e3a0003f64a6057f8f4db1e05163a7d43b6
https://github.com/archangel/archangel/blob/f84a9e3a0003f64a6057f8f4db1e05163a7d43b6/lib/archangel/liquid_view.rb#L35-L42
train
inukshuk/bibtex-ruby
lib/bibtex/lexer.rb
BibTeX.Lexer.push
def push(value) case value[0] when :CONTENT, :STRING_LITERAL value[1].gsub!(/\n\s*/, ' ') if strip_line_breaks? if [email protected]? && value[0] == @stack[-1][0] @stack[-1][1] << value[1] else @stack.push(value) end when :ERROR @stack.push(value) if @include_errors leave_object when :META_CONTENT @stack.push(value) if @include_meta_content else @stack.push(value) end self end
ruby
def push(value) case value[0] when :CONTENT, :STRING_LITERAL value[1].gsub!(/\n\s*/, ' ') if strip_line_breaks? if [email protected]? && value[0] == @stack[-1][0] @stack[-1][1] << value[1] else @stack.push(value) end when :ERROR @stack.push(value) if @include_errors leave_object when :META_CONTENT @stack.push(value) if @include_meta_content else @stack.push(value) end self end
[ "def", "push", "(", "value", ")", "case", "value", "[", "0", "]", "when", ":CONTENT", ",", ":STRING_LITERAL", "value", "[", "1", "]", ".", "gsub!", "(", "/", "\\n", "\\s", "/", ",", "' '", ")", "if", "strip_line_breaks?", "if", "!", "@stack", ".", "empty?", "&&", "value", "[", "0", "]", "==", "@stack", "[", "-", "1", "]", "[", "0", "]", "@stack", "[", "-", "1", "]", "[", "1", "]", "<<", "value", "[", "1", "]", "else", "@stack", ".", "push", "(", "value", ")", "end", "when", ":ERROR", "@stack", ".", "push", "(", "value", ")", "if", "@include_errors", "leave_object", "when", ":META_CONTENT", "@stack", ".", "push", "(", "value", ")", "if", "@include_meta_content", "else", "@stack", ".", "push", "(", "value", ")", "end", "self", "end" ]
Pushes a value onto the parse stack. Returns the Lexer.
[ "Pushes", "a", "value", "onto", "the", "parse", "stack", ".", "Returns", "the", "Lexer", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/lexer.rb#L145-L165
train
inukshuk/bibtex-ruby
lib/bibtex/lexer.rb
BibTeX.Lexer.analyse
def analyse(string = nil) raise(ArgumentError, 'Lexer: failed to start analysis: no source given!') unless string || @scanner self.data = string || @scanner.string until @scanner.eos? send("parse_#{MODE[@mode]}") end push([false, '$end']) end
ruby
def analyse(string = nil) raise(ArgumentError, 'Lexer: failed to start analysis: no source given!') unless string || @scanner self.data = string || @scanner.string until @scanner.eos? send("parse_#{MODE[@mode]}") end push([false, '$end']) end
[ "def", "analyse", "(", "string", "=", "nil", ")", "raise", "(", "ArgumentError", ",", "'Lexer: failed to start analysis: no source given!'", ")", "unless", "string", "||", "@scanner", "self", ".", "data", "=", "string", "||", "@scanner", ".", "string", "until", "@scanner", ".", "eos?", "send", "(", "\"parse_#{MODE[@mode]}\"", ")", "end", "push", "(", "[", "false", ",", "'$end'", "]", ")", "end" ]
Start the lexical analysis.
[ "Start", "the", "lexical", "analysis", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/lexer.rb#L168-L179
train
inukshuk/bibtex-ruby
lib/bibtex/lexer.rb
BibTeX.Lexer.enter_object
def enter_object @brace_level = 0 push [:AT,'@'] case when @scanner.scan(Lexer.patterns[:string]) @mode = @active_object = :string push [:STRING, @scanner.matched] when @scanner.scan(Lexer.patterns[:preamble]) @mode = @active_object = :preamble push [:PREAMBLE, @scanner.matched] when @scanner.scan(Lexer.patterns[:comment]) @mode = @active_object = :comment push [:COMMENT, @scanner.matched] when @scanner.scan(Lexer.patterns[:entry]) @mode = @active_object = :entry push [:NAME, @scanner.matched] # TODO: DRY - try to parse key if @scanner.scan(Lexer.patterns[:lbrace]) @brace_level += 1 push([:LBRACE,'{']) @mode = :content if @brace_level > 1 || @brace_level == 1 && active?(:comment) if @scanner.scan(Lexer.patterns[allow_missing_keys? ? :optional_key : :key]) push [:KEY, @scanner.matched.chop.strip] end end else error_unexpected_object end end
ruby
def enter_object @brace_level = 0 push [:AT,'@'] case when @scanner.scan(Lexer.patterns[:string]) @mode = @active_object = :string push [:STRING, @scanner.matched] when @scanner.scan(Lexer.patterns[:preamble]) @mode = @active_object = :preamble push [:PREAMBLE, @scanner.matched] when @scanner.scan(Lexer.patterns[:comment]) @mode = @active_object = :comment push [:COMMENT, @scanner.matched] when @scanner.scan(Lexer.patterns[:entry]) @mode = @active_object = :entry push [:NAME, @scanner.matched] # TODO: DRY - try to parse key if @scanner.scan(Lexer.patterns[:lbrace]) @brace_level += 1 push([:LBRACE,'{']) @mode = :content if @brace_level > 1 || @brace_level == 1 && active?(:comment) if @scanner.scan(Lexer.patterns[allow_missing_keys? ? :optional_key : :key]) push [:KEY, @scanner.matched.chop.strip] end end else error_unexpected_object end end
[ "def", "enter_object", "@brace_level", "=", "0", "push", "[", ":AT", ",", "'@'", "]", "case", "when", "@scanner", ".", "scan", "(", "Lexer", ".", "patterns", "[", ":string", "]", ")", "@mode", "=", "@active_object", "=", ":string", "push", "[", ":STRING", ",", "@scanner", ".", "matched", "]", "when", "@scanner", ".", "scan", "(", "Lexer", ".", "patterns", "[", ":preamble", "]", ")", "@mode", "=", "@active_object", "=", ":preamble", "push", "[", ":PREAMBLE", ",", "@scanner", ".", "matched", "]", "when", "@scanner", ".", "scan", "(", "Lexer", ".", "patterns", "[", ":comment", "]", ")", "@mode", "=", "@active_object", "=", ":comment", "push", "[", ":COMMENT", ",", "@scanner", ".", "matched", "]", "when", "@scanner", ".", "scan", "(", "Lexer", ".", "patterns", "[", ":entry", "]", ")", "@mode", "=", "@active_object", "=", ":entry", "push", "[", ":NAME", ",", "@scanner", ".", "matched", "]", "if", "@scanner", ".", "scan", "(", "Lexer", ".", "patterns", "[", ":lbrace", "]", ")", "@brace_level", "+=", "1", "push", "(", "[", ":LBRACE", ",", "'{'", "]", ")", "@mode", "=", ":content", "if", "@brace_level", ">", "1", "||", "@brace_level", "==", "1", "&&", "active?", "(", ":comment", ")", "if", "@scanner", ".", "scan", "(", "Lexer", ".", "patterns", "[", "allow_missing_keys?", "?", ":optional_key", ":", ":key", "]", ")", "push", "[", ":KEY", ",", "@scanner", ".", "matched", ".", "chop", ".", "strip", "]", "end", "end", "else", "error_unexpected_object", "end", "end" ]
Called when the lexer encounters a new BibTeX object.
[ "Called", "when", "the", "lexer", "encounters", "a", "new", "BibTeX", "object", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/lexer.rb#L285-L317
train
inukshuk/bibtex-ruby
lib/bibtex/entry.rb
BibTeX.Entry.initialize_copy
def initialize_copy(other) @fields = {} self.type = other.type self.key = other.key add(other.fields) end
ruby
def initialize_copy(other) @fields = {} self.type = other.type self.key = other.key add(other.fields) end
[ "def", "initialize_copy", "(", "other", ")", "@fields", "=", "{", "}", "self", ".", "type", "=", "other", ".", "type", "self", ".", "key", "=", "other", ".", "key", "add", "(", "other", ".", "fields", ")", "end" ]
Creates a new instance. If a hash is given, the entry is populated accordingly.
[ "Creates", "a", "new", "instance", ".", "If", "a", "hash", "is", "given", "the", "entry", "is", "populated", "accordingly", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/entry.rb#L85-L92
train
inukshuk/bibtex-ruby
lib/bibtex/entry.rb
BibTeX.Entry.key=
def key=(key) key = key.to_s if registered? bibliography.entries.delete(@key) key = register(key) end @key = key rescue => e raise BibTeXError, "failed to set key to #{key.inspect}: #{e.message}" end
ruby
def key=(key) key = key.to_s if registered? bibliography.entries.delete(@key) key = register(key) end @key = key rescue => e raise BibTeXError, "failed to set key to #{key.inspect}: #{e.message}" end
[ "def", "key", "=", "(", "key", ")", "key", "=", "key", ".", "to_s", "if", "registered?", "bibliography", ".", "entries", ".", "delete", "(", "@key", ")", "key", "=", "register", "(", "key", ")", "end", "@key", "=", "key", "rescue", "=>", "e", "raise", "BibTeXError", ",", "\"failed to set key to #{key.inspect}: #{e.message}\"", "end" ]
Sets the Entry's key. If the Entry is currently registered with a Bibliography, re-registers the Entry with the new key; note that this may change the key value if another Entry is already regsitered with the same key. Returns the new key.
[ "Sets", "the", "Entry", "s", "key", ".", "If", "the", "Entry", "is", "currently", "registered", "with", "a", "Bibliography", "re", "-", "registers", "the", "Entry", "with", "the", "new", "key", ";", "note", "that", "this", "may", "change", "the", "key", "value", "if", "another", "Entry", "is", "already", "regsitered", "with", "the", "same", "key", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/entry.rb#L183-L194
train
inukshuk/bibtex-ruby
lib/bibtex/entry.rb
BibTeX.Entry.provide
def provide(name) return nil unless name.respond_to?(:to_sym) name = name.to_sym fields[name] || fields[aliases[name]] end
ruby
def provide(name) return nil unless name.respond_to?(:to_sym) name = name.to_sym fields[name] || fields[aliases[name]] end
[ "def", "provide", "(", "name", ")", "return", "nil", "unless", "name", ".", "respond_to?", "(", ":to_sym", ")", "name", "=", "name", ".", "to_sym", "fields", "[", "name", "]", "||", "fields", "[", "aliases", "[", "name", "]", "]", "end" ]
Returns the field value referenced by the passed-in name. For example, this will return the 'title' value for 'booktitle' if a corresponding alias is defined.
[ "Returns", "the", "field", "value", "referenced", "by", "the", "passed", "-", "in", "name", ".", "For", "example", "this", "will", "return", "the", "title", "value", "for", "booktitle", "if", "a", "corresponding", "alias", "is", "defined", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/entry.rb#L251-L255
train
inukshuk/bibtex-ruby
lib/bibtex/entry.rb
BibTeX.Entry.field_names
def field_names(filter = [], include_inherited = true) names = fields.keys if include_inherited && has_parent? names.concat(inherited_fields) end unless filter.empty? names = names & filter.map(&:to_sym) end names.sort! names end
ruby
def field_names(filter = [], include_inherited = true) names = fields.keys if include_inherited && has_parent? names.concat(inherited_fields) end unless filter.empty? names = names & filter.map(&:to_sym) end names.sort! names end
[ "def", "field_names", "(", "filter", "=", "[", "]", ",", "include_inherited", "=", "true", ")", "names", "=", "fields", ".", "keys", "if", "include_inherited", "&&", "has_parent?", "names", ".", "concat", "(", "inherited_fields", ")", "end", "unless", "filter", ".", "empty?", "names", "=", "names", "&", "filter", ".", "map", "(", "&", ":to_sym", ")", "end", "names", ".", "sort!", "names", "end" ]
Returns a sorted list of the Entry's field names. If a +filter+ is passed as argument, returns all field names that are also defined by the filter. If the +filter+ is empty, returns all field names. If the second optional argument is true (default) and the Entry contains a cross-reference, the list will include all inherited fields.
[ "Returns", "a", "sorted", "list", "of", "the", "Entry", "s", "field", "names", ".", "If", "a", "+", "filter", "+", "is", "passed", "as", "argument", "returns", "all", "field", "names", "that", "are", "also", "defined", "by", "the", "filter", ".", "If", "the", "+", "filter", "+", "is", "empty", "returns", "all", "field", "names", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/entry.rb#L275-L288
train
inukshuk/bibtex-ruby
lib/bibtex/entry.rb
BibTeX.Entry.inherited_fields
def inherited_fields return [] unless has_parent? names = parent.fields.keys - fields.keys names.concat(parent.aliases.reject { |k,v| !parent.has_field?(v) }.keys) names.sort! names end
ruby
def inherited_fields return [] unless has_parent? names = parent.fields.keys - fields.keys names.concat(parent.aliases.reject { |k,v| !parent.has_field?(v) }.keys) names.sort! names end
[ "def", "inherited_fields", "return", "[", "]", "unless", "has_parent?", "names", "=", "parent", ".", "fields", ".", "keys", "-", "fields", ".", "keys", "names", ".", "concat", "(", "parent", ".", "aliases", ".", "reject", "{", "|", "k", ",", "v", "|", "!", "parent", ".", "has_field?", "(", "v", ")", "}", ".", "keys", ")", "names", ".", "sort!", "names", "end" ]
Returns a sorted list of all field names referenced by this Entry's cross-reference.
[ "Returns", "a", "sorted", "list", "of", "all", "field", "names", "referenced", "by", "this", "Entry", "s", "cross", "-", "reference", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/entry.rb#L291-L299
train
inukshuk/bibtex-ruby
lib/bibtex/entry.rb
BibTeX.Entry.rename!
def rename!(*arguments) Hash[*arguments.flatten].each_pair do |from,to| if fields.has_key?(from) && !fields.has_key?(to) fields[to] = fields[from] fields.delete(from) end end self end
ruby
def rename!(*arguments) Hash[*arguments.flatten].each_pair do |from,to| if fields.has_key?(from) && !fields.has_key?(to) fields[to] = fields[from] fields.delete(from) end end self end
[ "def", "rename!", "(", "*", "arguments", ")", "Hash", "[", "*", "arguments", ".", "flatten", "]", ".", "each_pair", "do", "|", "from", ",", "to", "|", "if", "fields", ".", "has_key?", "(", "from", ")", "&&", "!", "fields", ".", "has_key?", "(", "to", ")", "fields", "[", "to", "]", "=", "fields", "[", "from", "]", "fields", ".", "delete", "(", "from", ")", "end", "end", "self", "end" ]
Renames the given field names unless a field with the new name already exists.
[ "Renames", "the", "given", "field", "names", "unless", "a", "field", "with", "the", "new", "name", "already", "exists", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/entry.rb#L330-L338
train
inukshuk/bibtex-ruby
lib/bibtex/entry.rb
BibTeX.Entry.valid?
def valid? REQUIRED_FIELDS[type].all? do |f| f.is_a?(Array) ? !(f & fields.keys).empty? : !fields[f].nil? end end
ruby
def valid? REQUIRED_FIELDS[type].all? do |f| f.is_a?(Array) ? !(f & fields.keys).empty? : !fields[f].nil? end end
[ "def", "valid?", "REQUIRED_FIELDS", "[", "type", "]", ".", "all?", "do", "|", "f", "|", "f", ".", "is_a?", "(", "Array", ")", "?", "!", "(", "f", "&", "fields", ".", "keys", ")", ".", "empty?", ":", "!", "fields", "[", "f", "]", ".", "nil?", "end", "end" ]
Returns false if the entry is one of the standard entry types and does not have definitions of all the required fields for that type.
[ "Returns", "false", "if", "the", "entry", "is", "one", "of", "the", "standard", "entry", "types", "and", "does", "not", "have", "definitions", "of", "all", "the", "required", "fields", "for", "that", "type", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/entry.rb#L389-L393
train
inukshuk/bibtex-ruby
lib/bibtex/entry.rb
BibTeX.Entry.digest
def digest(filter = []) names = field_names(filter) digest = type.to_s names.zip(values_at(*names)).each do |key, value| digest << "|#{key}:#{value}" end digest = yield(digest, self) if block_given? digest end
ruby
def digest(filter = []) names = field_names(filter) digest = type.to_s names.zip(values_at(*names)).each do |key, value| digest << "|#{key}:#{value}" end digest = yield(digest, self) if block_given? digest end
[ "def", "digest", "(", "filter", "=", "[", "]", ")", "names", "=", "field_names", "(", "filter", ")", "digest", "=", "type", ".", "to_s", "names", ".", "zip", "(", "values_at", "(", "*", "names", ")", ")", ".", "each", "do", "|", "key", ",", "value", "|", "digest", "<<", "\"|#{key}:#{value}\"", "end", "digest", "=", "yield", "(", "digest", ",", "self", ")", "if", "block_given?", "digest", "end" ]
Creates the entry's digest based on the passed-in filters. The digest contains the type and all key-value pairs based on the passed in filter. If a block is given, the computed digest will be passed to the block for post-processing (the entry itself will be passed as the second parameter). @see #field_names @param [<Symbol>] the field names to use @return [String] the digest string
[ "Creates", "the", "entry", "s", "digest", "based", "on", "the", "passed", "-", "in", "filters", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/entry.rb#L408-L418
train
inukshuk/bibtex-ruby
lib/bibtex/entry.rb
BibTeX.Entry.added_to_bibliography
def added_to_bibliography(bibliography) super @key = register(key) [:parse_names, :parse_months].each do |parser| send(parser) if bibliography.options[parser] end if bibliography.options.has_key?(:filter) [*bibliography.options[:filter]].each do |filter| convert!(filter) end end self end
ruby
def added_to_bibliography(bibliography) super @key = register(key) [:parse_names, :parse_months].each do |parser| send(parser) if bibliography.options[parser] end if bibliography.options.has_key?(:filter) [*bibliography.options[:filter]].each do |filter| convert!(filter) end end self end
[ "def", "added_to_bibliography", "(", "bibliography", ")", "super", "@key", "=", "register", "(", "key", ")", "[", ":parse_names", ",", ":parse_months", "]", ".", "each", "do", "|", "parser", "|", "send", "(", "parser", ")", "if", "bibliography", ".", "options", "[", "parser", "]", "end", "if", "bibliography", ".", "options", ".", "has_key?", "(", ":filter", ")", "[", "*", "bibliography", ".", "options", "[", ":filter", "]", "]", ".", "each", "do", "|", "filter", "|", "convert!", "(", "filter", ")", "end", "end", "self", "end" ]
Called when the element was added to a bibliography.
[ "Called", "when", "the", "element", "was", "added", "to", "a", "bibliography", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/entry.rb#L434-L450
train
inukshuk/bibtex-ruby
lib/bibtex/entry.rb
BibTeX.Entry.register
def register(key) return nil if bibliography.nil? k = key.dup k.succ! while bibliography.has_key?(k) bibliography.entries[k] = self k end
ruby
def register(key) return nil if bibliography.nil? k = key.dup k.succ! while bibliography.has_key?(k) bibliography.entries[k] = self k end
[ "def", "register", "(", "key", ")", "return", "nil", "if", "bibliography", ".", "nil?", "k", "=", "key", ".", "dup", "k", ".", "succ!", "while", "bibliography", ".", "has_key?", "(", "k", ")", "bibliography", ".", "entries", "[", "k", "]", "=", "self", "k", "end" ]
Registers this Entry in the associated Bibliographies entries hash. This method may change the Entry's key, if another entry is already registered with the current key. Returns the key or nil if the Entry is not associated with a Bibliography.
[ "Registers", "this", "Entry", "in", "the", "associated", "Bibliographies", "entries", "hash", ".", "This", "method", "may", "change", "the", "Entry", "s", "key", "if", "another", "entry", "is", "already", "registered", "with", "the", "current", "key", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/entry.rb#L469-L476
train
inukshuk/bibtex-ruby
lib/bibtex/entry.rb
BibTeX.Entry.parse_names
def parse_names strings = bibliography ? bibliography.strings.values : [] NAME_FIELDS.each do |key| if name = fields[key] name = name.dup.replace(strings).join.to_name fields[key] = name unless name.nil? end end self end
ruby
def parse_names strings = bibliography ? bibliography.strings.values : [] NAME_FIELDS.each do |key| if name = fields[key] name = name.dup.replace(strings).join.to_name fields[key] = name unless name.nil? end end self end
[ "def", "parse_names", "strings", "=", "bibliography", "?", "bibliography", ".", "strings", ".", "values", ":", "[", "]", "NAME_FIELDS", ".", "each", "do", "|", "key", "|", "if", "name", "=", "fields", "[", "key", "]", "name", "=", "name", ".", "dup", ".", "replace", "(", "strings", ")", ".", "join", ".", "to_name", "fields", "[", "key", "]", "=", "name", "unless", "name", ".", "nil?", "end", "end", "self", "end" ]
Parses all name values of the entry. Tries to replace and join the value prior to parsing.
[ "Parses", "all", "name", "values", "of", "the", "entry", ".", "Tries", "to", "replace", "and", "join", "the", "value", "prior", "to", "parsing", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/entry.rb#L522-L533
train
inukshuk/bibtex-ruby
lib/bibtex/entry.rb
BibTeX.Entry.convert!
def convert!(*filters) filters = filters.flatten.map { |f| Filters.resolve!(f) } fields.each_pair do |k, v| (!block_given? || yield(k, v)) ? v.convert!(*filters) : v end self end
ruby
def convert!(*filters) filters = filters.flatten.map { |f| Filters.resolve!(f) } fields.each_pair do |k, v| (!block_given? || yield(k, v)) ? v.convert!(*filters) : v end self end
[ "def", "convert!", "(", "*", "filters", ")", "filters", "=", "filters", ".", "flatten", ".", "map", "{", "|", "f", "|", "Filters", ".", "resolve!", "(", "f", ")", "}", "fields", ".", "each_pair", "do", "|", "k", ",", "v", "|", "(", "!", "block_given?", "||", "yield", "(", "k", ",", "v", ")", ")", "?", "v", ".", "convert!", "(", "*", "filters", ")", ":", "v", "end", "self", "end" ]
In-place variant of @see #convert
[ "In", "-", "place", "variant", "of" ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/entry.rb#L617-L625
train
inukshuk/bibtex-ruby
lib/bibtex/entry.rb
BibTeX.Entry.default_key
def default_key k = names[0] k = k.respond_to?(:family) ? k.family : k.to_s k = BibTeX.transliterate(k).gsub(/["']/, '') k = k[/[A-Za-z-]+/] || 'unknown' k << (year.to_s[/\d+/] || '-') k << 'a' k.downcase! k end
ruby
def default_key k = names[0] k = k.respond_to?(:family) ? k.family : k.to_s k = BibTeX.transliterate(k).gsub(/["']/, '') k = k[/[A-Za-z-]+/] || 'unknown' k << (year.to_s[/\d+/] || '-') k << 'a' k.downcase! k end
[ "def", "default_key", "k", "=", "names", "[", "0", "]", "k", "=", "k", ".", "respond_to?", "(", ":family", ")", "?", "k", ".", "family", ":", "k", ".", "to_s", "k", "=", "BibTeX", ".", "transliterate", "(", "k", ")", ".", "gsub", "(", "/", "/", ",", "''", ")", "k", "=", "k", "[", "/", "/", "]", "||", "'unknown'", "k", "<<", "(", "year", ".", "to_s", "[", "/", "\\d", "/", "]", "||", "'-'", ")", "k", "<<", "'a'", "k", ".", "downcase!", "k", "end" ]
Returns a default key for this entry.
[ "Returns", "a", "default", "key", "for", "this", "entry", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/entry.rb#L679-L688
train
inukshuk/bibtex-ruby
lib/bibtex/bibliography.rb
BibTeX.Bibliography.initialize_copy
def initialize_copy(other) @options = other.options.dup @errors = other.errors.dup @data, @strings = [], {} @entries = Hash.new { |h,k| h.fetch(k.to_s, nil) } other.each do |element| add element.dup end self end
ruby
def initialize_copy(other) @options = other.options.dup @errors = other.errors.dup @data, @strings = [], {} @entries = Hash.new { |h,k| h.fetch(k.to_s, nil) } other.each do |element| add element.dup end self end
[ "def", "initialize_copy", "(", "other", ")", "@options", "=", "other", ".", "options", ".", "dup", "@errors", "=", "other", ".", "errors", ".", "dup", "@data", ",", "@strings", "=", "[", "]", ",", "{", "}", "@entries", "=", "Hash", ".", "new", "{", "|", "h", ",", "k", "|", "h", ".", "fetch", "(", "k", ".", "to_s", ",", "nil", ")", "}", "other", ".", "each", "do", "|", "element", "|", "add", "element", ".", "dup", "end", "self", "end" ]
Creates a new bibliography.
[ "Creates", "a", "new", "bibliography", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/bibliography.rb#L105-L116
train
inukshuk/bibtex-ruby
lib/bibtex/bibliography.rb
BibTeX.Bibliography.add
def add(*arguments) Element.parse(arguments.flatten, @options).each do |element| data << element.added_to_bibliography(self) end self end
ruby
def add(*arguments) Element.parse(arguments.flatten, @options).each do |element| data << element.added_to_bibliography(self) end self end
[ "def", "add", "(", "*", "arguments", ")", "Element", ".", "parse", "(", "arguments", ".", "flatten", ",", "@options", ")", ".", "each", "do", "|", "element", "|", "data", "<<", "element", ".", "added_to_bibliography", "(", "self", ")", "end", "self", "end" ]
Adds a new element, or a list of new elements to the bibliography. Returns the Bibliography for chainability.
[ "Adds", "a", "new", "element", "or", "a", "list", "of", "new", "elements", "to", "the", "bibliography", ".", "Returns", "the", "Bibliography", "for", "chainability", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/bibliography.rb#L120-L125
train
inukshuk/bibtex-ruby
lib/bibtex/bibliography.rb
BibTeX.Bibliography.save_to
def save_to(path, options = {}) options[:quotes] ||= %w({ }) File.open(path, 'w:UTF-8') do |f| f.write(to_s(options)) end self end
ruby
def save_to(path, options = {}) options[:quotes] ||= %w({ }) File.open(path, 'w:UTF-8') do |f| f.write(to_s(options)) end self end
[ "def", "save_to", "(", "path", ",", "options", "=", "{", "}", ")", "options", "[", ":quotes", "]", "||=", "%w(", "{", "}", ")", "File", ".", "open", "(", "path", ",", "'w:UTF-8'", ")", "do", "|", "f", "|", "f", ".", "write", "(", "to_s", "(", "options", ")", ")", "end", "self", "end" ]
Saves the bibliography to a file at the given path. Returns the bibliography.
[ "Saves", "the", "bibliography", "to", "a", "file", "at", "the", "given", "path", ".", "Returns", "the", "bibliography", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/bibliography.rb#L137-L145
train
inukshuk/bibtex-ruby
lib/bibtex/bibliography.rb
BibTeX.Bibliography.delete
def delete(*arguments, &block) objects = q(*arguments, &block).map { |o| o.removed_from_bibliography(self) } @data = @data - objects objects.length == 1 ? objects[0] : objects end
ruby
def delete(*arguments, &block) objects = q(*arguments, &block).map { |o| o.removed_from_bibliography(self) } @data = @data - objects objects.length == 1 ? objects[0] : objects end
[ "def", "delete", "(", "*", "arguments", ",", "&", "block", ")", "objects", "=", "q", "(", "*", "arguments", ",", "&", "block", ")", ".", "map", "{", "|", "o", "|", "o", ".", "removed_from_bibliography", "(", "self", ")", "}", "@data", "=", "@data", "-", "objects", "objects", ".", "length", "==", "1", "?", "objects", "[", "0", "]", ":", "objects", "end" ]
Deletes an object, or a list of objects from the bibliography. If a list of objects is to be deleted, you can either supply the list of objects or use a query or block to define the list. Returns the object (or the list of objects) that were deleted; nil if the object was not part of the bibliography.
[ "Deletes", "an", "object", "or", "a", "list", "of", "objects", "from", "the", "bibliography", ".", "If", "a", "list", "of", "objects", "is", "to", "be", "deleted", "you", "can", "either", "supply", "the", "list", "of", "objects", "or", "use", "a", "query", "or", "block", "to", "define", "the", "list", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/bibliography.rb#L189-L193
train
inukshuk/bibtex-ruby
lib/bibtex/bibliography.rb
BibTeX.Bibliography.extend_initials!
def extend_initials! groups = Hash.new do |h,k| h[k] = { :prototype => nil, :names => [] } end # group names together names.each do |name| group = groups[name.sort_order(:initials => true).downcase] group[:names] << name if group[:prototype].nil? || group[:prototype].first.to_s.length < name.first.to_s.length group[:prototype] = name end end # extend all names in group to prototype groups.each_value do |group| group[:names].each do |name| name.set(group[:prototype]) end end self end
ruby
def extend_initials! groups = Hash.new do |h,k| h[k] = { :prototype => nil, :names => [] } end # group names together names.each do |name| group = groups[name.sort_order(:initials => true).downcase] group[:names] << name if group[:prototype].nil? || group[:prototype].first.to_s.length < name.first.to_s.length group[:prototype] = name end end # extend all names in group to prototype groups.each_value do |group| group[:names].each do |name| name.set(group[:prototype]) end end self end
[ "def", "extend_initials!", "groups", "=", "Hash", ".", "new", "do", "|", "h", ",", "k", "|", "h", "[", "k", "]", "=", "{", ":prototype", "=>", "nil", ",", ":names", "=>", "[", "]", "}", "end", "names", ".", "each", "do", "|", "name", "|", "group", "=", "groups", "[", "name", ".", "sort_order", "(", ":initials", "=>", "true", ")", ".", "downcase", "]", "group", "[", ":names", "]", "<<", "name", "if", "group", "[", ":prototype", "]", ".", "nil?", "||", "group", "[", ":prototype", "]", ".", "first", ".", "to_s", ".", "length", "<", "name", ".", "first", ".", "to_s", ".", "length", "group", "[", ":prototype", "]", "=", "name", "end", "end", "groups", ".", "each_value", "do", "|", "group", "|", "group", "[", ":names", "]", ".", "each", "do", "|", "name", "|", "name", ".", "set", "(", "group", "[", ":prototype", "]", ")", "end", "end", "self", "end" ]
This method combines all names in the bibliography that look identical when using initials as first names and then tries to extend the first names for all names in each group to the longest available form. Returns the bibliography. If your bibliography contains the names 'Poe, Edgar A.', 'Poe, E.A.', and 'Poe, E. A.' calling this method would convert all three names to 'Poe, Edgar A.'.
[ "This", "method", "combines", "all", "names", "in", "the", "bibliography", "that", "look", "identical", "when", "using", "initials", "as", "first", "names", "and", "then", "tries", "to", "extend", "the", "first", "names", "for", "all", "names", "in", "each", "group", "to", "the", "longest", "available", "form", ".", "Returns", "the", "bibliography", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/bibliography.rb#L320-L343
train
inukshuk/bibtex-ruby
lib/bibtex/elements.rb
BibTeX.Element.matches?
def matches?(query) return true if query.nil? || query.respond_to?(:empty?) && query.empty? case query when Symbol query.to_s == id.to_s when Element query == self when Regexp to_s.match(query) when /^\/(.+)\/$/ to_s.match(Regexp.new($1)) when /@(\*|\w+)(?:\[([^\]]*)\])?/ query.scan(/(!)?@(\*|\w+)(?:\[([^\]]*)\])?/).any? do |non, type, condition| if (non ? !has_type?(type) : has_type?(type)) if condition.nil? || condition.empty? true else condition.to_s.split(/\s*\|\|\s*/).any? do |conditions| meets_all? conditions.split(/\s*(?:,|&&)\s*/) end end end end else id.to_s == query end end
ruby
def matches?(query) return true if query.nil? || query.respond_to?(:empty?) && query.empty? case query when Symbol query.to_s == id.to_s when Element query == self when Regexp to_s.match(query) when /^\/(.+)\/$/ to_s.match(Regexp.new($1)) when /@(\*|\w+)(?:\[([^\]]*)\])?/ query.scan(/(!)?@(\*|\w+)(?:\[([^\]]*)\])?/).any? do |non, type, condition| if (non ? !has_type?(type) : has_type?(type)) if condition.nil? || condition.empty? true else condition.to_s.split(/\s*\|\|\s*/).any? do |conditions| meets_all? conditions.split(/\s*(?:,|&&)\s*/) end end end end else id.to_s == query end end
[ "def", "matches?", "(", "query", ")", "return", "true", "if", "query", ".", "nil?", "||", "query", ".", "respond_to?", "(", ":empty?", ")", "&&", "query", ".", "empty?", "case", "query", "when", "Symbol", "query", ".", "to_s", "==", "id", ".", "to_s", "when", "Element", "query", "==", "self", "when", "Regexp", "to_s", ".", "match", "(", "query", ")", "when", "/", "\\/", "\\/", "/", "to_s", ".", "match", "(", "Regexp", ".", "new", "(", "$1", ")", ")", "when", "/", "\\*", "\\w", "\\[", "\\]", "\\]", "/", "query", ".", "scan", "(", "/", "\\*", "\\w", "\\[", "\\]", "\\]", "/", ")", ".", "any?", "do", "|", "non", ",", "type", ",", "condition", "|", "if", "(", "non", "?", "!", "has_type?", "(", "type", ")", ":", "has_type?", "(", "type", ")", ")", "if", "condition", ".", "nil?", "||", "condition", ".", "empty?", "true", "else", "condition", ".", "to_s", ".", "split", "(", "/", "\\s", "\\|", "\\|", "\\s", "/", ")", ".", "any?", "do", "|", "conditions", "|", "meets_all?", "conditions", ".", "split", "(", "/", "\\s", "\\s", "/", ")", "end", "end", "end", "end", "else", "id", ".", "to_s", "==", "query", "end", "end" ]
Returns true if the element matches the given query.
[ "Returns", "true", "if", "the", "element", "matches", "the", "given", "query", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/elements.rb#L92-L119
train
inukshuk/bibtex-ruby
lib/bibtex/names.rb
BibTeX.Name.set
def set(attributes = {}) attributes.each_pair do |key, value| send("#{key}=", value) if respond_to?(key) end self end
ruby
def set(attributes = {}) attributes.each_pair do |key, value| send("#{key}=", value) if respond_to?(key) end self end
[ "def", "set", "(", "attributes", "=", "{", "}", ")", "attributes", ".", "each_pair", "do", "|", "key", ",", "value", "|", "send", "(", "\"#{key}=\"", ",", "value", ")", "if", "respond_to?", "(", "key", ")", "end", "self", "end" ]
Set the name tokens to the values defined in the passed-in hash.
[ "Set", "the", "name", "tokens", "to", "the", "values", "defined", "in", "the", "passed", "-", "in", "hash", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/names.rb#L155-L161
train
inukshuk/bibtex-ruby
lib/bibtex/names.rb
BibTeX.Name.extend_initials
def extend_initials(with_first, for_last) rename_if :first => with_first do |name| if name.last == for_last mine = name.initials.split(/\.[^[:alpha:]]*/) other = initials(with_first).split(/\.[^[:alpha:]]*/) mine == other || mine.length < other.length && mine == other[0, mine.length] end end end
ruby
def extend_initials(with_first, for_last) rename_if :first => with_first do |name| if name.last == for_last mine = name.initials.split(/\.[^[:alpha:]]*/) other = initials(with_first).split(/\.[^[:alpha:]]*/) mine == other || mine.length < other.length && mine == other[0, mine.length] end end end
[ "def", "extend_initials", "(", "with_first", ",", "for_last", ")", "rename_if", ":first", "=>", "with_first", "do", "|", "name", "|", "if", "name", ".", "last", "==", "for_last", "mine", "=", "name", ".", "initials", ".", "split", "(", "/", "\\.", "/", ")", "other", "=", "initials", "(", "with_first", ")", ".", "split", "(", "/", "\\.", "/", ")", "mine", "==", "other", "||", "mine", ".", "length", "<", "other", ".", "length", "&&", "mine", "==", "other", "[", "0", ",", "mine", ".", "length", "]", "end", "end", "end" ]
Sets the name's first name to the passed-in name if the last name equals for_last and the current first name has the same initials as with_first.
[ "Sets", "the", "name", "s", "first", "name", "to", "the", "passed", "-", "in", "name", "if", "the", "last", "name", "equals", "for_last", "and", "the", "current", "first", "name", "has", "the", "same", "initials", "as", "with_first", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/names.rb#L187-L196
train
inukshuk/bibtex-ruby
lib/bibtex/names.rb
BibTeX.Name.rename_if
def rename_if(attributes, conditions = {}) if block_given? set(attributes) if yield self else set(attributes) if conditions.all? do |key, value| respond_to?(key) && send(key) == value end end self end
ruby
def rename_if(attributes, conditions = {}) if block_given? set(attributes) if yield self else set(attributes) if conditions.all? do |key, value| respond_to?(key) && send(key) == value end end self end
[ "def", "rename_if", "(", "attributes", ",", "conditions", "=", "{", "}", ")", "if", "block_given?", "set", "(", "attributes", ")", "if", "yield", "self", "else", "set", "(", "attributes", ")", "if", "conditions", ".", "all?", "do", "|", "key", ",", "value", "|", "respond_to?", "(", "key", ")", "&&", "send", "(", "key", ")", "==", "value", "end", "end", "self", "end" ]
Renames the tokens according to the passed-in attributes if all of the conditions match or if the given block returns true.
[ "Renames", "the", "tokens", "according", "to", "the", "passed", "-", "in", "attributes", "if", "all", "of", "the", "conditions", "match", "or", "if", "the", "given", "block", "returns", "true", "." ]
69bd06d35499929f1eb1df6b98fa7b5a2d768b1d
https://github.com/inukshuk/bibtex-ruby/blob/69bd06d35499929f1eb1df6b98fa7b5a2d768b1d/lib/bibtex/names.rb#L200-L210
train
redding/assert
lib/assert/context.rb
Assert.Context.assert
def assert(assertion, desc = nil) if assertion pass else what = if block_given? yield else "Failed assert: assertion was "\ "`#{Assert::U.show(assertion, __assert_config__)}`." end fail(fail_message(desc, what)) end end
ruby
def assert(assertion, desc = nil) if assertion pass else what = if block_given? yield else "Failed assert: assertion was "\ "`#{Assert::U.show(assertion, __assert_config__)}`." end fail(fail_message(desc, what)) end end
[ "def", "assert", "(", "assertion", ",", "desc", "=", "nil", ")", "if", "assertion", "pass", "else", "what", "=", "if", "block_given?", "yield", "else", "\"Failed assert: assertion was \"", "\"`#{Assert::U.show(assertion, __assert_config__)}`.\"", "end", "fail", "(", "fail_message", "(", "desc", ",", "what", ")", ")", "end", "end" ]
check if the assertion is a truthy value, if so create a new pass result, otherwise create a new fail result with the desc and what failed msg. all other assertion helpers use this one in the end
[ "check", "if", "the", "assertion", "is", "a", "truthy", "value", "if", "so", "create", "a", "new", "pass", "result", "otherwise", "create", "a", "new", "fail", "result", "with", "the", "desc", "and", "what", "failed", "msg", ".", "all", "other", "assertion", "helpers", "use", "this", "one", "in", "the", "end" ]
52c0adf2db40bdd3490021539b3a26a0b530d5a4
https://github.com/redding/assert/blob/52c0adf2db40bdd3490021539b3a26a0b530d5a4/lib/assert/context.rb#L68-L80
train
redding/assert
lib/assert/context.rb
Assert.Context.pass
def pass(pass_msg = nil) if @__assert_pending__ == 0 capture_result(Assert::Result::Pass, pass_msg) else capture_result(Assert::Result::Fail, "Pending pass (make it "\ "not pending)") end end
ruby
def pass(pass_msg = nil) if @__assert_pending__ == 0 capture_result(Assert::Result::Pass, pass_msg) else capture_result(Assert::Result::Fail, "Pending pass (make it "\ "not pending)") end end
[ "def", "pass", "(", "pass_msg", "=", "nil", ")", "if", "@__assert_pending__", "==", "0", "capture_result", "(", "Assert", "::", "Result", "::", "Pass", ",", "pass_msg", ")", "else", "capture_result", "(", "Assert", "::", "Result", "::", "Fail", ",", "\"Pending pass (make it \"", "\"not pending)\"", ")", "end", "end" ]
adds a Pass result to the end of the test's results does not break test execution
[ "adds", "a", "Pass", "result", "to", "the", "end", "of", "the", "test", "s", "results", "does", "not", "break", "test", "execution" ]
52c0adf2db40bdd3490021539b3a26a0b530d5a4
https://github.com/redding/assert/blob/52c0adf2db40bdd3490021539b3a26a0b530d5a4/lib/assert/context.rb#L94-L101
train
redding/assert
lib/assert/context.rb
Assert.Context.fail
def fail(message = nil) if @__assert_pending__ == 0 if halt_on_fail? raise Result::TestFailure, message || "" else capture_result(Assert::Result::Fail, message || "") end else if halt_on_fail? raise Result::TestSkipped, "Pending fail: #{message || ""}" else capture_result(Assert::Result::Skip, "Pending fail: #{message || ""}") end end end
ruby
def fail(message = nil) if @__assert_pending__ == 0 if halt_on_fail? raise Result::TestFailure, message || "" else capture_result(Assert::Result::Fail, message || "") end else if halt_on_fail? raise Result::TestSkipped, "Pending fail: #{message || ""}" else capture_result(Assert::Result::Skip, "Pending fail: #{message || ""}") end end end
[ "def", "fail", "(", "message", "=", "nil", ")", "if", "@__assert_pending__", "==", "0", "if", "halt_on_fail?", "raise", "Result", "::", "TestFailure", ",", "message", "||", "\"\"", "else", "capture_result", "(", "Assert", "::", "Result", "::", "Fail", ",", "message", "||", "\"\"", ")", "end", "else", "if", "halt_on_fail?", "raise", "Result", "::", "TestSkipped", ",", "\"Pending fail: #{message || \"\"}\"", "else", "capture_result", "(", "Assert", "::", "Result", "::", "Skip", ",", "\"Pending fail: #{message || \"\"}\"", ")", "end", "end", "end" ]
adds a Fail result to the end of the test's results break test execution if assert is configured to halt on failures
[ "adds", "a", "Fail", "result", "to", "the", "end", "of", "the", "test", "s", "results", "break", "test", "execution", "if", "assert", "is", "configured", "to", "halt", "on", "failures" ]
52c0adf2db40bdd3490021539b3a26a0b530d5a4
https://github.com/redding/assert/blob/52c0adf2db40bdd3490021539b3a26a0b530d5a4/lib/assert/context.rb#L111-L125
train
justinweiss/resque_unit
lib/resque_unit/scheduler.rb
ResqueUnit.Scheduler.enqueue_in
def enqueue_in(number_of_seconds_from_now, klass, *args) enqueue_at(Time.now + number_of_seconds_from_now, klass, *args) end
ruby
def enqueue_in(number_of_seconds_from_now, klass, *args) enqueue_at(Time.now + number_of_seconds_from_now, klass, *args) end
[ "def", "enqueue_in", "(", "number_of_seconds_from_now", ",", "klass", ",", "*", "args", ")", "enqueue_at", "(", "Time", ".", "now", "+", "number_of_seconds_from_now", ",", "klass", ",", "*", "args", ")", "end" ]
Identical to enqueue_at but takes number_of_seconds_from_now instead of a timestamp.
[ "Identical", "to", "enqueue_at", "but", "takes", "number_of_seconds_from_now", "instead", "of", "a", "timestamp", "." ]
064f54b6405980dfdd37afabe03b959884b3b166
https://github.com/justinweiss/resque_unit/blob/064f54b6405980dfdd37afabe03b959884b3b166/lib/resque_unit/scheduler.rb#L21-L23
train
justinweiss/resque_unit
lib/resque_unit/helpers.rb
ResqueUnit.Helpers.decode
def decode(object) return unless object if defined? Yajl begin Yajl::Parser.parse(object, :check_utf8 => false) rescue Yajl::ParseError end else begin JSON.parse(object) rescue JSON::ParserError end end end
ruby
def decode(object) return unless object if defined? Yajl begin Yajl::Parser.parse(object, :check_utf8 => false) rescue Yajl::ParseError end else begin JSON.parse(object) rescue JSON::ParserError end end end
[ "def", "decode", "(", "object", ")", "return", "unless", "object", "if", "defined?", "Yajl", "begin", "Yajl", "::", "Parser", ".", "parse", "(", "object", ",", ":check_utf8", "=>", "false", ")", "rescue", "Yajl", "::", "ParseError", "end", "else", "begin", "JSON", ".", "parse", "(", "object", ")", "rescue", "JSON", "::", "ParserError", "end", "end", "end" ]
Given a string, returns a Ruby object.
[ "Given", "a", "string", "returns", "a", "Ruby", "object", "." ]
064f54b6405980dfdd37afabe03b959884b3b166
https://github.com/justinweiss/resque_unit/blob/064f54b6405980dfdd37afabe03b959884b3b166/lib/resque_unit/helpers.rb#L14-L28
train
justinweiss/resque_unit
lib/resque_unit/helpers.rb
ResqueUnit.Helpers.constantize
def constantize(camel_cased_word) camel_cased_word = camel_cased_word.to_s if camel_cased_word.include?('-') camel_cased_word = classify(camel_cased_word) end names = camel_cased_word.split('::') names.shift if names.empty? || names.first.empty? constant = Object names.each do |name| constant = constant.const_get(name) || constant.const_missing(name) end constant end
ruby
def constantize(camel_cased_word) camel_cased_word = camel_cased_word.to_s if camel_cased_word.include?('-') camel_cased_word = classify(camel_cased_word) end names = camel_cased_word.split('::') names.shift if names.empty? || names.first.empty? constant = Object names.each do |name| constant = constant.const_get(name) || constant.const_missing(name) end constant end
[ "def", "constantize", "(", "camel_cased_word", ")", "camel_cased_word", "=", "camel_cased_word", ".", "to_s", "if", "camel_cased_word", ".", "include?", "(", "'-'", ")", "camel_cased_word", "=", "classify", "(", "camel_cased_word", ")", "end", "names", "=", "camel_cased_word", ".", "split", "(", "'::'", ")", "names", ".", "shift", "if", "names", ".", "empty?", "||", "names", ".", "first", ".", "empty?", "constant", "=", "Object", "names", ".", "each", "do", "|", "name", "|", "constant", "=", "constant", ".", "const_get", "(", "name", ")", "||", "constant", ".", "const_missing", "(", "name", ")", "end", "constant", "end" ]
Given a camel cased word, returns the constant it represents constantize('JobName') # => JobName
[ "Given", "a", "camel", "cased", "word", "returns", "the", "constant", "it", "represents" ]
064f54b6405980dfdd37afabe03b959884b3b166
https://github.com/justinweiss/resque_unit/blob/064f54b6405980dfdd37afabe03b959884b3b166/lib/resque_unit/helpers.rb#L40-L55
train
joshwlewis/unitwise
lib/unitwise/term.rb
Unitwise.Term.atom=
def atom=(value) value.is_a?(Atom) ? super(value) : super(Atom.find(value.to_s)) end
ruby
def atom=(value) value.is_a?(Atom) ? super(value) : super(Atom.find(value.to_s)) end
[ "def", "atom", "=", "(", "value", ")", "value", ".", "is_a?", "(", "Atom", ")", "?", "super", "(", "value", ")", ":", "super", "(", "Atom", ".", "find", "(", "value", ".", "to_s", ")", ")", "end" ]
Set the atom. @param value [String, Atom] Either a string representing an Atom, or an Atom @api public
[ "Set", "the", "atom", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/term.rb#L12-L14
train
joshwlewis/unitwise
lib/unitwise/term.rb
Unitwise.Term.prefix=
def prefix=(value) value.is_a?(Prefix) ? super(value) : super(Prefix.find(value.to_s)) end
ruby
def prefix=(value) value.is_a?(Prefix) ? super(value) : super(Prefix.find(value.to_s)) end
[ "def", "prefix", "=", "(", "value", ")", "value", ".", "is_a?", "(", "Prefix", ")", "?", "super", "(", "value", ")", ":", "super", "(", "Prefix", ".", "find", "(", "value", ".", "to_s", ")", ")", "end" ]
Set the prefix. @param value [String, Prefix] Either a string representing a Prefix, or a Prefix
[ "Set", "the", "prefix", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/term.rb#L19-L21
train
joshwlewis/unitwise
lib/unitwise/term.rb
Unitwise.Term.root_terms
def root_terms if terminal? [self] else atom.scale.root_terms.map do |t| self.class.new(:atom => t.atom, :exponent => t.exponent * exponent) end end end
ruby
def root_terms if terminal? [self] else atom.scale.root_terms.map do |t| self.class.new(:atom => t.atom, :exponent => t.exponent * exponent) end end end
[ "def", "root_terms", "if", "terminal?", "[", "self", "]", "else", "atom", ".", "scale", ".", "root_terms", ".", "map", "do", "|", "t", "|", "self", ".", "class", ".", "new", "(", ":atom", "=>", "t", ".", "atom", ",", ":exponent", "=>", "t", ".", "exponent", "*", "exponent", ")", "end", "end", "end" ]
The base units this term is derived from @return [Array] An array of Unitwise::Term @api public
[ "The", "base", "units", "this", "term", "is", "derived", "from" ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/term.rb#L77-L85
train
joshwlewis/unitwise
lib/unitwise/term.rb
Unitwise.Term.operate
def operate(operator, other) exp = operator == '/' ? -1 : 1 if other.respond_to?(:terms) Unit.new(other.terms.map { |t| t ** exp } << self) elsif other.respond_to?(:atom) Unit.new([self, other ** exp]) elsif other.is_a?(Numeric) self.class.new(to_hash.merge(:factor => factor.send(operator, other))) end end
ruby
def operate(operator, other) exp = operator == '/' ? -1 : 1 if other.respond_to?(:terms) Unit.new(other.terms.map { |t| t ** exp } << self) elsif other.respond_to?(:atom) Unit.new([self, other ** exp]) elsif other.is_a?(Numeric) self.class.new(to_hash.merge(:factor => factor.send(operator, other))) end end
[ "def", "operate", "(", "operator", ",", "other", ")", "exp", "=", "operator", "==", "'/'", "?", "-", "1", ":", "1", "if", "other", ".", "respond_to?", "(", ":terms", ")", "Unit", ".", "new", "(", "other", ".", "terms", ".", "map", "{", "|", "t", "|", "t", "**", "exp", "}", "<<", "self", ")", "elsif", "other", ".", "respond_to?", "(", ":atom", ")", "Unit", ".", "new", "(", "[", "self", ",", "other", "**", "exp", "]", ")", "elsif", "other", ".", "is_a?", "(", "Numeric", ")", "self", ".", "class", ".", "new", "(", "to_hash", ".", "merge", "(", ":factor", "=>", "factor", ".", "send", "(", "operator", ",", "other", ")", ")", ")", "end", "end" ]
Multiply or divide a term @api private
[ "Multiply", "or", "divide", "a", "term" ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/term.rb#L134-L143
train
joshwlewis/unitwise
lib/unitwise/base.rb
Unitwise.Base.to_s
def to_s(mode = :primary_code) res = send(mode) || primary_code res.respond_to?(:each) ? res.first.to_s : res.to_s end
ruby
def to_s(mode = :primary_code) res = send(mode) || primary_code res.respond_to?(:each) ? res.first.to_s : res.to_s end
[ "def", "to_s", "(", "mode", "=", ":primary_code", ")", "res", "=", "send", "(", "mode", ")", "||", "primary_code", "res", ".", "respond_to?", "(", ":each", ")", "?", "res", ".", "first", ".", "to_s", ":", "res", ".", "to_s", "end" ]
String representation for the instance. @param mode [symbol] The attribute to for stringification @return [String] @api public
[ "String", "representation", "for", "the", "instance", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/base.rb#L53-L56
train
joshwlewis/unitwise
lib/unitwise/atom.rb
Unitwise.Atom.scale=
def scale=(attrs) @scale = if attrs[:function_code] Functional.new(attrs[:value], attrs[:unit_code], attrs[:function_code]) else Scale.new(attrs[:value], attrs[:unit_code]) end end
ruby
def scale=(attrs) @scale = if attrs[:function_code] Functional.new(attrs[:value], attrs[:unit_code], attrs[:function_code]) else Scale.new(attrs[:value], attrs[:unit_code]) end end
[ "def", "scale", "=", "(", "attrs", ")", "@scale", "=", "if", "attrs", "[", ":function_code", "]", "Functional", ".", "new", "(", "attrs", "[", ":value", "]", ",", "attrs", "[", ":unit_code", "]", ",", "attrs", "[", ":function_code", "]", ")", "else", "Scale", ".", "new", "(", "attrs", "[", ":value", "]", ",", "attrs", "[", ":unit_code", "]", ")", "end", "end" ]
Set the atom's scale. It can be set as a Scale or a Functional @return [Unitwise::Functional, Unitwise::Scale] @api public
[ "Set", "the", "atom", "s", "scale", ".", "It", "can", "be", "set", "as", "a", "Scale", "or", "a", "Functional" ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/atom.rb#L93-L99
train
joshwlewis/unitwise
lib/unitwise/atom.rb
Unitwise.Atom.validate!
def validate! missing_properties = %i{primary_code names scale}.select do |prop| val = liner_get(prop) val.nil? || (val.respond_to?(:empty) && val.empty?) end if !missing_properties.empty? missing_list = missing_properties.join(',') raise Unitwise::DefinitionError, "Atom has missing properties: #{missing_list}." end msg = "Atom definition could not be resolved. Ensure that it is a base " \ "unit or is defined relative to existing units." begin !scalar.nil? && !magnitude.nil? || raise(Unitwise::DefinitionError, msg) rescue Unitwise::ExpressionError raise Unitwise::DefinitionError, msg end end
ruby
def validate! missing_properties = %i{primary_code names scale}.select do |prop| val = liner_get(prop) val.nil? || (val.respond_to?(:empty) && val.empty?) end if !missing_properties.empty? missing_list = missing_properties.join(',') raise Unitwise::DefinitionError, "Atom has missing properties: #{missing_list}." end msg = "Atom definition could not be resolved. Ensure that it is a base " \ "unit or is defined relative to existing units." begin !scalar.nil? && !magnitude.nil? || raise(Unitwise::DefinitionError, msg) rescue Unitwise::ExpressionError raise Unitwise::DefinitionError, msg end end
[ "def", "validate!", "missing_properties", "=", "%i{", "primary_code", "names", "scale", "}", ".", "select", "do", "|", "prop", "|", "val", "=", "liner_get", "(", "prop", ")", "val", ".", "nil?", "||", "(", "val", ".", "respond_to?", "(", ":empty", ")", "&&", "val", ".", "empty?", ")", "end", "if", "!", "missing_properties", ".", "empty?", "missing_list", "=", "missing_properties", ".", "join", "(", "','", ")", "raise", "Unitwise", "::", "DefinitionError", ",", "\"Atom has missing properties: #{missing_list}.\"", "end", "msg", "=", "\"Atom definition could not be resolved. Ensure that it is a base \"", "\"unit or is defined relative to existing units.\"", "begin", "!", "scalar", ".", "nil?", "&&", "!", "magnitude", ".", "nil?", "||", "raise", "(", "Unitwise", "::", "DefinitionError", ",", "msg", ")", "rescue", "Unitwise", "::", "ExpressionError", "raise", "Unitwise", "::", "DefinitionError", ",", "msg", "end", "end" ]
A basic validator for atoms. It checks for the bare minimum properties and that it's scalar and magnitude can be resolved. Note that this method requires the units it depends on to already exist, so it is not used when loading the initial data from UCUM. @return [true] returns true if the atom is valid @raise [Unitwise::DefinitionError]
[ "A", "basic", "validator", "for", "atoms", ".", "It", "checks", "for", "the", "bare", "minimum", "properties", "and", "that", "it", "s", "scalar", "and", "magnitude", "can", "be", "resolved", ".", "Note", "that", "this", "method", "requires", "the", "units", "it", "depends", "on", "to", "already", "exist", "so", "it", "is", "not", "used", "when", "loading", "the", "initial", "data", "from", "UCUM", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/atom.rb#L128-L148
train