id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
5,600
mLewisLogic/saddle
lib/saddle/requester.rb
Saddle.Requester.delete
def delete(url, params={}, options={}) response = connection.delete do |req| req.saddle_options = options req.url(url, params) end handle_response(response) end
ruby
def delete(url, params={}, options={}) response = connection.delete do |req| req.saddle_options = options req.url(url, params) end handle_response(response) end
[ "def", "delete", "(", "url", ",", "params", "=", "{", "}", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "delete", "do", "|", "req", "|", "req", ".", "saddle_options", "=", "options", "req", ".", "url", "(", "url", ",", "params", ")", "end", "handle_response", "(", "response", ")", "end" ]
Make a DELETE request
[ "Make", "a", "DELETE", "request" ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/requester.rb#L111-L117
5,601
mLewisLogic/saddle
lib/saddle/requester.rb
Saddle.Requester.connection
def connection @connection ||= Faraday.new(base_url, :builder_class => Saddle::RackBuilder) do |connection| # Include the requester level options connection.builder.saddle_options[:client_options] = @options # Config options connection.options[:timeout] = @timeout connection.builder.saddle_options[:request_style] = @request_style connection.builder.saddle_options[:num_retries] = @num_retries connection.builder.saddle_options[:client] = @parent_client # Support default return values upon exception connection.use(Saddle::Middleware::Response::DefaultResponse) # Hard timeout on the entire request connection.use(Saddle::Middleware::RubyTimeout) # Set up a user agent connection.use(Saddle::Middleware::Request::UserAgent) # Set up the path prefix if needed connection.use(Saddle::Middleware::Request::PathPrefix) # Apply additional implementation-specific middlewares @additional_middlewares.each do |m| m[:args] ? connection.use(m[:klass], *m[:args]) : connection.use(m[:klass]) end # Request encoding connection.use(Saddle::Middleware::Request::JsonEncoded) connection.use(Saddle::Middleware::Request::UrlEncoded) # Automatic retries connection.use(Saddle::Middleware::Request::Retry) # Raise exceptions on 4xx and 5xx errors connection.use(Saddle::Middleware::Response::RaiseError) # Handle parsing out the response if it's JSON connection.use(Saddle::Middleware::Response::ParseJson) # Set up instrumentation around the adapter for extensibility connection.use(FaradayMiddleware::Instrumentation) # Add in extra env data if needed connection.use(Saddle::Middleware::ExtraEnv) # Set up our adapter if @stubs.nil? # Use the default adapter connection.adapter(@http_adapter[:key], *@http_adapter[:args]) else # Use the test adapter connection.adapter(:test, @stubs) end end end
ruby
def connection @connection ||= Faraday.new(base_url, :builder_class => Saddle::RackBuilder) do |connection| # Include the requester level options connection.builder.saddle_options[:client_options] = @options # Config options connection.options[:timeout] = @timeout connection.builder.saddle_options[:request_style] = @request_style connection.builder.saddle_options[:num_retries] = @num_retries connection.builder.saddle_options[:client] = @parent_client # Support default return values upon exception connection.use(Saddle::Middleware::Response::DefaultResponse) # Hard timeout on the entire request connection.use(Saddle::Middleware::RubyTimeout) # Set up a user agent connection.use(Saddle::Middleware::Request::UserAgent) # Set up the path prefix if needed connection.use(Saddle::Middleware::Request::PathPrefix) # Apply additional implementation-specific middlewares @additional_middlewares.each do |m| m[:args] ? connection.use(m[:klass], *m[:args]) : connection.use(m[:klass]) end # Request encoding connection.use(Saddle::Middleware::Request::JsonEncoded) connection.use(Saddle::Middleware::Request::UrlEncoded) # Automatic retries connection.use(Saddle::Middleware::Request::Retry) # Raise exceptions on 4xx and 5xx errors connection.use(Saddle::Middleware::Response::RaiseError) # Handle parsing out the response if it's JSON connection.use(Saddle::Middleware::Response::ParseJson) # Set up instrumentation around the adapter for extensibility connection.use(FaradayMiddleware::Instrumentation) # Add in extra env data if needed connection.use(Saddle::Middleware::ExtraEnv) # Set up our adapter if @stubs.nil? # Use the default adapter connection.adapter(@http_adapter[:key], *@http_adapter[:args]) else # Use the test adapter connection.adapter(:test, @stubs) end end end
[ "def", "connection", "@connection", "||=", "Faraday", ".", "new", "(", "base_url", ",", ":builder_class", "=>", "Saddle", "::", "RackBuilder", ")", "do", "|", "connection", "|", "# Include the requester level options", "connection", ".", "builder", ".", "saddle_options", "[", ":client_options", "]", "=", "@options", "# Config options", "connection", ".", "options", "[", ":timeout", "]", "=", "@timeout", "connection", ".", "builder", ".", "saddle_options", "[", ":request_style", "]", "=", "@request_style", "connection", ".", "builder", ".", "saddle_options", "[", ":num_retries", "]", "=", "@num_retries", "connection", ".", "builder", ".", "saddle_options", "[", ":client", "]", "=", "@parent_client", "# Support default return values upon exception", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Response", "::", "DefaultResponse", ")", "# Hard timeout on the entire request", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "RubyTimeout", ")", "# Set up a user agent", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Request", "::", "UserAgent", ")", "# Set up the path prefix if needed", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Request", "::", "PathPrefix", ")", "# Apply additional implementation-specific middlewares", "@additional_middlewares", ".", "each", "do", "|", "m", "|", "m", "[", ":args", "]", "?", "connection", ".", "use", "(", "m", "[", ":klass", "]", ",", "m", "[", ":args", "]", ")", ":", "connection", ".", "use", "(", "m", "[", ":klass", "]", ")", "end", "# Request encoding", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Request", "::", "JsonEncoded", ")", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Request", "::", "UrlEncoded", ")", "# Automatic retries", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Request", "::", "Retry", ")", "# Raise exceptions on 4xx and 5xx errors", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Response", "::", "RaiseError", ")", "# Handle parsing out the response if it's JSON", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "Response", "::", "ParseJson", ")", "# Set up instrumentation around the adapter for extensibility", "connection", ".", "use", "(", "FaradayMiddleware", "::", "Instrumentation", ")", "# Add in extra env data if needed", "connection", ".", "use", "(", "Saddle", "::", "Middleware", "::", "ExtraEnv", ")", "# Set up our adapter", "if", "@stubs", ".", "nil?", "# Use the default adapter", "connection", ".", "adapter", "(", "@http_adapter", "[", ":key", "]", ",", "@http_adapter", "[", ":args", "]", ")", "else", "# Use the test adapter", "connection", ".", "adapter", "(", ":test", ",", "@stubs", ")", "end", "end", "end" ]
Build a connection instance, wrapped in the middleware that we want
[ "Build", "a", "connection", "instance", "wrapped", "in", "the", "middleware", "that", "we", "want" ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/requester.rb#L134-L190
5,602
devs-ruby/devs
lib/devs/container.rb
DEVS.Container.remove_child
def remove_child(child) child = child.name if child.is_a?(Model) children.delete(child) end
ruby
def remove_child(child) child = child.name if child.is_a?(Model) children.delete(child) end
[ "def", "remove_child", "(", "child", ")", "child", "=", "child", ".", "name", "if", "child", ".", "is_a?", "(", "Model", ")", "children", ".", "delete", "(", "child", ")", "end" ]
Deletes the specified child from children list @param child [Model,String,Symbol] the child to remove @return [Model] the deleted child, or nil if no matching component is found.
[ "Deletes", "the", "specified", "child", "from", "children", "list" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/container.rb#L57-L60
5,603
devs-ruby/devs
lib/devs/container.rb
DEVS.Container.attach
def attach(p1, to:, between: nil, and: nil) p2 = to sender = between # use binding#local_variable_get because 'and:' keyword argument clashes # with the language reserved keyword. receiver = binding.local_variable_get(:and) raise ArgumentError.new("'between:' keyword was omitted, 'p1' should be a Port.") if sender.nil? && !p1.is_a?(Port) raise ArgumentError.new("'and:' keyword was omitted, 'to:' should be a Port") if receiver.nil? && !p2.is_a?(Port) a = if p1.is_a?(Port) then p1.host elsif sender.is_a?(Coupleable) then sender elsif sender == @name then self else fetch_child(sender); end b = if p2.is_a?(Port) then p2.host elsif receiver.is_a?(Coupleable) then receiver elsif receiver == @name then self else fetch_child(receiver); end if has_child?(a) && has_child?(b) # IC p1 = a.output_port(p1) unless p1.is_a?(Port) p2 = b.input_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.output? && p2.input? raise FeedbackLoopError.new("#{a} must be different than #{b}") if a.object_id == b.object_id _internal_couplings[p1] << p2 elsif a == self && has_child?(b) # EIC p1 = a.input_port(p1) unless p1.is_a?(Port) p2 = b.input_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.input? && p2.input? _input_couplings[p1] << p2 elsif has_child?(a) && b == self # EOC p1 = a.output_port(p1) unless p1.is_a?(Port) p2 = b.output_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.output? && p2.output? _output_couplings[p1] << p2 else raise InvalidPortHostError.new("Illegal coupling between #{p1} and #{p2}") end end
ruby
def attach(p1, to:, between: nil, and: nil) p2 = to sender = between # use binding#local_variable_get because 'and:' keyword argument clashes # with the language reserved keyword. receiver = binding.local_variable_get(:and) raise ArgumentError.new("'between:' keyword was omitted, 'p1' should be a Port.") if sender.nil? && !p1.is_a?(Port) raise ArgumentError.new("'and:' keyword was omitted, 'to:' should be a Port") if receiver.nil? && !p2.is_a?(Port) a = if p1.is_a?(Port) then p1.host elsif sender.is_a?(Coupleable) then sender elsif sender == @name then self else fetch_child(sender); end b = if p2.is_a?(Port) then p2.host elsif receiver.is_a?(Coupleable) then receiver elsif receiver == @name then self else fetch_child(receiver); end if has_child?(a) && has_child?(b) # IC p1 = a.output_port(p1) unless p1.is_a?(Port) p2 = b.input_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.output? && p2.input? raise FeedbackLoopError.new("#{a} must be different than #{b}") if a.object_id == b.object_id _internal_couplings[p1] << p2 elsif a == self && has_child?(b) # EIC p1 = a.input_port(p1) unless p1.is_a?(Port) p2 = b.input_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.input? && p2.input? _input_couplings[p1] << p2 elsif has_child?(a) && b == self # EOC p1 = a.output_port(p1) unless p1.is_a?(Port) p2 = b.output_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.output? && p2.output? _output_couplings[p1] << p2 else raise InvalidPortHostError.new("Illegal coupling between #{p1} and #{p2}") end end
[ "def", "attach", "(", "p1", ",", "to", ":", ",", "between", ":", "nil", ",", "and", ":", "nil", ")", "p2", "=", "to", "sender", "=", "between", "# use binding#local_variable_get because 'and:' keyword argument clashes", "# with the language reserved keyword.", "receiver", "=", "binding", ".", "local_variable_get", "(", ":and", ")", "raise", "ArgumentError", ".", "new", "(", "\"'between:' keyword was omitted, 'p1' should be a Port.\"", ")", "if", "sender", ".", "nil?", "&&", "!", "p1", ".", "is_a?", "(", "Port", ")", "raise", "ArgumentError", ".", "new", "(", "\"'and:' keyword was omitted, 'to:' should be a Port\"", ")", "if", "receiver", ".", "nil?", "&&", "!", "p2", ".", "is_a?", "(", "Port", ")", "a", "=", "if", "p1", ".", "is_a?", "(", "Port", ")", "then", "p1", ".", "host", "elsif", "sender", ".", "is_a?", "(", "Coupleable", ")", "then", "sender", "elsif", "sender", "==", "@name", "then", "self", "else", "fetch_child", "(", "sender", ")", ";", "end", "b", "=", "if", "p2", ".", "is_a?", "(", "Port", ")", "then", "p2", ".", "host", "elsif", "receiver", ".", "is_a?", "(", "Coupleable", ")", "then", "receiver", "elsif", "receiver", "==", "@name", "then", "self", "else", "fetch_child", "(", "receiver", ")", ";", "end", "if", "has_child?", "(", "a", ")", "&&", "has_child?", "(", "b", ")", "# IC", "p1", "=", "a", ".", "output_port", "(", "p1", ")", "unless", "p1", ".", "is_a?", "(", "Port", ")", "p2", "=", "b", ".", "input_port", "(", "p2", ")", "unless", "p2", ".", "is_a?", "(", "Port", ")", "raise", "InvalidPortTypeError", ".", "new", "unless", "p1", ".", "output?", "&&", "p2", ".", "input?", "raise", "FeedbackLoopError", ".", "new", "(", "\"#{a} must be different than #{b}\"", ")", "if", "a", ".", "object_id", "==", "b", ".", "object_id", "_internal_couplings", "[", "p1", "]", "<<", "p2", "elsif", "a", "==", "self", "&&", "has_child?", "(", "b", ")", "# EIC", "p1", "=", "a", ".", "input_port", "(", "p1", ")", "unless", "p1", ".", "is_a?", "(", "Port", ")", "p2", "=", "b", ".", "input_port", "(", "p2", ")", "unless", "p2", ".", "is_a?", "(", "Port", ")", "raise", "InvalidPortTypeError", ".", "new", "unless", "p1", ".", "input?", "&&", "p2", ".", "input?", "_input_couplings", "[", "p1", "]", "<<", "p2", "elsif", "has_child?", "(", "a", ")", "&&", "b", "==", "self", "# EOC", "p1", "=", "a", ".", "output_port", "(", "p1", ")", "unless", "p1", ".", "is_a?", "(", "Port", ")", "p2", "=", "b", ".", "output_port", "(", "p2", ")", "unless", "p2", ".", "is_a?", "(", "Port", ")", "raise", "InvalidPortTypeError", ".", "new", "unless", "p1", ".", "output?", "&&", "p2", ".", "output?", "_output_couplings", "[", "p1", "]", "<<", "p2", "else", "raise", "InvalidPortHostError", ".", "new", "(", "\"Illegal coupling between #{p1} and #{p2}\"", ")", "end", "end" ]
Adds a coupling to self between two ports. Depending on *p1* and *to* hosts, the function will create an internal coupling (IC), an external input coupling (EIC) or an external output coupling (EOC). @overload attach(p1, to:) @param p1 [Port] the sender port of the coupling @param to [Port] the receiver port of the coupling @overload attach(p1, to:, between:, and:) @param p1 [Port,Symbol,String] the sender port of the coupling @param to [Port,Symbol,String] the receiver port of the coupling @param between [Coupleable,Symbol,String] the sender @param and [Coupleable,Symbol,String] the receiver @raise [FeedbackLoopError] if *p1* and *p2* hosts are the same child when constructing an internal coupling. Direct feedback loops are not allowed, i.e, no output port of a component may be connected to an input port of the same component. @raise [InvalidPortTypeError] if given ports are not of the expected IO modes (:input or :output). @raise [InvalidPortHostError] if no coupling can be established from given ports hosts. @note If given port names *p1* and *p2* doesn't exist within their host (respectively *sender* and *receiver*), they will be automatically generated. @example Attach two ports together to form a new coupling attach component1.output_port(:out) to: component2.input_port(:in) # IC attach self.input_port(:in) to: child.input_port(:in) # EIC attach child.output_port(:out) to: self.output_port(:out) # EOC @example Attach specified ports and components to form a new coupling attach :out, to: :in, between: :component1, and: :component2 attach :in, to: :in, between: self, and: child
[ "Adds", "a", "coupling", "to", "self", "between", "two", "ports", "." ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/container.rb#L257-L296
5,604
suculent/apprepo
lib/apprepo/manifest.rb
AppRepo.Manifest.manifest_as_json
def manifest_as_json structure = { appcode: appcode, filename: filename, bundle_identifier: bundle_identifier, bundle_version: bundle_version, title: title, subtitle: subtitle, notify: notify } fputs structure end
ruby
def manifest_as_json structure = { appcode: appcode, filename: filename, bundle_identifier: bundle_identifier, bundle_version: bundle_version, title: title, subtitle: subtitle, notify: notify } fputs structure end
[ "def", "manifest_as_json", "structure", "=", "{", "appcode", ":", "appcode", ",", "filename", ":", "filename", ",", "bundle_identifier", ":", "bundle_identifier", ",", "bundle_version", ":", "bundle_version", ",", "title", ":", "title", ",", "subtitle", ":", "subtitle", ",", "notify", ":", "notify", "}", "fputs", "structure", "end" ]
Provide JSON serialized data
[ "Provide", "JSON", "serialized", "data" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/manifest.rb#L28-L40
5,605
eanlain/calligraphy
lib/calligraphy/resource/file_resource.rb
Calligraphy.FileResource.copy_options
def copy_options(options) copy_options = { can_copy: false, ancestor_exist: false, locked: false } destination = copy_destination options to_path = join_paths @root_dir, destination to_path_exists = File.exist? to_path copy_options[:ancestor_exist] = File.exist? parent_path destination copy_options[:locked] = can_copy_locked_option to_path, to_path_exists copy_options = can_copy_option copy_options, options, to_path_exists copy_options end
ruby
def copy_options(options) copy_options = { can_copy: false, ancestor_exist: false, locked: false } destination = copy_destination options to_path = join_paths @root_dir, destination to_path_exists = File.exist? to_path copy_options[:ancestor_exist] = File.exist? parent_path destination copy_options[:locked] = can_copy_locked_option to_path, to_path_exists copy_options = can_copy_option copy_options, options, to_path_exists copy_options end
[ "def", "copy_options", "(", "options", ")", "copy_options", "=", "{", "can_copy", ":", "false", ",", "ancestor_exist", ":", "false", ",", "locked", ":", "false", "}", "destination", "=", "copy_destination", "options", "to_path", "=", "join_paths", "@root_dir", ",", "destination", "to_path_exists", "=", "File", ".", "exist?", "to_path", "copy_options", "[", ":ancestor_exist", "]", "=", "File", ".", "exist?", "parent_path", "destination", "copy_options", "[", ":locked", "]", "=", "can_copy_locked_option", "to_path", ",", "to_path_exists", "copy_options", "=", "can_copy_option", "copy_options", ",", "options", ",", "to_path_exists", "copy_options", "end" ]
Responsible for returning a hash with keys indicating if the resource can be copied, if an ancestor exists, or if the copy destinatin is locked. Return hash should contain `can_copy`, `ancestor_exist`, and `locked` keys with boolean values. Used in COPY and MOVE (which inherits from COPY) requests.
[ "Responsible", "for", "returning", "a", "hash", "with", "keys", "indicating", "if", "the", "resource", "can", "be", "copied", "if", "an", "ancestor", "exists", "or", "if", "the", "copy", "destinatin", "is", "locked", "." ]
19290d38322287fcb8e0152a7ed3b7f01033b57e
https://github.com/eanlain/calligraphy/blob/19290d38322287fcb8e0152a7ed3b7f01033b57e/lib/calligraphy/resource/file_resource.rb#L73-L84
5,606
fulldecent/structured-acceptance-test
implementations/ruby/lib/process.rb
StatModule.Process.print
def print(formatted = nil) result = name unless version.nil? result += ", version #{version}" end if formatted result = "#{FORMATTING_STAR.colorize(:yellow)} #{result}" end result end
ruby
def print(formatted = nil) result = name unless version.nil? result += ", version #{version}" end if formatted result = "#{FORMATTING_STAR.colorize(:yellow)} #{result}" end result end
[ "def", "print", "(", "formatted", "=", "nil", ")", "result", "=", "name", "unless", "version", ".", "nil?", "result", "+=", "\", version #{version}\"", "end", "if", "formatted", "result", "=", "\"#{FORMATTING_STAR.colorize(:yellow)} #{result}\"", "end", "result", "end" ]
Get formatted information about process Params: +formatted+:: indicate weather print boring or pretty colorful process
[ "Get", "formatted", "information", "about", "process" ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/process.rb#L141-L150
5,607
addagger/html_slicer
lib/html_slicer/interface.rb
HtmlSlicer.Interface.source
def source case options[:processors].present? when true then HtmlSlicer::Process.iterate(@env.send(@method_name), options[:processors]) else @env.send(@method_name) end end
ruby
def source case options[:processors].present? when true then HtmlSlicer::Process.iterate(@env.send(@method_name), options[:processors]) else @env.send(@method_name) end end
[ "def", "source", "case", "options", "[", ":processors", "]", ".", "present?", "when", "true", "then", "HtmlSlicer", "::", "Process", ".", "iterate", "(", "@env", ".", "send", "(", "@method_name", ")", ",", "options", "[", ":processors", "]", ")", "else", "@env", ".", "send", "(", "@method_name", ")", "end", "end" ]
Getting source content
[ "Getting", "source", "content" ]
bbe6ab55a0d0335621079c304af534959b518d8b
https://github.com/addagger/html_slicer/blob/bbe6ab55a0d0335621079c304af534959b518d8b/lib/html_slicer/interface.rb#L40-L46
5,608
addagger/html_slicer
lib/html_slicer/interface.rb
HtmlSlicer.Interface.slice!
def slice!(slice = nil) raise(Exception, "Slicing unavailable!") unless sliced? if slice.present? if slice.to_i.in?(1..slice_number) @current_slice = slice.to_i else raise(ArgumentError, "Slice number must be Integer in (1..#{slice_number}). #{slice.inspect} passed.") end end self end
ruby
def slice!(slice = nil) raise(Exception, "Slicing unavailable!") unless sliced? if slice.present? if slice.to_i.in?(1..slice_number) @current_slice = slice.to_i else raise(ArgumentError, "Slice number must be Integer in (1..#{slice_number}). #{slice.inspect} passed.") end end self end
[ "def", "slice!", "(", "slice", "=", "nil", ")", "raise", "(", "Exception", ",", "\"Slicing unavailable!\"", ")", "unless", "sliced?", "if", "slice", ".", "present?", "if", "slice", ".", "to_i", ".", "in?", "(", "1", "..", "slice_number", ")", "@current_slice", "=", "slice", ".", "to_i", "else", "raise", "(", "ArgumentError", ",", "\"Slice number must be Integer in (1..#{slice_number}). #{slice.inspect} passed.\"", ")", "end", "end", "self", "end" ]
General slicing method. Passing the argument changes the +current_slice+.
[ "General", "slicing", "method", ".", "Passing", "the", "argument", "changes", "the", "+", "current_slice", "+", "." ]
bbe6ab55a0d0335621079c304af534959b518d8b
https://github.com/addagger/html_slicer/blob/bbe6ab55a0d0335621079c304af534959b518d8b/lib/html_slicer/interface.rb#L99-L109
5,609
addagger/html_slicer
lib/html_slicer/interface.rb
HtmlSlicer.Interface.view
def view(node, slice, &block) slice = slice.to_i case node when ::HTML::Tag then children_view = node.children.map {|child| view(child, slice, &block)}.compact.join if resized? resizing.resize_node(node) end if sliced? if slicing.map.get(node, slice) || children_view.present? if node.closing == :close "</#{node.name}>" else s = "<#{node.name}" node.attributes.each do |k,v| s << " #{k}" s << "=\"#{v}\"" if String === v end s << " /" if node.closing == :self s << ">" s += children_view s << "</#{node.name}>" if node.closing != :self && !node.children.empty? s end end else node.to_s end when ::HTML::Text then if sliced? if range = slicing.map.get(node, slice) (range.is_a?(Array) ? node.content[Range.new(*range)] : node.content).tap do |export| unless range == true || (range.is_a?(Array) && range.last == -1) # broken text export << slicing.options.text_break if slicing.options.text_break if block_given? yield self, export end end end end else node.to_s end when ::HTML::CDATA then node.to_s when ::HTML::Node then node.children.map {|child| view(child, slice, &block)}.compact.join end end
ruby
def view(node, slice, &block) slice = slice.to_i case node when ::HTML::Tag then children_view = node.children.map {|child| view(child, slice, &block)}.compact.join if resized? resizing.resize_node(node) end if sliced? if slicing.map.get(node, slice) || children_view.present? if node.closing == :close "</#{node.name}>" else s = "<#{node.name}" node.attributes.each do |k,v| s << " #{k}" s << "=\"#{v}\"" if String === v end s << " /" if node.closing == :self s << ">" s += children_view s << "</#{node.name}>" if node.closing != :self && !node.children.empty? s end end else node.to_s end when ::HTML::Text then if sliced? if range = slicing.map.get(node, slice) (range.is_a?(Array) ? node.content[Range.new(*range)] : node.content).tap do |export| unless range == true || (range.is_a?(Array) && range.last == -1) # broken text export << slicing.options.text_break if slicing.options.text_break if block_given? yield self, export end end end end else node.to_s end when ::HTML::CDATA then node.to_s when ::HTML::Node then node.children.map {|child| view(child, slice, &block)}.compact.join end end
[ "def", "view", "(", "node", ",", "slice", ",", "&", "block", ")", "slice", "=", "slice", ".", "to_i", "case", "node", "when", "::", "HTML", "::", "Tag", "then", "children_view", "=", "node", ".", "children", ".", "map", "{", "|", "child", "|", "view", "(", "child", ",", "slice", ",", "block", ")", "}", ".", "compact", ".", "join", "if", "resized?", "resizing", ".", "resize_node", "(", "node", ")", "end", "if", "sliced?", "if", "slicing", ".", "map", ".", "get", "(", "node", ",", "slice", ")", "||", "children_view", ".", "present?", "if", "node", ".", "closing", "==", ":close", "\"</#{node.name}>\"", "else", "s", "=", "\"<#{node.name}\"", "node", ".", "attributes", ".", "each", "do", "|", "k", ",", "v", "|", "s", "<<", "\" #{k}\"", "s", "<<", "\"=\\\"#{v}\\\"\"", "if", "String", "===", "v", "end", "s", "<<", "\" /\"", "if", "node", ".", "closing", "==", ":self", "s", "<<", "\">\"", "s", "+=", "children_view", "s", "<<", "\"</#{node.name}>\"", "if", "node", ".", "closing", "!=", ":self", "&&", "!", "node", ".", "children", ".", "empty?", "s", "end", "end", "else", "node", ".", "to_s", "end", "when", "::", "HTML", "::", "Text", "then", "if", "sliced?", "if", "range", "=", "slicing", ".", "map", ".", "get", "(", "node", ",", "slice", ")", "(", "range", ".", "is_a?", "(", "Array", ")", "?", "node", ".", "content", "[", "Range", ".", "new", "(", "range", ")", "]", ":", "node", ".", "content", ")", ".", "tap", "do", "|", "export", "|", "unless", "range", "==", "true", "||", "(", "range", ".", "is_a?", "(", "Array", ")", "&&", "range", ".", "last", "==", "-", "1", ")", "# broken text", "export", "<<", "slicing", ".", "options", ".", "text_break", "if", "slicing", ".", "options", ".", "text_break", "if", "block_given?", "yield", "self", ",", "export", "end", "end", "end", "end", "else", "node", ".", "to_s", "end", "when", "::", "HTML", "::", "CDATA", "then", "node", ".", "to_s", "when", "::", "HTML", "::", "Node", "then", "node", ".", "children", ".", "map", "{", "|", "child", "|", "view", "(", "child", ",", "slice", ",", "block", ")", "}", ".", "compact", ".", "join", "end", "end" ]
Return a textual representation of the node including all children.
[ "Return", "a", "textual", "representation", "of", "the", "node", "including", "all", "children", "." ]
bbe6ab55a0d0335621079c304af534959b518d8b
https://github.com/addagger/html_slicer/blob/bbe6ab55a0d0335621079c304af534959b518d8b/lib/html_slicer/interface.rb#L138-L186
5,610
eprothro/cassie
lib/cassie/schema/versioning.rb
Cassie::Schema.Versioning.version
def version SelectVersionsQuery.new.fetch_first || Version.new('0') rescue Cassandra::Errors::InvalidError raise uninitialized_error end
ruby
def version SelectVersionsQuery.new.fetch_first || Version.new('0') rescue Cassandra::Errors::InvalidError raise uninitialized_error end
[ "def", "version", "SelectVersionsQuery", ".", "new", ".", "fetch_first", "||", "Version", ".", "new", "(", "'0'", ")", "rescue", "Cassandra", "::", "Errors", "::", "InvalidError", "raise", "uninitialized_error", "end" ]
The current schema version @return [Version]
[ "The", "current", "schema", "version" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/versioning.rb#L18-L22
5,611
eprothro/cassie
lib/cassie/schema/versioning.rb
Cassie::Schema.Versioning.record_version
def record_version(version, set_execution_metadata=true) time = Time.now version.id ||= Cassandra::TimeUuid::Generator.new.at(time) if set_execution_metadata version.executed_at = time version.executor = Etc.getlogin rescue '<unknown>' end InsertVersionQuery.new(version: version).execute! @applied_versions = nil rescue StandardError => e version.id = nil version.executed_at = nil version.executor = nil raise e end
ruby
def record_version(version, set_execution_metadata=true) time = Time.now version.id ||= Cassandra::TimeUuid::Generator.new.at(time) if set_execution_metadata version.executed_at = time version.executor = Etc.getlogin rescue '<unknown>' end InsertVersionQuery.new(version: version).execute! @applied_versions = nil rescue StandardError => e version.id = nil version.executed_at = nil version.executor = nil raise e end
[ "def", "record_version", "(", "version", ",", "set_execution_metadata", "=", "true", ")", "time", "=", "Time", ".", "now", "version", ".", "id", "||=", "Cassandra", "::", "TimeUuid", "::", "Generator", ".", "new", ".", "at", "(", "time", ")", "if", "set_execution_metadata", "version", ".", "executed_at", "=", "time", "version", ".", "executor", "=", "Etc", ".", "getlogin", "rescue", "'<unknown>'", "end", "InsertVersionQuery", ".", "new", "(", "version", ":", "version", ")", ".", "execute!", "@applied_versions", "=", "nil", "rescue", "StandardError", "=>", "e", "version", ".", "id", "=", "nil", "version", ".", "executed_at", "=", "nil", "version", ".", "executor", "=", "nil", "raise", "e", "end" ]
Record a version in the schema version store. This should only be done if the version has been sucesfully migrated @param [Version] The version to record @param [Boolean] set_execution_metadata Determines whether or not to populate the version object with execution tracking info (+id+, +executed_at+, and +executor+). @return [Boolean] whether succesfull or not @raises [StandardError] if version could not be recorded. If this happens, execution_metadata will not be preset on the version object.
[ "Record", "a", "version", "in", "the", "schema", "version", "store", ".", "This", "should", "only", "be", "done", "if", "the", "version", "has", "been", "sucesfully", "migrated" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/versioning.rb#L48-L64
5,612
eprothro/cassie
lib/cassie/schema/versioning.rb
Cassie::Schema.Versioning.load_applied_versions
def load_applied_versions database_versions.tap do |versions| versions.each{|v| VersionObjectLoader.new(v).load } end rescue Cassandra::Errors::InvalidError => e raise uninitialized_error end
ruby
def load_applied_versions database_versions.tap do |versions| versions.each{|v| VersionObjectLoader.new(v).load } end rescue Cassandra::Errors::InvalidError => e raise uninitialized_error end
[ "def", "load_applied_versions", "database_versions", ".", "tap", "do", "|", "versions", "|", "versions", ".", "each", "{", "|", "v", "|", "VersionObjectLoader", ".", "new", "(", "v", ")", ".", "load", "}", "end", "rescue", "Cassandra", "::", "Errors", "::", "InvalidError", "=>", "e", "raise", "uninitialized_error", "end" ]
load version migration class from disk
[ "load", "version", "migration", "class", "from", "disk" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/versioning.rb#L121-L127
5,613
mackwic/slack-rtmapi
lib/slack-rtmapi/client.rb
SlackRTM.Client.init
def init return if @has_been_init @socket = init_socket(@socket) @socket.connect # costly and blocking ! internalWrapper = (Struct.new :url, :socket do def write(*args) self.socket.write(*args) end end).new @url.to_s, @socket # this, also, is costly and blocking @driver = WebSocket::Driver.client internalWrapper @driver.on :open do @connected = true unless @callbacks[:open].nil? @callbacks[:open].call end end @driver.on :error do |event| @connected = false unless @callbacks[:error].nil? @callbacks[:error].call end end @driver.on :message do |event| data = JSON.parse event.data unless @callbacks[:message].nil? @callbacks[:message].call data end end @driver.start @has_been_init = true end
ruby
def init return if @has_been_init @socket = init_socket(@socket) @socket.connect # costly and blocking ! internalWrapper = (Struct.new :url, :socket do def write(*args) self.socket.write(*args) end end).new @url.to_s, @socket # this, also, is costly and blocking @driver = WebSocket::Driver.client internalWrapper @driver.on :open do @connected = true unless @callbacks[:open].nil? @callbacks[:open].call end end @driver.on :error do |event| @connected = false unless @callbacks[:error].nil? @callbacks[:error].call end end @driver.on :message do |event| data = JSON.parse event.data unless @callbacks[:message].nil? @callbacks[:message].call data end end @driver.start @has_been_init = true end
[ "def", "init", "return", "if", "@has_been_init", "@socket", "=", "init_socket", "(", "@socket", ")", "@socket", ".", "connect", "# costly and blocking !", "internalWrapper", "=", "(", "Struct", ".", "new", ":url", ",", ":socket", "do", "def", "write", "(", "*", "args", ")", "self", ".", "socket", ".", "write", "(", "args", ")", "end", "end", ")", ".", "new", "@url", ".", "to_s", ",", "@socket", "# this, also, is costly and blocking", "@driver", "=", "WebSocket", "::", "Driver", ".", "client", "internalWrapper", "@driver", ".", "on", ":open", "do", "@connected", "=", "true", "unless", "@callbacks", "[", ":open", "]", ".", "nil?", "@callbacks", "[", ":open", "]", ".", "call", "end", "end", "@driver", ".", "on", ":error", "do", "|", "event", "|", "@connected", "=", "false", "unless", "@callbacks", "[", ":error", "]", ".", "nil?", "@callbacks", "[", ":error", "]", ".", "call", "end", "end", "@driver", ".", "on", ":message", "do", "|", "event", "|", "data", "=", "JSON", ".", "parse", "event", ".", "data", "unless", "@callbacks", "[", ":message", "]", ".", "nil?", "@callbacks", "[", ":message", "]", ".", "call", "data", "end", "end", "@driver", ".", "start", "@has_been_init", "=", "true", "end" ]
This init has been delayed because the SSL handshake is a blocking and expensive call
[ "This", "init", "has", "been", "delayed", "because", "the", "SSL", "handshake", "is", "a", "blocking", "and", "expensive", "call" ]
5c217ba97dcab1801360b03cd3c26e8cab682fe9
https://github.com/mackwic/slack-rtmapi/blob/5c217ba97dcab1801360b03cd3c26e8cab682fe9/lib/slack-rtmapi/client.rb#L42-L78
5,614
mackwic/slack-rtmapi
lib/slack-rtmapi/client.rb
SlackRTM.Client.inner_loop
def inner_loop return if @stop data = @socket.readpartial 4096 return if data.nil? or data.empty? @driver.parse data @msg_queue.each {|msg| @driver.text msg} @msg_queue.clear end
ruby
def inner_loop return if @stop data = @socket.readpartial 4096 return if data.nil? or data.empty? @driver.parse data @msg_queue.each {|msg| @driver.text msg} @msg_queue.clear end
[ "def", "inner_loop", "return", "if", "@stop", "data", "=", "@socket", ".", "readpartial", "4096", "return", "if", "data", ".", "nil?", "or", "data", ".", "empty?", "@driver", ".", "parse", "data", "@msg_queue", ".", "each", "{", "|", "msg", "|", "@driver", ".", "text", "msg", "}", "@msg_queue", ".", "clear", "end" ]
All the polling work is done here
[ "All", "the", "polling", "work", "is", "done", "here" ]
5c217ba97dcab1801360b03cd3c26e8cab682fe9
https://github.com/mackwic/slack-rtmapi/blob/5c217ba97dcab1801360b03cd3c26e8cab682fe9/lib/slack-rtmapi/client.rb#L85-L93
5,615
bachya/cliutils
lib/cliutils/messenger.rb
CLIUtils.Messenger.error
def error(m) puts _word_wrap(m, '# ').red @targets.each { |_, t| t.error(m) } end
ruby
def error(m) puts _word_wrap(m, '# ').red @targets.each { |_, t| t.error(m) } end
[ "def", "error", "(", "m", ")", "puts", "_word_wrap", "(", "m", ",", "'# '", ")", ".", "red", "@targets", ".", "each", "{", "|", "_", ",", "t", "|", "t", ".", "error", "(", "m", ")", "}", "end" ]
Outputs a formatted-red error message. @param [String] m The message to output @return [void]
[ "Outputs", "a", "formatted", "-", "red", "error", "message", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/messenger.rb#L42-L45
5,616
bachya/cliutils
lib/cliutils/messenger.rb
CLIUtils.Messenger.info
def info(m) puts _word_wrap(m, '# ').blue @targets.each { |_, t| t.info(m) } end
ruby
def info(m) puts _word_wrap(m, '# ').blue @targets.each { |_, t| t.info(m) } end
[ "def", "info", "(", "m", ")", "puts", "_word_wrap", "(", "m", ",", "'# '", ")", ".", "blue", "@targets", ".", "each", "{", "|", "_", ",", "t", "|", "t", ".", "info", "(", "m", ")", "}", "end" ]
Outputs a formatted-blue informational message. @param [String] m The message to output @return [void]
[ "Outputs", "a", "formatted", "-", "blue", "informational", "message", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/messenger.rb#L50-L53
5,617
bachya/cliutils
lib/cliutils/messenger.rb
CLIUtils.Messenger.section
def section(m) puts _word_wrap(m, '---> ').purple @targets.each { |_, t| t.section(m) } end
ruby
def section(m) puts _word_wrap(m, '---> ').purple @targets.each { |_, t| t.section(m) } end
[ "def", "section", "(", "m", ")", "puts", "_word_wrap", "(", "m", ",", "'---> '", ")", ".", "purple", "@targets", ".", "each", "{", "|", "_", ",", "t", "|", "t", ".", "section", "(", "m", ")", "}", "end" ]
Outputs a formatted-purple section message. @param [String] m The message to output @return [void]
[ "Outputs", "a", "formatted", "-", "purple", "section", "message", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/messenger.rb#L97-L100
5,618
bachya/cliutils
lib/cliutils/messenger.rb
CLIUtils.Messenger.success
def success(m) puts _word_wrap(m, '# ').green @targets.each { |_, t| t.success(m) } end
ruby
def success(m) puts _word_wrap(m, '# ').green @targets.each { |_, t| t.success(m) } end
[ "def", "success", "(", "m", ")", "puts", "_word_wrap", "(", "m", ",", "'# '", ")", ".", "green", "@targets", ".", "each", "{", "|", "_", ",", "t", "|", "t", ".", "success", "(", "m", ")", "}", "end" ]
Outputs a formatted-green success message. @param [String] m The message to output @return [void]
[ "Outputs", "a", "formatted", "-", "green", "success", "message", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/messenger.rb#L105-L108
5,619
bachya/cliutils
lib/cliutils/messenger.rb
CLIUtils.Messenger.warn
def warn(m) puts _word_wrap(m, '# ').yellow @targets.each { |_, t| t.warn(m) } end
ruby
def warn(m) puts _word_wrap(m, '# ').yellow @targets.each { |_, t| t.warn(m) } end
[ "def", "warn", "(", "m", ")", "puts", "_word_wrap", "(", "m", ",", "'# '", ")", ".", "yellow", "@targets", ".", "each", "{", "|", "_", ",", "t", "|", "t", ".", "warn", "(", "m", ")", "}", "end" ]
Outputs a formatted-yellow warning message. @param [String] m The message to output @return [void]
[ "Outputs", "a", "formatted", "-", "yellow", "warning", "message", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/messenger.rb#L113-L116
5,620
ExerciciosResolvidos/latex_to_png
lib/latex_to_png.rb
LatexToPng.Convert.size_in_points
def size_in_points size_in_pixels size = Sizes.invert[size_in_pixels] return (size.nil?)? size_in_points("#{size_in_pixels.to_i + 1}px") : size end
ruby
def size_in_points size_in_pixels size = Sizes.invert[size_in_pixels] return (size.nil?)? size_in_points("#{size_in_pixels.to_i + 1}px") : size end
[ "def", "size_in_points", "size_in_pixels", "size", "=", "Sizes", ".", "invert", "[", "size_in_pixels", "]", "return", "(", "size", ".", "nil?", ")", "?", "size_in_points", "(", "\"#{size_in_pixels.to_i + 1}px\"", ")", ":", "size", "end" ]
or formula or filepath
[ "or", "formula", "or", "filepath" ]
527bb57b48022a69b76c69c7a4d9c7fb745c3125
https://github.com/ExerciciosResolvidos/latex_to_png/blob/527bb57b48022a69b76c69c7a4d9c7fb745c3125/lib/latex_to_png.rb#L56-L59
5,621
nysa/ruby-opencnam
lib/opencnam/parsers.rb
Opencnam.Parsers.parse_json
def parse_json(json) hash = JSON.parse(json, :symbolize_names => true) # Convert hash[:created] and hash[:updated] to Time objects if hash[:created] hash.merge!({ :created => parse_iso_date_string(hash[:created]) }) end if hash[:updated] hash.merge!({ :updated => parse_iso_date_string(hash[:updated]) }) end hash end
ruby
def parse_json(json) hash = JSON.parse(json, :symbolize_names => true) # Convert hash[:created] and hash[:updated] to Time objects if hash[:created] hash.merge!({ :created => parse_iso_date_string(hash[:created]) }) end if hash[:updated] hash.merge!({ :updated => parse_iso_date_string(hash[:updated]) }) end hash end
[ "def", "parse_json", "(", "json", ")", "hash", "=", "JSON", ".", "parse", "(", "json", ",", ":symbolize_names", "=>", "true", ")", "# Convert hash[:created] and hash[:updated] to Time objects", "if", "hash", "[", ":created", "]", "hash", ".", "merge!", "(", "{", ":created", "=>", "parse_iso_date_string", "(", "hash", "[", ":created", "]", ")", "}", ")", "end", "if", "hash", "[", ":updated", "]", "hash", ".", "merge!", "(", "{", ":updated", "=>", "parse_iso_date_string", "(", "hash", "[", ":updated", "]", ")", "}", ")", "end", "hash", "end" ]
Parses a JSON string. @param [String] json the JSON formatted string @return [Hash]
[ "Parses", "a", "JSON", "string", "." ]
7c9e62f6efc59466ab307977bc04070d19c4cadf
https://github.com/nysa/ruby-opencnam/blob/7c9e62f6efc59466ab307977bc04070d19c4cadf/lib/opencnam/parsers.rb#L18-L31
5,622
upserve/giraph
lib/giraph/schema.rb
Giraph.Schema.execute
def execute(query, **args) args = args .merge(with_giraph_root(args)) .merge(with_giraph_resolvers(args)) super(query, **args) end
ruby
def execute(query, **args) args = args .merge(with_giraph_root(args)) .merge(with_giraph_resolvers(args)) super(query, **args) end
[ "def", "execute", "(", "query", ",", "**", "args", ")", "args", "=", "args", ".", "merge", "(", "with_giraph_root", "(", "args", ")", ")", ".", "merge", "(", "with_giraph_resolvers", "(", "args", ")", ")", "super", "(", "query", ",", "**", "args", ")", "end" ]
Extract special arguments for resolver objects, let the rest pass-through Defer the execution only after setting up context and root_value with resolvers and remote arguments
[ "Extract", "special", "arguments", "for", "resolver", "objects", "let", "the", "rest", "pass", "-", "through", "Defer", "the", "execution", "only", "after", "setting", "up", "context", "and", "root_value", "with", "resolvers", "and", "remote", "arguments" ]
b3d26bbf29d4e9ef8a5787ccb4c4e2bc9d36cd4f
https://github.com/upserve/giraph/blob/b3d26bbf29d4e9ef8a5787ccb4c4e2bc9d36cd4f/lib/giraph/schema.rb#L15-L21
5,623
igor-makarov/cocoapods-repo-cdn
lib/cdn_source.rb
Pod.CDNSource.specification_path
def specification_path(name, version) raise ArgumentError, 'No name' unless name raise ArgumentError, 'No version' unless version relative_podspec = pod_path_partial(name).join("#{version}/#{name}.podspec.json") download_file(relative_podspec) pod_path(name).join("#{version}/#{name}.podspec.json") end
ruby
def specification_path(name, version) raise ArgumentError, 'No name' unless name raise ArgumentError, 'No version' unless version relative_podspec = pod_path_partial(name).join("#{version}/#{name}.podspec.json") download_file(relative_podspec) pod_path(name).join("#{version}/#{name}.podspec.json") end
[ "def", "specification_path", "(", "name", ",", "version", ")", "raise", "ArgumentError", ",", "'No name'", "unless", "name", "raise", "ArgumentError", ",", "'No version'", "unless", "version", "relative_podspec", "=", "pod_path_partial", "(", "name", ")", ".", "join", "(", "\"#{version}/#{name}.podspec.json\"", ")", "download_file", "(", "relative_podspec", ")", "pod_path", "(", "name", ")", ".", "join", "(", "\"#{version}/#{name}.podspec.json\"", ")", "end" ]
Returns the path of the specification with the given name and version. @param [String] name the name of the Pod. @param [Version,String] version the version for the specification. @return [Pathname] The path of the specification.
[ "Returns", "the", "path", "of", "the", "specification", "with", "the", "given", "name", "and", "version", "." ]
45d9d3fc779297ec9c67312de2f9bb819d29ba8d
https://github.com/igor-makarov/cocoapods-repo-cdn/blob/45d9d3fc779297ec9c67312de2f9bb819d29ba8d/lib/cdn_source.rb#L174-L181
5,624
rthbound/pay_dirt
lib/pay_dirt/use_case.rb
PayDirt.UseCase.load_options
def load_options(*required_options, options) # Load required options required_options.each { |o| options = load_option(o, options) } # Load remaining options options.each_key { |k| options = load_option(k, options) } block_given? ? yield : options end
ruby
def load_options(*required_options, options) # Load required options required_options.each { |o| options = load_option(o, options) } # Load remaining options options.each_key { |k| options = load_option(k, options) } block_given? ? yield : options end
[ "def", "load_options", "(", "*", "required_options", ",", "options", ")", "# Load required options", "required_options", ".", "each", "{", "|", "o", "|", "options", "=", "load_option", "(", "o", ",", "options", ")", "}", "# Load remaining options", "options", ".", "each_key", "{", "|", "k", "|", "options", "=", "load_option", "(", "k", ",", "options", ")", "}", "block_given?", "?", "yield", ":", "options", "end" ]
Load instance variables from the provided hash of dependencies. Raises if any required dependencies (+required_options+) are missing from +options+ hash. Optionally, takes and yields a block after loading options. Use this to validate dependencies. @param [List<String,Symbol>] option_names list of keys representing required dependencies @param [Hash] options A hash of dependencies @public
[ "Load", "instance", "variables", "from", "the", "provided", "hash", "of", "dependencies", "." ]
9bf92cb1125e2e5f6eb08600b6c7f33e5030291c
https://github.com/rthbound/pay_dirt/blob/9bf92cb1125e2e5f6eb08600b6c7f33e5030291c/lib/pay_dirt/use_case.rb#L17-L25
5,625
mLewisLogic/saddle
lib/saddle/method_tree_builder.rb
Saddle.MethodTreeBuilder.build_tree
def build_tree(requester) root_node = build_root_node(requester) # Search out the implementations directory structure for endpoints if defined?(self.implementation_root) # For each endpoints directory, recurse down it to load the modules endpoints_directories.each do |endpoints_directories| Dir["#{endpoints_directories}/**/*.rb"].each { |f| require(f) } end build_node_children(self.endpoints_module, root_node, requester) end root_node end
ruby
def build_tree(requester) root_node = build_root_node(requester) # Search out the implementations directory structure for endpoints if defined?(self.implementation_root) # For each endpoints directory, recurse down it to load the modules endpoints_directories.each do |endpoints_directories| Dir["#{endpoints_directories}/**/*.rb"].each { |f| require(f) } end build_node_children(self.endpoints_module, root_node, requester) end root_node end
[ "def", "build_tree", "(", "requester", ")", "root_node", "=", "build_root_node", "(", "requester", ")", "# Search out the implementations directory structure for endpoints", "if", "defined?", "(", "self", ".", "implementation_root", ")", "# For each endpoints directory, recurse down it to load the modules", "endpoints_directories", ".", "each", "do", "|", "endpoints_directories", "|", "Dir", "[", "\"#{endpoints_directories}/**/*.rb\"", "]", ".", "each", "{", "|", "f", "|", "require", "(", "f", ")", "}", "end", "build_node_children", "(", "self", ".", "endpoints_module", ",", "root_node", ",", "requester", ")", "end", "root_node", "end" ]
Build out the endpoint structure from the root of the implementation
[ "Build", "out", "the", "endpoint", "structure", "from", "the", "root", "of", "the", "implementation" ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/method_tree_builder.rb#L17-L28
5,626
mLewisLogic/saddle
lib/saddle/method_tree_builder.rb
Saddle.MethodTreeBuilder.build_root_node
def build_root_node(requester) if defined?(self.implementation_root) root_endpoint_file = File.join( self.implementation_root, 'root_endpoint.rb' ) if File.file?(root_endpoint_file) warn "[DEPRECATION] `root_endpoint.rb` is deprecated. Please use `ABSOLUTE_PATH` in your endpoints." # Load it and create our base endpoint require(root_endpoint_file) # RootEndpoint is the special class name for a root endpoint root_node_class = self.implementation_module::RootEndpoint else # 'root_endpoint.rb' doesn't exist, so create a dummy endpoint root_node_class = Saddle::RootEndpoint end else # we don't even have an implementation root, so create a dummy endpoint root_node_class = Saddle::RootEndpoint end root_node_class.new(requester, nil, self) end
ruby
def build_root_node(requester) if defined?(self.implementation_root) root_endpoint_file = File.join( self.implementation_root, 'root_endpoint.rb' ) if File.file?(root_endpoint_file) warn "[DEPRECATION] `root_endpoint.rb` is deprecated. Please use `ABSOLUTE_PATH` in your endpoints." # Load it and create our base endpoint require(root_endpoint_file) # RootEndpoint is the special class name for a root endpoint root_node_class = self.implementation_module::RootEndpoint else # 'root_endpoint.rb' doesn't exist, so create a dummy endpoint root_node_class = Saddle::RootEndpoint end else # we don't even have an implementation root, so create a dummy endpoint root_node_class = Saddle::RootEndpoint end root_node_class.new(requester, nil, self) end
[ "def", "build_root_node", "(", "requester", ")", "if", "defined?", "(", "self", ".", "implementation_root", ")", "root_endpoint_file", "=", "File", ".", "join", "(", "self", ".", "implementation_root", ",", "'root_endpoint.rb'", ")", "if", "File", ".", "file?", "(", "root_endpoint_file", ")", "warn", "\"[DEPRECATION] `root_endpoint.rb` is deprecated. Please use `ABSOLUTE_PATH` in your endpoints.\"", "# Load it and create our base endpoint", "require", "(", "root_endpoint_file", ")", "# RootEndpoint is the special class name for a root endpoint", "root_node_class", "=", "self", ".", "implementation_module", "::", "RootEndpoint", "else", "# 'root_endpoint.rb' doesn't exist, so create a dummy endpoint", "root_node_class", "=", "Saddle", "::", "RootEndpoint", "end", "else", "# we don't even have an implementation root, so create a dummy endpoint", "root_node_class", "=", "Saddle", "::", "RootEndpoint", "end", "root_node_class", ".", "new", "(", "requester", ",", "nil", ",", "self", ")", "end" ]
Build our root node here. The root node is special in that it lives below the 'endpoints' directory, and so we need to manually check if it exists.
[ "Build", "our", "root", "node", "here", ".", "The", "root", "node", "is", "special", "in", "that", "it", "lives", "below", "the", "endpoints", "directory", "and", "so", "we", "need", "to", "manually", "check", "if", "it", "exists", "." ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/method_tree_builder.rb#L33-L54
5,627
mLewisLogic/saddle
lib/saddle/method_tree_builder.rb
Saddle.MethodTreeBuilder.build_node_children
def build_node_children(current_module, current_node, requester) return unless current_module current_module.constants.each do |const_symbol| const = current_module.const_get(const_symbol) if const.class == Module # A module means that it's a branch # Build the branch out with a base endpoint branch_node = current_node._build_and_attach_node( Saddle::TraversalEndpoint, const_symbol.to_s.underscore ) # Build out the branch's endpoints on the new branch node self.build_node_children(const, branch_node, requester) end if const < Saddle::TraversalEndpoint # A class means that it's a node # Build out this endpoint on the current node current_node._build_and_attach_node(const) end end end
ruby
def build_node_children(current_module, current_node, requester) return unless current_module current_module.constants.each do |const_symbol| const = current_module.const_get(const_symbol) if const.class == Module # A module means that it's a branch # Build the branch out with a base endpoint branch_node = current_node._build_and_attach_node( Saddle::TraversalEndpoint, const_symbol.to_s.underscore ) # Build out the branch's endpoints on the new branch node self.build_node_children(const, branch_node, requester) end if const < Saddle::TraversalEndpoint # A class means that it's a node # Build out this endpoint on the current node current_node._build_and_attach_node(const) end end end
[ "def", "build_node_children", "(", "current_module", ",", "current_node", ",", "requester", ")", "return", "unless", "current_module", "current_module", ".", "constants", ".", "each", "do", "|", "const_symbol", "|", "const", "=", "current_module", ".", "const_get", "(", "const_symbol", ")", "if", "const", ".", "class", "==", "Module", "# A module means that it's a branch", "# Build the branch out with a base endpoint", "branch_node", "=", "current_node", ".", "_build_and_attach_node", "(", "Saddle", "::", "TraversalEndpoint", ",", "const_symbol", ".", "to_s", ".", "underscore", ")", "# Build out the branch's endpoints on the new branch node", "self", ".", "build_node_children", "(", "const", ",", "branch_node", ",", "requester", ")", "end", "if", "const", "<", "Saddle", "::", "TraversalEndpoint", "# A class means that it's a node", "# Build out this endpoint on the current node", "current_node", ".", "_build_and_attach_node", "(", "const", ")", "end", "end", "end" ]
Build out the traversal tree by module namespace
[ "Build", "out", "the", "traversal", "tree", "by", "module", "namespace" ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/method_tree_builder.rb#L58-L80
5,628
FormAPI/formapi-ruby
lib/form_api/api/client.rb
FormAPI.Client.combine_submissions
def combine_submissions(options) unless options[:submission_ids].is_a?(::Array) raise InvalidDataError, "submission_ids is required, and must be an Array." end options[:source_pdfs] = options[:submission_ids].map do |id| { type: 'submission', id: id } end options.delete :submission_ids combine_pdfs(options) end
ruby
def combine_submissions(options) unless options[:submission_ids].is_a?(::Array) raise InvalidDataError, "submission_ids is required, and must be an Array." end options[:source_pdfs] = options[:submission_ids].map do |id| { type: 'submission', id: id } end options.delete :submission_ids combine_pdfs(options) end
[ "def", "combine_submissions", "(", "options", ")", "unless", "options", "[", ":submission_ids", "]", ".", "is_a?", "(", "::", "Array", ")", "raise", "InvalidDataError", ",", "\"submission_ids is required, and must be an Array.\"", "end", "options", "[", ":source_pdfs", "]", "=", "options", "[", ":submission_ids", "]", ".", "map", "do", "|", "id", "|", "{", "type", ":", "'submission'", ",", "id", ":", "id", "}", "end", "options", ".", "delete", ":submission_ids", "combine_pdfs", "(", "options", ")", "end" ]
Alias for combine_pdfs, for backwards compatibility
[ "Alias", "for", "combine_pdfs", "for", "backwards", "compatibility" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/client.rb#L143-L153
5,629
devs-ruby/devs
lib/devs/atomic_model.rb
DEVS.AtomicModel.ensure_output_port
def ensure_output_port(port) raise ArgumentError, "port argument cannot be nil" if port.nil? unless port.kind_of?(Port) port = output_port(port) raise ArgumentError, "the given port doesn't exists" if port.nil? end unless port.host == self raise InvalidPortHostError, "The given port doesn't belong to this \ model" end unless port.output? raise InvalidPortTypeError, "The given port isn't an output port" end port end
ruby
def ensure_output_port(port) raise ArgumentError, "port argument cannot be nil" if port.nil? unless port.kind_of?(Port) port = output_port(port) raise ArgumentError, "the given port doesn't exists" if port.nil? end unless port.host == self raise InvalidPortHostError, "The given port doesn't belong to this \ model" end unless port.output? raise InvalidPortTypeError, "The given port isn't an output port" end port end
[ "def", "ensure_output_port", "(", "port", ")", "raise", "ArgumentError", ",", "\"port argument cannot be nil\"", "if", "port", ".", "nil?", "unless", "port", ".", "kind_of?", "(", "Port", ")", "port", "=", "output_port", "(", "port", ")", "raise", "ArgumentError", ",", "\"the given port doesn't exists\"", "if", "port", ".", "nil?", "end", "unless", "port", ".", "host", "==", "self", "raise", "InvalidPortHostError", ",", "\"The given port doesn't belong to this \\\n model\"", "end", "unless", "port", ".", "output?", "raise", "InvalidPortTypeError", ",", "\"The given port isn't an output port\"", "end", "port", "end" ]
Finds and checks if the given port is an output port @api private @param port [Port, String, Symbol] the port or its name @return [Port] the matching port @raise [NoSuchPortError] if the given port doesn't exists @raise [InvalidPortHostError] if the given port doesn't belong to this model @raise [InvalidPortTypeError] if the given port isn't an output port
[ "Finds", "and", "checks", "if", "the", "given", "port", "is", "an", "output", "port" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/atomic_model.rb#L95-L109
5,630
j0hnds/cron-spec
lib/cron-spec/cron_specification.rb
CronSpec.CronSpecification.is_specification_in_effect?
def is_specification_in_effect?(time=Time.now) idx = 0 test_results = @cron_values.collect do | cvalues | time_value = time.send(TimeMethods[idx]) idx += 1 !cvalues.detect { | cv | cv.is_effective?(time_value) }.nil? end.all? end
ruby
def is_specification_in_effect?(time=Time.now) idx = 0 test_results = @cron_values.collect do | cvalues | time_value = time.send(TimeMethods[idx]) idx += 1 !cvalues.detect { | cv | cv.is_effective?(time_value) }.nil? end.all? end
[ "def", "is_specification_in_effect?", "(", "time", "=", "Time", ".", "now", ")", "idx", "=", "0", "test_results", "=", "@cron_values", ".", "collect", "do", "|", "cvalues", "|", "time_value", "=", "time", ".", "send", "(", "TimeMethods", "[", "idx", "]", ")", "idx", "+=", "1", "!", "cvalues", ".", "detect", "{", "|", "cv", "|", "cv", ".", "is_effective?", "(", "time_value", ")", "}", ".", "nil?", "end", ".", "all?", "end" ]
Constructs a new CronSpecification with a textual cron specificiation. A broad cron syntax is supported: * * * * * - - - - - | | | | | | | | | +----- day of week (0 - 6) (Sunday=0) | | | +---------- month (1 - 12) | | +--------------- day of month (1 - 31) | +-------------------- hour (0 - 23) +------------------------- min (0 - 59) The following named entries can be used: * Day of week - sun, mon, tue, wed, thu, fri, sat * Month - jan feb mar apr may jun jul aug sep oct nov dec The following constructs are supported: * Ranges are supported (e.g. 2-10 or mon-fri) * Multiple values are supported (e.g. 2,3,8 or mon,wed,fri) * Wildcards are supported (e.g. *) * Step values are supported (e.g. */4) * Combinations of all but wildcard are supported (e.g. 2,*/3,8-10) A single space is required between each group. Return true if the specified time falls within the definition of the CronSpecification. The parameter defaults to the current time.
[ "Constructs", "a", "new", "CronSpecification", "with", "a", "textual", "cron", "specificiation", "." ]
ac6dfa5cb312ec6d855ddde4e46d0bf2916121aa
https://github.com/j0hnds/cron-spec/blob/ac6dfa5cb312ec6d855ddde4e46d0bf2916121aa/lib/cron-spec/cron_specification.rb#L89-L97
5,631
thelazycamel/rubychain
lib/rubychain/block.rb
Rubychain.Block.hash_block
def hash_block hash_string = [index,timestamp,data,prev_hash].join sha = Digest::SHA256.new sha.update(hash_string) sha.hexdigest end
ruby
def hash_block hash_string = [index,timestamp,data,prev_hash].join sha = Digest::SHA256.new sha.update(hash_string) sha.hexdigest end
[ "def", "hash_block", "hash_string", "=", "[", "index", ",", "timestamp", ",", "data", ",", "prev_hash", "]", ".", "join", "sha", "=", "Digest", "::", "SHA256", ".", "new", "sha", ".", "update", "(", "hash_string", ")", "sha", ".", "hexdigest", "end" ]
Create the blocks hash by encrypting all the blocks data using SHA256
[ "Create", "the", "blocks", "hash", "by", "encrypting", "all", "the", "blocks", "data", "using", "SHA256" ]
7671fe6d25f818a88c8a62c3167438837d37740d
https://github.com/thelazycamel/rubychain/blob/7671fe6d25f818a88c8a62c3167438837d37740d/lib/rubychain/block.rb#L18-L23
5,632
bachya/cliutils
lib/cliutils/prefs.rb
CLIUtils.Prefs.ask
def ask # First, deliver all the prompts that don't have # any prerequisites. @prompts.reject { |p| p.prereqs }.each do |p| _deliver_prompt(p) end # After the "non-prerequisite" prompts are delivered, # deliver any that require prerequisites. @prompts.select { |p| p.prereqs }.each do |p| _deliver_prompt(p) if _prereqs_fulfilled?(p) end end
ruby
def ask # First, deliver all the prompts that don't have # any prerequisites. @prompts.reject { |p| p.prereqs }.each do |p| _deliver_prompt(p) end # After the "non-prerequisite" prompts are delivered, # deliver any that require prerequisites. @prompts.select { |p| p.prereqs }.each do |p| _deliver_prompt(p) if _prereqs_fulfilled?(p) end end
[ "def", "ask", "# First, deliver all the prompts that don't have", "# any prerequisites.", "@prompts", ".", "reject", "{", "|", "p", "|", "p", ".", "prereqs", "}", ".", "each", "do", "|", "p", "|", "_deliver_prompt", "(", "p", ")", "end", "# After the \"non-prerequisite\" prompts are delivered,", "# deliver any that require prerequisites.", "@prompts", ".", "select", "{", "|", "p", "|", "p", ".", "prereqs", "}", ".", "each", "do", "|", "p", "|", "_deliver_prompt", "(", "p", ")", "if", "_prereqs_fulfilled?", "(", "p", ")", "end", "end" ]
Reads prompt data from and stores it. @param [<String, Hash, Array>] data Filepath to YAML, Hash, or Array @param [Configurator] configurator Source of defailt values @return [void] Runs through all of the prompt questions and collects answers from the user. Note that all questions w/o prerequisites are examined first; once those are complete, questions w/ prerequisites are examined. @return [void]
[ "Reads", "prompt", "data", "from", "and", "stores", "it", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/prefs.rb#L78-L90
5,633
bachya/cliutils
lib/cliutils/prefs.rb
CLIUtils.Prefs._prereqs_fulfilled?
def _prereqs_fulfilled?(p) ret = true p.prereqs.each do |req| a = @prompts.find do |answer| answer.config_key == req[:config_key] && answer.answer == req[:config_value] end ret = false if a.nil? end ret end
ruby
def _prereqs_fulfilled?(p) ret = true p.prereqs.each do |req| a = @prompts.find do |answer| answer.config_key == req[:config_key] && answer.answer == req[:config_value] end ret = false if a.nil? end ret end
[ "def", "_prereqs_fulfilled?", "(", "p", ")", "ret", "=", "true", "p", ".", "prereqs", ".", "each", "do", "|", "req", "|", "a", "=", "@prompts", ".", "find", "do", "|", "answer", "|", "answer", ".", "config_key", "==", "req", "[", ":config_key", "]", "&&", "answer", ".", "answer", "==", "req", "[", ":config_value", "]", "end", "ret", "=", "false", "if", "a", ".", "nil?", "end", "ret", "end" ]
Utility method for determining whether a prompt's prerequisites have already been fulfilled. @param [Hash] p The prompt @return [void]
[ "Utility", "method", "for", "determining", "whether", "a", "prompt", "s", "prerequisites", "have", "already", "been", "fulfilled", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/prefs.rb#L171-L181
5,634
ohler55/opee
lib/opee/askqueue.rb
Opee.AskQueue.ask_worker
def ask_worker(worker, job) raise NoMethodError.new("undefined method for #{job.class}. Expected a method invocation") unless job.is_a?(Actor::Act) worker.ask(job.op, *job.args) end
ruby
def ask_worker(worker, job) raise NoMethodError.new("undefined method for #{job.class}. Expected a method invocation") unless job.is_a?(Actor::Act) worker.ask(job.op, *job.args) end
[ "def", "ask_worker", "(", "worker", ",", "job", ")", "raise", "NoMethodError", ".", "new", "(", "\"undefined method for #{job.class}. Expected a method invocation\"", ")", "unless", "job", ".", "is_a?", "(", "Actor", "::", "Act", ")", "worker", ".", "ask", "(", "job", ".", "op", ",", "job", ".", "args", ")", "end" ]
Asks the worker to invoke the method of an Act Object.
[ "Asks", "the", "worker", "to", "invoke", "the", "method", "of", "an", "Act", "Object", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/askqueue.rb#L23-L26
5,635
ktemkin/ruby-ise
lib/ise/project.rb
ISE.Project.set_property
def set_property(name, value, mark_non_default=true) #Set the node's property, as specified. node = get_property_node(name) node.attribute("value").value = value #If the mark non-default option is set, mark the state is not a default value. node.attribute("valueState").value = 'non-default' if mark_non_default end
ruby
def set_property(name, value, mark_non_default=true) #Set the node's property, as specified. node = get_property_node(name) node.attribute("value").value = value #If the mark non-default option is set, mark the state is not a default value. node.attribute("valueState").value = 'non-default' if mark_non_default end
[ "def", "set_property", "(", "name", ",", "value", ",", "mark_non_default", "=", "true", ")", "#Set the node's property, as specified.", "node", "=", "get_property_node", "(", "name", ")", "node", ".", "attribute", "(", "\"value\"", ")", ".", "value", "=", "value", "#If the mark non-default option is set, mark the state is not a default value.", "node", ".", "attribute", "(", "\"valueState\"", ")", ".", "value", "=", "'non-default'", "if", "mark_non_default", "end" ]
Sets the value of an ISE project property.
[ "Sets", "the", "value", "of", "an", "ISE", "project", "property", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/project.rb#L33-L42
5,636
ktemkin/ruby-ise
lib/ise/project.rb
ISE.Project.minimize_runtime!
def minimize_runtime! #Compute the path in which temporary synthesis files should be created. shortname = CGI::escape(get_property(ShortNameProperty)) temp_path = Dir::mktmpdir([shortname, '']) #Synthesize from RAM. set_property(WorkingDirectoryProperty, temp_path) #Ask the project to focus on runtime over performance. set_property(GoalProperty, 'Minimum Runtime') end
ruby
def minimize_runtime! #Compute the path in which temporary synthesis files should be created. shortname = CGI::escape(get_property(ShortNameProperty)) temp_path = Dir::mktmpdir([shortname, '']) #Synthesize from RAM. set_property(WorkingDirectoryProperty, temp_path) #Ask the project to focus on runtime over performance. set_property(GoalProperty, 'Minimum Runtime') end
[ "def", "minimize_runtime!", "#Compute the path in which temporary synthesis files should be created.", "shortname", "=", "CGI", "::", "escape", "(", "get_property", "(", "ShortNameProperty", ")", ")", "temp_path", "=", "Dir", "::", "mktmpdir", "(", "[", "shortname", ",", "''", "]", ")", "#Synthesize from RAM.", "set_property", "(", "WorkingDirectoryProperty", ",", "temp_path", ")", "#Ask the project to focus on runtime over performance.", "set_property", "(", "GoalProperty", ",", "'Minimum Runtime'", ")", "end" ]
Attempts to minimize synthesis runtime of a _single run_. This will place all intermediary files in RAM- which means that synthesis results won't be preserved between reboots!
[ "Attempts", "to", "minimize", "synthesis", "runtime", "of", "a", "_single", "run_", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/project.rb#L50-L62
5,637
ktemkin/ruby-ise
lib/ise/project.rb
ISE.Project.top_level_file
def top_level_file(absolute_path=true) path = get_property(TopLevelFileProperty) #If the absolute_path flag is set, and we know how, expand the file path. if absolute_path path = File.expand_path(path, @base_path) end #Return the relevant path. path end
ruby
def top_level_file(absolute_path=true) path = get_property(TopLevelFileProperty) #If the absolute_path flag is set, and we know how, expand the file path. if absolute_path path = File.expand_path(path, @base_path) end #Return the relevant path. path end
[ "def", "top_level_file", "(", "absolute_path", "=", "true", ")", "path", "=", "get_property", "(", "TopLevelFileProperty", ")", "#If the absolute_path flag is set, and we know how, expand the file path.", "if", "absolute_path", "path", "=", "File", ".", "expand_path", "(", "path", ",", "@base_path", ")", "end", "#Return the relevant path.", "path", "end" ]
Returns a path to the top-level file in the given project. absoulute_path: If set when the project file's path is known, an absolute path will be returned.
[ "Returns", "a", "path", "to", "the", "top", "-", "level", "file", "in", "the", "given", "project", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/project.rb#L69-L81
5,638
ktemkin/ruby-ise
lib/ise/project.rb
ISE.Project.bit_file
def bit_file #Determine ISE's working directory. working_directory = get_property(WorkingDirectoryProperty) #Find an absolute path at which the most recently generated bit file should reside. name = get_property(OutputNameProperty) name = File.expand_path("#{working_directory}/#{name}.bit", @base_path) #If it exists, return it. File::exists?(name) ? name : nil end
ruby
def bit_file #Determine ISE's working directory. working_directory = get_property(WorkingDirectoryProperty) #Find an absolute path at which the most recently generated bit file should reside. name = get_property(OutputNameProperty) name = File.expand_path("#{working_directory}/#{name}.bit", @base_path) #If it exists, return it. File::exists?(name) ? name : nil end
[ "def", "bit_file", "#Determine ISE's working directory.", "working_directory", "=", "get_property", "(", "WorkingDirectoryProperty", ")", "#Find an absolute path at which the most recently generated bit file should reside.", "name", "=", "get_property", "(", "OutputNameProperty", ")", "name", "=", "File", ".", "expand_path", "(", "\"#{working_directory}/#{name}.bit\"", ",", "@base_path", ")", "#If it exists, return it.", "File", "::", "exists?", "(", "name", ")", "?", "name", ":", "nil", "end" ]
Returns the best-guess path to the most recently generated bit file, or nil if we weren't able to find one.
[ "Returns", "the", "best", "-", "guess", "path", "to", "the", "most", "recently", "generated", "bit", "file", "or", "nil", "if", "we", "weren", "t", "able", "to", "find", "one", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/project.rb#L94-L106
5,639
addagger/html_slicer
lib/html_slicer/installer.rb
HtmlSlicer.Installer.slice
def slice(*args, &block) attr_name = args.first raise(NameError, "Attribute name expected!") unless attr_name options = args.extract_options! config = HtmlSlicer.config(options.delete(:config)).duplicate # Configuration instance for each single one implementation if options.present? # Accepts options from args options.each do |key, value| config.send("#{key}=", value) end end if block_given? # Accepts options from block yield config end if config.processors Array.wrap(config.processors).each do |name| HtmlSlicer.load_processor!(name) end end method_name = config.as||"#{attr_name}_slice" config.cache_to = "#{method_name}_cache" if config.cache_to == true class_eval do define_method method_name do var_name = "@_#{method_name}" instance_variable_get(var_name)||instance_variable_set(var_name, HtmlSlicer::Interface.new(self, attr_name, config.config)) end end if config.cache_to && self.superclass == ActiveRecord::Base before_save do send(method_name).load! end end end
ruby
def slice(*args, &block) attr_name = args.first raise(NameError, "Attribute name expected!") unless attr_name options = args.extract_options! config = HtmlSlicer.config(options.delete(:config)).duplicate # Configuration instance for each single one implementation if options.present? # Accepts options from args options.each do |key, value| config.send("#{key}=", value) end end if block_given? # Accepts options from block yield config end if config.processors Array.wrap(config.processors).each do |name| HtmlSlicer.load_processor!(name) end end method_name = config.as||"#{attr_name}_slice" config.cache_to = "#{method_name}_cache" if config.cache_to == true class_eval do define_method method_name do var_name = "@_#{method_name}" instance_variable_get(var_name)||instance_variable_set(var_name, HtmlSlicer::Interface.new(self, attr_name, config.config)) end end if config.cache_to && self.superclass == ActiveRecord::Base before_save do send(method_name).load! end end end
[ "def", "slice", "(", "*", "args", ",", "&", "block", ")", "attr_name", "=", "args", ".", "first", "raise", "(", "NameError", ",", "\"Attribute name expected!\"", ")", "unless", "attr_name", "options", "=", "args", ".", "extract_options!", "config", "=", "HtmlSlicer", ".", "config", "(", "options", ".", "delete", "(", ":config", ")", ")", ".", "duplicate", "# Configuration instance for each single one implementation", "if", "options", ".", "present?", "# Accepts options from args", "options", ".", "each", "do", "|", "key", ",", "value", "|", "config", ".", "send", "(", "\"#{key}=\"", ",", "value", ")", "end", "end", "if", "block_given?", "# Accepts options from block", "yield", "config", "end", "if", "config", ".", "processors", "Array", ".", "wrap", "(", "config", ".", "processors", ")", ".", "each", "do", "|", "name", "|", "HtmlSlicer", ".", "load_processor!", "(", "name", ")", "end", "end", "method_name", "=", "config", ".", "as", "||", "\"#{attr_name}_slice\"", "config", ".", "cache_to", "=", "\"#{method_name}_cache\"", "if", "config", ".", "cache_to", "==", "true", "class_eval", "do", "define_method", "method_name", "do", "var_name", "=", "\"@_#{method_name}\"", "instance_variable_get", "(", "var_name", ")", "||", "instance_variable_set", "(", "var_name", ",", "HtmlSlicer", "::", "Interface", ".", "new", "(", "self", ",", "attr_name", ",", "config", ".", "config", ")", ")", "end", "end", "if", "config", ".", "cache_to", "&&", "self", ".", "superclass", "==", "ActiveRecord", "::", "Base", "before_save", "do", "send", "(", "method_name", ")", ".", "load!", "end", "end", "end" ]
The basic implementation method. slice <method_name>, <configuration>, [:config => <:style>]* where: * <method_name> - any method or local variable which returns source String (can be called with .send()). * <configuration> - Hash of configuration options and/or +:config+ parameter. === Example: class Article < ActiveRecord::Base slice :content, :as => :paged, :slice => {:maximum => 2000}, :resize => {:width => 600} end === Where: * <tt>:content</tt> is a method name or local variable, that return a target String object. * <tt>:as</tt> is a name of basic accessor for result. * <tt>:slice</tt> is a hash of +slicing options+. * <tt>:resize</tt> is a hash of +resizing options+. You can define any configuration key you want. Otherwise, default configuration options (if available) will be picked up automatically. === All configuration keys: * <tt>:as</tt> is a name of basic accessor for sliced +object+. * <tt>:slice</tt> is a hash of slicing options*. * <tt>:resize</tt> is a hash of resizing options*. * <tt>:processors</tt> - processors names*. * <tt>:window</tt> - parameter for ActionView: The "inner window" size (4 by default). * <tt>:outer_window</tt> - parameter for ActionView: The "outer window" size (0 by default). * <tt>:left</tt> - parameter for ActionView: The "left outer window" size (0 by default). * <tt>:right</tt> - parameter for ActionView: The "right outer window" size (0 by default). * <tt>:params</tt> - parameter for ActionView: url_for parameters for the links (:controller, :action, etc.) * <tt>:param_name</tt> - parameter for ActionView: parameter name for slice number in the links. Accepts +symbol+, +string+, +array+. * <tt>:remote</tt> - parameter for ActionView: Ajax? (false by default) === Block-style configuration example: slice *args do |config| config.as = :paged config.slice.merge! {:maximum => 1500} config.resize = nil end # *args = method name or local variable, and/or +:config+ parameter. === Premature configuration (+:config+ parameter): Stylizied general configuration can be used for many implementations, such as: # For example, we set the global stylized config: HtmlSlicer.configure(:paged_config) do |config| config.as = :page config.slice = {:maximum => 300} config.window = 4 config.outer_window = 0 config.left = 0 config.right = 0 config.param_name = :slice end # Now we can use it as next: slice *args, :config => :paged_config You can also pass another configuration options directrly as arguments and/or the block to clarify the config along with used global: slice *args, :as => :chapter, :config => :paged_config do |config| config.slice.merge! {:unit => {:tag => 'h1', :class => 'chapter'}, :maximum => 1} end === Skipping slicing: To skip slicing (for example, if you want to use only resizing feature) you can nilify +slice+ option at all: slice :content, :slice => nil, :resize => {:width => 300} Notice: without +:slice+ neither +:resize+ options, using HtmlSlicer becomes meaningless. :) === See README.rdoc for details about +:slice+ and +:resize+ options etc.
[ "The", "basic", "implementation", "method", "." ]
bbe6ab55a0d0335621079c304af534959b518d8b
https://github.com/addagger/html_slicer/blob/bbe6ab55a0d0335621079c304af534959b518d8b/lib/html_slicer/installer.rb#L88-L120
5,640
mpakus/uniqable
lib/uniqable.rb
Uniqable.ClassMethods.uniqable
def uniqable(*fields, to_param: nil) fields = [:uid] if fields.blank? fields.each do |name| before_create { |record| record.uniqable_uid(name) } end define_singleton_method :uniqable_fields do fields end return if to_param.blank? # :to_param option define_method :to_param do public_send(to_param) end end
ruby
def uniqable(*fields, to_param: nil) fields = [:uid] if fields.blank? fields.each do |name| before_create { |record| record.uniqable_uid(name) } end define_singleton_method :uniqable_fields do fields end return if to_param.blank? # :to_param option define_method :to_param do public_send(to_param) end end
[ "def", "uniqable", "(", "*", "fields", ",", "to_param", ":", "nil", ")", "fields", "=", "[", ":uid", "]", "if", "fields", ".", "blank?", "fields", ".", "each", "do", "|", "name", "|", "before_create", "{", "|", "record", "|", "record", ".", "uniqable_uid", "(", "name", ")", "}", "end", "define_singleton_method", ":uniqable_fields", "do", "fields", "end", "return", "if", "to_param", ".", "blank?", "# :to_param option", "define_method", ":to_param", "do", "public_send", "(", "to_param", ")", "end", "end" ]
Uniqable fields and options declaration @example: uniqable :uid, :slug, to_param: :uid rubocop:disable Metrics/MethodLength
[ "Uniqable", "fields", "and", "options", "declaration" ]
8a4828c73ba967b6cd046580e2358ea169ea122f
https://github.com/mpakus/uniqable/blob/8a4828c73ba967b6cd046580e2358ea169ea122f/lib/uniqable.rb#L17-L30
5,641
CultureHQ/paperweight
lib/paperweight/download.rb
Paperweight.Download.normalize_download
def normalize_download(file) return file unless file.is_a?(StringIO) # We need to open it in binary mode for Windows users. Tempfile.new('download-', binmode: true).tap do |tempfile| # IO.copy_stream is the most efficient way of data transfer. IO.copy_stream(file, tempfile.path) # We add the metadata that open-uri puts on the file # (e.g. #content_type) OpenURI::Meta.init(tempfile) end end
ruby
def normalize_download(file) return file unless file.is_a?(StringIO) # We need to open it in binary mode for Windows users. Tempfile.new('download-', binmode: true).tap do |tempfile| # IO.copy_stream is the most efficient way of data transfer. IO.copy_stream(file, tempfile.path) # We add the metadata that open-uri puts on the file # (e.g. #content_type) OpenURI::Meta.init(tempfile) end end
[ "def", "normalize_download", "(", "file", ")", "return", "file", "unless", "file", ".", "is_a?", "(", "StringIO", ")", "# We need to open it in binary mode for Windows users.", "Tempfile", ".", "new", "(", "'download-'", ",", "binmode", ":", "true", ")", ".", "tap", "do", "|", "tempfile", "|", "# IO.copy_stream is the most efficient way of data transfer.", "IO", ".", "copy_stream", "(", "file", ",", "tempfile", ".", "path", ")", "# We add the metadata that open-uri puts on the file", "# (e.g. #content_type)", "OpenURI", "::", "Meta", ".", "init", "(", "tempfile", ")", "end", "end" ]
open-uri will return a StringIO instead of a Tempfile if the filesize is less than 10 KB, so we patch this behaviour by converting it into a Tempfile.
[ "open", "-", "uri", "will", "return", "a", "StringIO", "instead", "of", "a", "Tempfile", "if", "the", "filesize", "is", "less", "than", "10", "KB", "so", "we", "patch", "this", "behaviour", "by", "converting", "it", "into", "a", "Tempfile", "." ]
dfd91e1a6708b56f01de46f793fba5fca17d7e45
https://github.com/CultureHQ/paperweight/blob/dfd91e1a6708b56f01de46f793fba5fca17d7e45/lib/paperweight/download.rb#L43-L55
5,642
eprothro/cassie
lib/cassie/schema/structure_dumper.rb
Cassie::Schema.StructureDumper.keyspace_structure
def keyspace_structure @keyspace_structure ||= begin args = ["-e", "'DESCRIBE KEYSPACE #{Cassie.configuration[:keyspace]}'"] runner = Cassie::Support::SystemCommand.new("cqlsh", args) runner.succeed runner.output end end
ruby
def keyspace_structure @keyspace_structure ||= begin args = ["-e", "'DESCRIBE KEYSPACE #{Cassie.configuration[:keyspace]}'"] runner = Cassie::Support::SystemCommand.new("cqlsh", args) runner.succeed runner.output end end
[ "def", "keyspace_structure", "@keyspace_structure", "||=", "begin", "args", "=", "[", "\"-e\"", ",", "\"'DESCRIBE KEYSPACE #{Cassie.configuration[:keyspace]}'\"", "]", "runner", "=", "Cassie", "::", "Support", "::", "SystemCommand", ".", "new", "(", "\"cqlsh\"", ",", "args", ")", "runner", ".", "succeed", "runner", ".", "output", "end", "end" ]
Fetch the CQL that can be used to recreate the current environment's keyspace @return [String] CQL commands @raise [RuntimeError] if the {Cassie.configuration[:keyspace]} keyspace could not be described.
[ "Fetch", "the", "CQL", "that", "can", "be", "used", "to", "recreate", "the", "current", "environment", "s", "keyspace" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/structure_dumper.rb#L22-L30
5,643
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.remarks
def remarks(keyword=nil) if keyword.nil? @remarks else ukw = keyword.upcase @remarks.find_all {|r| r[:keyword] == (ukw)} end end
ruby
def remarks(keyword=nil) if keyword.nil? @remarks else ukw = keyword.upcase @remarks.find_all {|r| r[:keyword] == (ukw)} end end
[ "def", "remarks", "(", "keyword", "=", "nil", ")", "if", "keyword", ".", "nil?", "@remarks", "else", "ukw", "=", "keyword", ".", "upcase", "@remarks", ".", "find_all", "{", "|", "r", "|", "r", "[", ":keyword", "]", "==", "(", "ukw", ")", "}", "end", "end" ]
Return the remark-elements found in the document. If _keyword_ is nil then return all remarks, else only the ones with the right keyword.
[ "Return", "the", "remark", "-", "elements", "found", "in", "the", "document", ".", "If", "_keyword_", "is", "nil", "then", "return", "all", "remarks", "else", "only", "the", "ones", "with", "the", "right", "keyword", "." ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L64-L71
5,644
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.find_section_title
def find_section_title(node) title = node.find_first('./db:title') if title.nil? title = node.find_first './db:info/db:title' end if title.nil? "" else title.content end end
ruby
def find_section_title(node) title = node.find_first('./db:title') if title.nil? title = node.find_first './db:info/db:title' end if title.nil? "" else title.content end end
[ "def", "find_section_title", "(", "node", ")", "title", "=", "node", ".", "find_first", "(", "'./db:title'", ")", "if", "title", ".", "nil?", "title", "=", "node", ".", "find_first", "'./db:info/db:title'", "end", "if", "title", ".", "nil?", "\"\"", "else", "title", ".", "content", "end", "end" ]
Find the _title_ of the current section. That element is either directly following or inside an _info_ element. Return the empty string if no title can be found.
[ "Find", "the", "_title_", "of", "the", "current", "section", ".", "That", "element", "is", "either", "directly", "following", "or", "inside", "an", "_info_", "element", ".", "Return", "the", "empty", "string", "if", "no", "title", "can", "be", "found", "." ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L98-L108
5,645
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.check_node
def check_node(node, level, ctr) if (@@text_elements.include? node.name) ctr << {:type => :para, :level => level, :words => count_content_words(node)} elsif (@@section_elements.include? node.name) title = find_section_title(node) ctr << {:type => :section, :level => level, :title => title, :name => node.name} node.children.each {|inner_elem| check_node(inner_elem, level+1, ctr)} if node.children? else node.children.each {|inner_elem| check_node(inner_elem, level+1, ctr)} if node.children? end ctr end
ruby
def check_node(node, level, ctr) if (@@text_elements.include? node.name) ctr << {:type => :para, :level => level, :words => count_content_words(node)} elsif (@@section_elements.include? node.name) title = find_section_title(node) ctr << {:type => :section, :level => level, :title => title, :name => node.name} node.children.each {|inner_elem| check_node(inner_elem, level+1, ctr)} if node.children? else node.children.each {|inner_elem| check_node(inner_elem, level+1, ctr)} if node.children? end ctr end
[ "def", "check_node", "(", "node", ",", "level", ",", "ctr", ")", "if", "(", "@@text_elements", ".", "include?", "node", ".", "name", ")", "ctr", "<<", "{", ":type", "=>", ":para", ",", ":level", "=>", "level", ",", ":words", "=>", "count_content_words", "(", "node", ")", "}", "elsif", "(", "@@section_elements", ".", "include?", "node", ".", "name", ")", "title", "=", "find_section_title", "(", "node", ")", "ctr", "<<", "{", ":type", "=>", ":section", ",", ":level", "=>", "level", ",", ":title", "=>", "title", ",", ":name", "=>", "node", ".", "name", "}", "node", ".", "children", ".", "each", "{", "|", "inner_elem", "|", "check_node", "(", "inner_elem", ",", "level", "+", "1", ",", "ctr", ")", "}", "if", "node", ".", "children?", "else", "node", ".", "children", ".", "each", "{", "|", "inner_elem", "|", "check_node", "(", "inner_elem", ",", "level", "+", "1", ",", "ctr", ")", "}", "if", "node", ".", "children?", "end", "ctr", "end" ]
Check the document elements for content and type recursively, starting at the current node. Returns an array with paragraph and section maps.
[ "Check", "the", "document", "elements", "for", "content", "and", "type", "recursively", "starting", "at", "the", "current", "node", ".", "Returns", "an", "array", "with", "paragraph", "and", "section", "maps", "." ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L114-L126
5,646
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.is_docbook?
def is_docbook?(doc) dbns = doc.root.namespaces.default (!dbns.nil? && (dbns.href.casecmp(DOCBOOK_NS) == 0)) end
ruby
def is_docbook?(doc) dbns = doc.root.namespaces.default (!dbns.nil? && (dbns.href.casecmp(DOCBOOK_NS) == 0)) end
[ "def", "is_docbook?", "(", "doc", ")", "dbns", "=", "doc", ".", "root", ".", "namespaces", ".", "default", "(", "!", "dbns", ".", "nil?", "&&", "(", "dbns", ".", "href", ".", "casecmp", "(", "DOCBOOK_NS", ")", "==", "0", ")", ")", "end" ]
Check whether the document has a DocBook default namespace
[ "Check", "whether", "the", "document", "has", "a", "DocBook", "default", "namespace" ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L129-L132
5,647
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.has_xinclude?
def has_xinclude?(doc) ret = false doc.root.namespaces.each do |ns| if (ns.href.casecmp(XINCLUDE_NS) == 0) ret = true break end end ret end
ruby
def has_xinclude?(doc) ret = false doc.root.namespaces.each do |ns| if (ns.href.casecmp(XINCLUDE_NS) == 0) ret = true break end end ret end
[ "def", "has_xinclude?", "(", "doc", ")", "ret", "=", "false", "doc", ".", "root", ".", "namespaces", ".", "each", "do", "|", "ns", "|", "if", "(", "ns", ".", "href", ".", "casecmp", "(", "XINCLUDE_NS", ")", "==", "0", ")", "ret", "=", "true", "break", "end", "end", "ret", "end" ]
Check whether the document has a XInclude namespace
[ "Check", "whether", "the", "document", "has", "a", "XInclude", "namespace" ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L135-L144
5,648
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.find_remarks
def find_remarks(filter=[]) if (@source.nil?) rfiles = find_xincludes(@doc) else @doc = XML::Document.file(@source) rfiles = [@source_file] + find_xincludes(@doc) end @remarks = rfiles.map {|rf| ind = XML::Document.file(File.expand_path(rf,@source.nil? ? '.' : @source_dir)) ind.root.namespaces.default_prefix = 'db' rems = find_remarks_in_doc(ind, rf) rems }.flatten if (filter.empty?) @remarks else filter.map {|f| @remarks.find_all {|r| f.casecmp(r[:keyword]) == 0} }.flatten end end
ruby
def find_remarks(filter=[]) if (@source.nil?) rfiles = find_xincludes(@doc) else @doc = XML::Document.file(@source) rfiles = [@source_file] + find_xincludes(@doc) end @remarks = rfiles.map {|rf| ind = XML::Document.file(File.expand_path(rf,@source.nil? ? '.' : @source_dir)) ind.root.namespaces.default_prefix = 'db' rems = find_remarks_in_doc(ind, rf) rems }.flatten if (filter.empty?) @remarks else filter.map {|f| @remarks.find_all {|r| f.casecmp(r[:keyword]) == 0} }.flatten end end
[ "def", "find_remarks", "(", "filter", "=", "[", "]", ")", "if", "(", "@source", ".", "nil?", ")", "rfiles", "=", "find_xincludes", "(", "@doc", ")", "else", "@doc", "=", "XML", "::", "Document", ".", "file", "(", "@source", ")", "rfiles", "=", "[", "@source_file", "]", "+", "find_xincludes", "(", "@doc", ")", "end", "@remarks", "=", "rfiles", ".", "map", "{", "|", "rf", "|", "ind", "=", "XML", "::", "Document", ".", "file", "(", "File", ".", "expand_path", "(", "rf", ",", "@source", ".", "nil?", "?", "'.'", ":", "@source_dir", ")", ")", "ind", ".", "root", ".", "namespaces", ".", "default_prefix", "=", "'db'", "rems", "=", "find_remarks_in_doc", "(", "ind", ",", "rf", ")", "rems", "}", ".", "flatten", "if", "(", "filter", ".", "empty?", ")", "@remarks", "else", "filter", ".", "map", "{", "|", "f", "|", "@remarks", ".", "find_all", "{", "|", "r", "|", "f", ".", "casecmp", "(", "r", "[", ":keyword", "]", ")", "==", "0", "}", "}", ".", "flatten", "end", "end" ]
Finds the remarks by looking through all the Xincluded files The remarks returned can be filtered by keyword if an keyword array is passed as an argument.
[ "Finds", "the", "remarks", "by", "looking", "through", "all", "the", "Xincluded", "files" ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L199-L219
5,649
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.sum_lower_sections
def sum_lower_sections(secs,start,level) i=start sum = 0 while (i < secs.length && secs[i][:level] > level) sum += secs[i][:words] i += 1 end [sum,i] end
ruby
def sum_lower_sections(secs,start,level) i=start sum = 0 while (i < secs.length && secs[i][:level] > level) sum += secs[i][:words] i += 1 end [sum,i] end
[ "def", "sum_lower_sections", "(", "secs", ",", "start", ",", "level", ")", "i", "=", "start", "sum", "=", "0", "while", "(", "i", "<", "secs", ".", "length", "&&", "secs", "[", "i", "]", "[", ":level", "]", ">", "level", ")", "sum", "+=", "secs", "[", "i", "]", "[", ":words", "]", "i", "+=", "1", "end", "[", "sum", ",", "i", "]", "end" ]
Helper for sum_sections
[ "Helper", "for", "sum_sections" ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L222-L230
5,650
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.sum_sections
def sum_sections(secs, max_level) 0.upto(max_level) do |cur_level| i = 0 while i < secs.length if (secs[i][:level] == cur_level) (ctr,ni) = sum_lower_sections(secs, i+1,cur_level) secs[i][:swords] = ctr i = ni else i += 1 end end end secs end
ruby
def sum_sections(secs, max_level) 0.upto(max_level) do |cur_level| i = 0 while i < secs.length if (secs[i][:level] == cur_level) (ctr,ni) = sum_lower_sections(secs, i+1,cur_level) secs[i][:swords] = ctr i = ni else i += 1 end end end secs end
[ "def", "sum_sections", "(", "secs", ",", "max_level", ")", "0", ".", "upto", "(", "max_level", ")", "do", "|", "cur_level", "|", "i", "=", "0", "while", "i", "<", "secs", ".", "length", "if", "(", "secs", "[", "i", "]", "[", ":level", "]", "==", "cur_level", ")", "(", "ctr", ",", "ni", ")", "=", "sum_lower_sections", "(", "secs", ",", "i", "+", "1", ",", "cur_level", ")", "secs", "[", "i", "]", "[", ":swords", "]", "=", "ctr", "i", "=", "ni", "else", "i", "+=", "1", "end", "end", "end", "secs", "end" ]
Sum the word counts of lower sections
[ "Sum", "the", "word", "counts", "of", "lower", "sections" ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L233-L247
5,651
rvolz/docbook_status
lib/docbook_status/status.rb
DocbookStatus.Status.analyze_file
def analyze_file full_name = File.expand_path(@source) changed = File.mtime(@source) @doc = XML::Document.file(@source) raise ArgumentError, "Error: #{@source} is apparently not DocBook 5." unless is_docbook?(@doc) @doc.xinclude if has_xinclude?(@doc) sections = analyze_document(@doc) {:file => full_name, :modified => changed, :sections => sections} end
ruby
def analyze_file full_name = File.expand_path(@source) changed = File.mtime(@source) @doc = XML::Document.file(@source) raise ArgumentError, "Error: #{@source} is apparently not DocBook 5." unless is_docbook?(@doc) @doc.xinclude if has_xinclude?(@doc) sections = analyze_document(@doc) {:file => full_name, :modified => changed, :sections => sections} end
[ "def", "analyze_file", "full_name", "=", "File", ".", "expand_path", "(", "@source", ")", "changed", "=", "File", ".", "mtime", "(", "@source", ")", "@doc", "=", "XML", "::", "Document", ".", "file", "(", "@source", ")", "raise", "ArgumentError", ",", "\"Error: #{@source} is apparently not DocBook 5.\"", "unless", "is_docbook?", "(", "@doc", ")", "@doc", ".", "xinclude", "if", "has_xinclude?", "(", "@doc", ")", "sections", "=", "analyze_document", "(", "@doc", ")", "{", ":file", "=>", "full_name", ",", ":modified", "=>", "changed", ",", ":sections", "=>", "sections", "}", "end" ]
Open the XML document, check for the DocBook5 namespace and finally apply Xinclude tretement to it, if it has a XInclude namespace. Returns a map with the file name, the file's modification time, and the section structure.
[ "Open", "the", "XML", "document", "check", "for", "the", "DocBook5", "namespace", "and", "finally", "apply", "Xinclude", "tretement", "to", "it", "if", "it", "has", "a", "XInclude", "namespace", ".", "Returns", "a", "map", "with", "the", "file", "name", "the", "file", "s", "modification", "time", "and", "the", "section", "structure", "." ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/status.rb#L293-L301
5,652
suculent/apprepo
lib/apprepo/runner.rb
AppRepo.Runner.upload_binary
def upload_binary if options[:ipa] uploader = AppRepo::Uploader.new(options) result = uploader.upload msg = 'Binary upload failed. Check out the error above.' UI.user_error!(msg) unless result end end
ruby
def upload_binary if options[:ipa] uploader = AppRepo::Uploader.new(options) result = uploader.upload msg = 'Binary upload failed. Check out the error above.' UI.user_error!(msg) unless result end end
[ "def", "upload_binary", "if", "options", "[", ":ipa", "]", "uploader", "=", "AppRepo", "::", "Uploader", ".", "new", "(", "options", ")", "result", "=", "uploader", ".", "upload", "msg", "=", "'Binary upload failed. Check out the error above.'", "UI", ".", "user_error!", "(", "msg", ")", "unless", "result", "end", "end" ]
Upload the binary to AppRepo
[ "Upload", "the", "binary", "to", "AppRepo" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/runner.rb#L52-L59
5,653
dpep/rb_autographql
lib/autographql/type_builder.rb
AutoGraphQL.TypeBuilder.convert_type
def convert_type type return type if type.is_a? GraphQL::BaseType unless type.is_a? Symbol type = type.to_s.downcase.to_sym end { boolean: GraphQL::BOOLEAN_TYPE, date: GraphQL::Types::DATE, datetime: GraphQL::Types::ISO8601DateTime, decimal: GraphQL::Types::DECIMAL, float: GraphQL::FLOAT_TYPE, int: GraphQL::INT_TYPE, integer: GraphQL::INT_TYPE, json: GraphQL::Types::JSON, string: GraphQL::STRING_TYPE, text: GraphQL::STRING_TYPE, }[type] end
ruby
def convert_type type return type if type.is_a? GraphQL::BaseType unless type.is_a? Symbol type = type.to_s.downcase.to_sym end { boolean: GraphQL::BOOLEAN_TYPE, date: GraphQL::Types::DATE, datetime: GraphQL::Types::ISO8601DateTime, decimal: GraphQL::Types::DECIMAL, float: GraphQL::FLOAT_TYPE, int: GraphQL::INT_TYPE, integer: GraphQL::INT_TYPE, json: GraphQL::Types::JSON, string: GraphQL::STRING_TYPE, text: GraphQL::STRING_TYPE, }[type] end
[ "def", "convert_type", "type", "return", "type", "if", "type", ".", "is_a?", "GraphQL", "::", "BaseType", "unless", "type", ".", "is_a?", "Symbol", "type", "=", "type", ".", "to_s", ".", "downcase", ".", "to_sym", "end", "{", "boolean", ":", "GraphQL", "::", "BOOLEAN_TYPE", ",", "date", ":", "GraphQL", "::", "Types", "::", "DATE", ",", "datetime", ":", "GraphQL", "::", "Types", "::", "ISO8601DateTime", ",", "decimal", ":", "GraphQL", "::", "Types", "::", "DECIMAL", ",", "float", ":", "GraphQL", "::", "FLOAT_TYPE", ",", "int", ":", "GraphQL", "::", "INT_TYPE", ",", "integer", ":", "GraphQL", "::", "INT_TYPE", ",", "json", ":", "GraphQL", "::", "Types", "::", "JSON", ",", "string", ":", "GraphQL", "::", "STRING_TYPE", ",", "text", ":", "GraphQL", "::", "STRING_TYPE", ",", "}", "[", "type", "]", "end" ]
convert Active Record type to GraphQL type
[ "convert", "Active", "Record", "type", "to", "GraphQL", "type" ]
e38c8648fe4e497b92e2a31143745f3e7a6ed439
https://github.com/dpep/rb_autographql/blob/e38c8648fe4e497b92e2a31143745f3e7a6ed439/lib/autographql/type_builder.rb#L130-L149
5,654
robertwahler/repo_manager
lib/repo_manager/assets/repo_asset.rb
RepoManager.RepoAsset.scm
def scm return @scm if @scm raise NoSuchPathError unless File.exists?(path) raise InvalidRepositoryError unless File.exists?(File.join(path, '.git')) @scm = Git.open(path) end
ruby
def scm return @scm if @scm raise NoSuchPathError unless File.exists?(path) raise InvalidRepositoryError unless File.exists?(File.join(path, '.git')) @scm = Git.open(path) end
[ "def", "scm", "return", "@scm", "if", "@scm", "raise", "NoSuchPathError", "unless", "File", ".", "exists?", "(", "path", ")", "raise", "InvalidRepositoryError", "unless", "File", ".", "exists?", "(", "File", ".", "join", "(", "path", ",", "'.git'", ")", ")", "@scm", "=", "Git", ".", "open", "(", "path", ")", "end" ]
version control system wrapper
[ "version", "control", "system", "wrapper" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/assets/repo_asset.rb#L21-L26
5,655
eprothro/cassie
lib/cassie/schema/version.rb
Cassie::Schema.Version.next
def next(bump_type=nil) bump_type ||= :patch bump_index = PARTS.index(bump_type.to_sym) # 0.2.1 - > 0.2 bumped_parts = parts.take(bump_index + 1) # 0.2 - > 0.3 bumped_parts[bump_index] = bumped_parts[bump_index].to_i + 1 # 0.3 - > 0.3.0.0 bumped_parts += [0]*(PARTS.length - (bump_index + 1)) self.class.new(bumped_parts.join('.')) end
ruby
def next(bump_type=nil) bump_type ||= :patch bump_index = PARTS.index(bump_type.to_sym) # 0.2.1 - > 0.2 bumped_parts = parts.take(bump_index + 1) # 0.2 - > 0.3 bumped_parts[bump_index] = bumped_parts[bump_index].to_i + 1 # 0.3 - > 0.3.0.0 bumped_parts += [0]*(PARTS.length - (bump_index + 1)) self.class.new(bumped_parts.join('.')) end
[ "def", "next", "(", "bump_type", "=", "nil", ")", "bump_type", "||=", ":patch", "bump_index", "=", "PARTS", ".", "index", "(", "bump_type", ".", "to_sym", ")", "# 0.2.1 - > 0.2", "bumped_parts", "=", "parts", ".", "take", "(", "bump_index", "+", "1", ")", "# 0.2 - > 0.3", "bumped_parts", "[", "bump_index", "]", "=", "bumped_parts", "[", "bump_index", "]", ".", "to_i", "+", "1", "# 0.3 - > 0.3.0.0", "bumped_parts", "+=", "[", "0", "]", "*", "(", "PARTS", ".", "length", "-", "(", "bump_index", "+", "1", ")", ")", "self", ".", "class", ".", "new", "(", "bumped_parts", ".", "join", "(", "'.'", ")", ")", "end" ]
Builds a new version, wiht a version number incremented from this object's version. Does not propogate any other attributes @option bump_type [Symbol] :build Bump the build version @option bump_type [Symbol] :patch Bump the patch version, set build to 0 @option bump_type [Symbol] :minor Bump the minor version, set patch and build to 0 @option bump_type [Symbol] :major Bump the major version, set minor, patch, and build to 0 @option bump_type [nil] nil Default, bumps patch, sets build to 0 @return [Version]
[ "Builds", "a", "new", "version", "wiht", "a", "version", "number", "incremented", "from", "this", "object", "s", "version", ".", "Does", "not", "propogate", "any", "other", "attributes" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/version.rb#L67-L78
5,656
robertwahler/repo_manager
lib/repo_manager/git/lib.rb
Git.Lib.native
def native(cmd, opts = [], chdir = true, redirect = '', &block) validate ENV['GIT_DIR'] = @git_dir ENV['GIT_INDEX_FILE'] = @git_index_file ENV['GIT_WORK_TREE'] = @git_work_dir path = @git_work_dir || @git_dir || @path opts = [opts].flatten.map {|s| escape(s) }.join(' ') git_cmd = "git #{cmd} #{opts} #{redirect} 2>&1" out = nil if chdir && (Dir.getwd != path) Dir.chdir(path) { out = run_command(git_cmd, &block) } else out = run_command(git_cmd, &block) end if @logger @logger.info(git_cmd) @logger.debug(out) end if $?.exitstatus > 0 if $?.exitstatus == 1 && out == '' return '' end raise Git::CommandFailed.new(git_cmd, $?.exitstatus, out.to_s) end out end
ruby
def native(cmd, opts = [], chdir = true, redirect = '', &block) validate ENV['GIT_DIR'] = @git_dir ENV['GIT_INDEX_FILE'] = @git_index_file ENV['GIT_WORK_TREE'] = @git_work_dir path = @git_work_dir || @git_dir || @path opts = [opts].flatten.map {|s| escape(s) }.join(' ') git_cmd = "git #{cmd} #{opts} #{redirect} 2>&1" out = nil if chdir && (Dir.getwd != path) Dir.chdir(path) { out = run_command(git_cmd, &block) } else out = run_command(git_cmd, &block) end if @logger @logger.info(git_cmd) @logger.debug(out) end if $?.exitstatus > 0 if $?.exitstatus == 1 && out == '' return '' end raise Git::CommandFailed.new(git_cmd, $?.exitstatus, out.to_s) end out end
[ "def", "native", "(", "cmd", ",", "opts", "=", "[", "]", ",", "chdir", "=", "true", ",", "redirect", "=", "''", ",", "&", "block", ")", "validate", "ENV", "[", "'GIT_DIR'", "]", "=", "@git_dir", "ENV", "[", "'GIT_INDEX_FILE'", "]", "=", "@git_index_file", "ENV", "[", "'GIT_WORK_TREE'", "]", "=", "@git_work_dir", "path", "=", "@git_work_dir", "||", "@git_dir", "||", "@path", "opts", "=", "[", "opts", "]", ".", "flatten", ".", "map", "{", "|", "s", "|", "escape", "(", "s", ")", "}", ".", "join", "(", "' '", ")", "git_cmd", "=", "\"git #{cmd} #{opts} #{redirect} 2>&1\"", "out", "=", "nil", "if", "chdir", "&&", "(", "Dir", ".", "getwd", "!=", "path", ")", "Dir", ".", "chdir", "(", "path", ")", "{", "out", "=", "run_command", "(", "git_cmd", ",", "block", ")", "}", "else", "out", "=", "run_command", "(", "git_cmd", ",", "block", ")", "end", "if", "@logger", "@logger", ".", "info", "(", "git_cmd", ")", "@logger", ".", "debug", "(", "out", ")", "end", "if", "$?", ".", "exitstatus", ">", "0", "if", "$?", ".", "exitstatus", "==", "1", "&&", "out", "==", "''", "return", "''", "end", "raise", "Git", "::", "CommandFailed", ".", "new", "(", "git_cmd", ",", "$?", ".", "exitstatus", ",", "out", ".", "to_s", ")", "end", "out", "end" ]
liberate the ruby-git's private command method with a few tweaks
[ "liberate", "the", "ruby", "-", "git", "s", "private", "command", "method", "with", "a", "few", "tweaks" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/git/lib.rb#L35-L65
5,657
thelazycamel/rubychain
lib/rubychain/chain.rb
Rubychain.Chain.add_next_block
def add_next_block(prev_block, data) if valid_block?(prev_block) blockchain << next_block(data) else raise InvalidBlockError end end
ruby
def add_next_block(prev_block, data) if valid_block?(prev_block) blockchain << next_block(data) else raise InvalidBlockError end end
[ "def", "add_next_block", "(", "prev_block", ",", "data", ")", "if", "valid_block?", "(", "prev_block", ")", "blockchain", "<<", "next_block", "(", "data", ")", "else", "raise", "InvalidBlockError", "end", "end" ]
Initialize a new blockchain by creating a new array with the Genesis block #add_next_block => Adds a new block to the blockchain with the given data it will raise an error if the previous_block hash does not match the last_block in our blockchain
[ "Initialize", "a", "new", "blockchain", "by", "creating", "a", "new", "array", "with", "the", "Genesis", "block" ]
7671fe6d25f818a88c8a62c3167438837d37740d
https://github.com/thelazycamel/rubychain/blob/7671fe6d25f818a88c8a62c3167438837d37740d/lib/rubychain/chain.rb#L19-L25
5,658
cyberarm/rewrite-gameoverseer
lib/gameoverseer/services/service.rb
GameOverseer.Service.data_to_method
def data_to_method(data) raise "No safe methods defined!" unless @safe_methods.size > 0 @safe_methods.each do |method| if data['mode'] == method.to_s self.send(data['mode'], data) end end end
ruby
def data_to_method(data) raise "No safe methods defined!" unless @safe_methods.size > 0 @safe_methods.each do |method| if data['mode'] == method.to_s self.send(data['mode'], data) end end end
[ "def", "data_to_method", "(", "data", ")", "raise", "\"No safe methods defined!\"", "unless", "@safe_methods", ".", "size", ">", "0", "@safe_methods", ".", "each", "do", "|", "method", "|", "if", "data", "[", "'mode'", "]", "==", "method", ".", "to_s", "self", ".", "send", "(", "data", "[", "'mode'", "]", ",", "data", ")", "end", "end", "end" ]
Uses the 'mode' from a packet to call the method of the same name @param data [Hash] data from packet
[ "Uses", "the", "mode", "from", "a", "packet", "to", "call", "the", "method", "of", "the", "same", "name" ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/services/service.rb#L74-L81
5,659
cyberarm/rewrite-gameoverseer
lib/gameoverseer/services/service.rb
GameOverseer.Service.every
def every(milliseconds, &block) Thread.new do loop do block.call sleep(milliseconds/1000.0) end end end
ruby
def every(milliseconds, &block) Thread.new do loop do block.call sleep(milliseconds/1000.0) end end end
[ "def", "every", "(", "milliseconds", ",", "&", "block", ")", "Thread", ".", "new", "do", "loop", "do", "block", ".", "call", "sleep", "(", "milliseconds", "/", "1000.0", ")", "end", "end", "end" ]
Calls Proc immediately then every milliseconds, async. @param milliseconds [Integer][Float] Time to wait before calling the block @param block [Proc]
[ "Calls", "Proc", "immediately", "then", "every", "milliseconds", "async", "." ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/services/service.rb#L86-L93
5,660
cyberarm/rewrite-gameoverseer
lib/gameoverseer/services/service.rb
GameOverseer.Service.log
def log(string, color = Gosu::Color::RED) GameOverseer::Console.log_with_color(string, color) end
ruby
def log(string, color = Gosu::Color::RED) GameOverseer::Console.log_with_color(string, color) end
[ "def", "log", "(", "string", ",", "color", "=", "Gosu", "::", "Color", "::", "RED", ")", "GameOverseer", "::", "Console", ".", "log_with_color", "(", "string", ",", "color", ")", "end" ]
String to be logged @param string [String] text to log @param color [Gosu::Color] color of text in console
[ "String", "to", "be", "logged" ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/services/service.rb#L108-L110
5,661
xlab-si/server-sent-events-ruby
lib/server_sent_events/event.rb
ServerSentEvents.Event.to_s
def to_s repr = "" repr += "id: #{id}\n" if id repr += "event: #{event}\n" if event if data.empty? repr += "data: \n" else data.split("\n").each { |l| repr += "data: #{l}\n" } end repr += "\n" end
ruby
def to_s repr = "" repr += "id: #{id}\n" if id repr += "event: #{event}\n" if event if data.empty? repr += "data: \n" else data.split("\n").each { |l| repr += "data: #{l}\n" } end repr += "\n" end
[ "def", "to_s", "repr", "=", "\"\"", "repr", "+=", "\"id: #{id}\\n\"", "if", "id", "repr", "+=", "\"event: #{event}\\n\"", "if", "event", "if", "data", ".", "empty?", "repr", "+=", "\"data: \\n\"", "else", "data", ".", "split", "(", "\"\\n\"", ")", ".", "each", "{", "|", "l", "|", "repr", "+=", "\"data: #{l}\\n\"", "}", "end", "repr", "+=", "\"\\n\"", "end" ]
Serialize event into form for transmission. Output of this method call can be written directly into the socket.
[ "Serialize", "event", "into", "form", "for", "transmission", "." ]
f57491a8ab3b08662f657668d3ffe6725dd251db
https://github.com/xlab-si/server-sent-events-ruby/blob/f57491a8ab3b08662f657668d3ffe6725dd251db/lib/server_sent_events/event.rb#L36-L46
5,662
pwnall/exec_sandbox
lib/exec_sandbox/sandbox.rb
ExecSandbox.Sandbox.push
def push(from, options = {}) to = File.join @path, (options[:to] || File.basename(from)) FileUtils.cp_r from, to permissions = options[:read_only] ? 0770 : 0750 FileUtils.chmod_R permissions, to FileUtils.chown_R @admin_uid, @user_gid, to # NOTE: making a file / directory read-only is useless -- the sandboxed # process can replace the file with another copy of the file; this can # be worked around by noting the inode number of the protected file / # dir, and making a hard link to it somewhere else so the inode won't # be reused. to end
ruby
def push(from, options = {}) to = File.join @path, (options[:to] || File.basename(from)) FileUtils.cp_r from, to permissions = options[:read_only] ? 0770 : 0750 FileUtils.chmod_R permissions, to FileUtils.chown_R @admin_uid, @user_gid, to # NOTE: making a file / directory read-only is useless -- the sandboxed # process can replace the file with another copy of the file; this can # be worked around by noting the inode number of the protected file / # dir, and making a hard link to it somewhere else so the inode won't # be reused. to end
[ "def", "push", "(", "from", ",", "options", "=", "{", "}", ")", "to", "=", "File", ".", "join", "@path", ",", "(", "options", "[", ":to", "]", "||", "File", ".", "basename", "(", "from", ")", ")", "FileUtils", ".", "cp_r", "from", ",", "to", "permissions", "=", "options", "[", ":read_only", "]", "?", "0770", ":", "0750", "FileUtils", ".", "chmod_R", "permissions", ",", "to", "FileUtils", ".", "chown_R", "@admin_uid", ",", "@user_gid", ",", "to", "# NOTE: making a file / directory read-only is useless -- the sandboxed", "# process can replace the file with another copy of the file; this can", "# be worked around by noting the inode number of the protected file /", "# dir, and making a hard link to it somewhere else so the inode won't", "# be reused.", "to", "end" ]
Empty sandbox. @param [String] admin the name of a user who will be able to peek into the sandbox Copies a file or directory to the sandbox. @param [String] from path to the file or directory to be copied @param [Hash] options tweaks the permissions and the path inside the sandbox @option options [String] :to the path inside the sandbox where the file or directory will be copied (defaults to the name of the source) @option options [Boolean] :read_only if true, the sandbox user will not be able to write to the file / directory @return [String] the absolute path to the copied file / directory inside the sandbox
[ "Empty", "sandbox", "." ]
2e6a80643978d4c2c6d62193463a7ab7d45db723
https://github.com/pwnall/exec_sandbox/blob/2e6a80643978d4c2c6d62193463a7ab7d45db723/lib/exec_sandbox/sandbox.rb#L42-L56
5,663
pwnall/exec_sandbox
lib/exec_sandbox/sandbox.rb
ExecSandbox.Sandbox.pull
def pull(from, to) from = File.join @path, from return nil unless File.exist? from FileUtils.cp_r from, to FileUtils.chmod_R 0770, to FileUtils.chown_R @admin_uid, @admin_gid, to # NOTE: making a file / directory read-only is useless -- the sandboxed # process can replace the file with another copy of the file; this can # be worked around by noting the inode number of the protected file / # dir, and making a hard link to it somewhere else so the inode won't # be reused. to end
ruby
def pull(from, to) from = File.join @path, from return nil unless File.exist? from FileUtils.cp_r from, to FileUtils.chmod_R 0770, to FileUtils.chown_R @admin_uid, @admin_gid, to # NOTE: making a file / directory read-only is useless -- the sandboxed # process can replace the file with another copy of the file; this can # be worked around by noting the inode number of the protected file / # dir, and making a hard link to it somewhere else so the inode won't # be reused. to end
[ "def", "pull", "(", "from", ",", "to", ")", "from", "=", "File", ".", "join", "@path", ",", "from", "return", "nil", "unless", "File", ".", "exist?", "from", "FileUtils", ".", "cp_r", "from", ",", "to", "FileUtils", ".", "chmod_R", "0770", ",", "to", "FileUtils", ".", "chown_R", "@admin_uid", ",", "@admin_gid", ",", "to", "# NOTE: making a file / directory read-only is useless -- the sandboxed", "# process can replace the file with another copy of the file; this can", "# be worked around by noting the inode number of the protected file /", "# dir, and making a hard link to it somewhere else so the inode won't", "# be reused.", "to", "end" ]
Copies a file or directory from the sandbox. @param [String] from relative path to the sandbox file or directory @param [String] to path where the file/directory will be copied @param [Hash] options tweaks the permissions and the path inside the sandbox @return [String] the path to the copied file / directory outside the sandbox, or nil if the file / directory does not exist inside the sandbox
[ "Copies", "a", "file", "or", "directory", "from", "the", "sandbox", "." ]
2e6a80643978d4c2c6d62193463a7ab7d45db723
https://github.com/pwnall/exec_sandbox/blob/2e6a80643978d4c2c6d62193463a7ab7d45db723/lib/exec_sandbox/sandbox.rb#L66-L80
5,664
pwnall/exec_sandbox
lib/exec_sandbox/sandbox.rb
ExecSandbox.Sandbox.run
def run(command, options = {}) limits = options[:limits] || {} io = {} if options[:in] io[:in] = options[:in] in_rd = nil else in_rd, in_wr = IO.pipe in_wr.write options[:in_data] if options[:in_data] in_wr.close io[:in] = in_rd end if options[:out] io[:out] = options[:out] else out_rd, out_wr = IO.pipe io[:out] = out_wr end case options[:err] when :out io[:err] = STDOUT when :none # Don't set io[:err], so the child's stderr will be closed. else io[:err] = STDERR end pid = ExecSandbox::Spawn.spawn command, io, @principal, limits # Close the pipe ends that are meant to be used in the child. in_rd.close if in_rd out_wr.close if out_wr # Collect information about the child. if out_rd out_pieces = [] out_pieces << out_rd.read rescue nil end status = ExecSandbox::Wait4.wait4 pid if out_rd out_pieces << out_rd.read rescue nil out_rd.close status[:out_data] = out_pieces.join('') end status end
ruby
def run(command, options = {}) limits = options[:limits] || {} io = {} if options[:in] io[:in] = options[:in] in_rd = nil else in_rd, in_wr = IO.pipe in_wr.write options[:in_data] if options[:in_data] in_wr.close io[:in] = in_rd end if options[:out] io[:out] = options[:out] else out_rd, out_wr = IO.pipe io[:out] = out_wr end case options[:err] when :out io[:err] = STDOUT when :none # Don't set io[:err], so the child's stderr will be closed. else io[:err] = STDERR end pid = ExecSandbox::Spawn.spawn command, io, @principal, limits # Close the pipe ends that are meant to be used in the child. in_rd.close if in_rd out_wr.close if out_wr # Collect information about the child. if out_rd out_pieces = [] out_pieces << out_rd.read rescue nil end status = ExecSandbox::Wait4.wait4 pid if out_rd out_pieces << out_rd.read rescue nil out_rd.close status[:out_data] = out_pieces.join('') end status end
[ "def", "run", "(", "command", ",", "options", "=", "{", "}", ")", "limits", "=", "options", "[", ":limits", "]", "||", "{", "}", "io", "=", "{", "}", "if", "options", "[", ":in", "]", "io", "[", ":in", "]", "=", "options", "[", ":in", "]", "in_rd", "=", "nil", "else", "in_rd", ",", "in_wr", "=", "IO", ".", "pipe", "in_wr", ".", "write", "options", "[", ":in_data", "]", "if", "options", "[", ":in_data", "]", "in_wr", ".", "close", "io", "[", ":in", "]", "=", "in_rd", "end", "if", "options", "[", ":out", "]", "io", "[", ":out", "]", "=", "options", "[", ":out", "]", "else", "out_rd", ",", "out_wr", "=", "IO", ".", "pipe", "io", "[", ":out", "]", "=", "out_wr", "end", "case", "options", "[", ":err", "]", "when", ":out", "io", "[", ":err", "]", "=", "STDOUT", "when", ":none", "# Don't set io[:err], so the child's stderr will be closed.", "else", "io", "[", ":err", "]", "=", "STDERR", "end", "pid", "=", "ExecSandbox", "::", "Spawn", ".", "spawn", "command", ",", "io", ",", "@principal", ",", "limits", "# Close the pipe ends that are meant to be used in the child.", "in_rd", ".", "close", "if", "in_rd", "out_wr", ".", "close", "if", "out_wr", "# Collect information about the child.", "if", "out_rd", "out_pieces", "=", "[", "]", "out_pieces", "<<", "out_rd", ".", "read", "rescue", "nil", "end", "status", "=", "ExecSandbox", "::", "Wait4", ".", "wait4", "pid", "if", "out_rd", "out_pieces", "<<", "out_rd", ".", "read", "rescue", "nil", "out_rd", ".", "close", "status", "[", ":out_data", "]", "=", "out_pieces", ".", "join", "(", "''", ")", "end", "status", "end" ]
Runs a command in the sandbox. @param [Array, String] command to be run; use an array to pass arguments to the command @param [Hash] options stdin / stdout redirection and resource limitations @option options [Hash] :limits see {Spawn.limit_resources} @option options [String] :in path to a file that is set as the child's stdin @option options [String] :in_data contents to be written to a pipe that is set as the child's stdin; if neither :in nor :in_data are specified, the child will receive the read end of an empty pipe @option options [String] :out path to a file that is set as the child's stdout; if not set, the child will receive the write end of a pipe whose contents is returned in :out_data @option options [Symbol] :err :none closes the child's stderr, :out redirects the child's stderr to stdout; by default, the child's stderr is the same as the parent's @return [Hash] the result of {Wait4.wait4}, plus an :out_data key if no :out option is given
[ "Runs", "a", "command", "in", "the", "sandbox", "." ]
2e6a80643978d4c2c6d62193463a7ab7d45db723
https://github.com/pwnall/exec_sandbox/blob/2e6a80643978d4c2c6d62193463a7ab7d45db723/lib/exec_sandbox/sandbox.rb#L100-L145
5,665
atd/rails-scheduler
lib/scheduler/model.rb
Scheduler.Model.ocurrences
def ocurrences(st, en = nil) recurrence ? recurrence.events(:starts => st, :until => en) : (start_at.to_date..end_at.to_date).to_a end
ruby
def ocurrences(st, en = nil) recurrence ? recurrence.events(:starts => st, :until => en) : (start_at.to_date..end_at.to_date).to_a end
[ "def", "ocurrences", "(", "st", ",", "en", "=", "nil", ")", "recurrence", "?", "recurrence", ".", "events", "(", ":starts", "=>", "st", ",", ":until", "=>", "en", ")", ":", "(", "start_at", ".", "to_date", "..", "end_at", ".", "to_date", ")", ".", "to_a", "end" ]
Array including all the dates this Scheduler has ocurrences between st and en
[ "Array", "including", "all", "the", "dates", "this", "Scheduler", "has", "ocurrences", "between", "st", "and", "en" ]
849e0a660f32646e768ab9f49296559184fcb9e4
https://github.com/atd/rails-scheduler/blob/849e0a660f32646e768ab9f49296559184fcb9e4/lib/scheduler/model.rb#L105-L109
5,666
rakeoe/rakeoe
lib/rakeoe/config.rb
RakeOE.Config.dump
def dump puts '******************' puts '* RakeOE::Config *' puts '******************' puts "Directories : #{@directories}" puts "Suffixes : #{@suffixes}" puts "Platform : #{@platform}" puts "Release mode : #{@release}" puts "Test framework : #{@test_fw}" puts "Optimization dbg : #{@optimization_dbg}" puts "Optimization release : #{@optimization_release}" puts "Language Standard for C : #{@language_std_c}" puts "Language Standard for C++ : #{@language_std_cpp}" puts "Software version string : #{@sw_version}" puts "Generate bin file : #{@generate_bin}" puts "Generate hex file : #{@generate_hex}" puts "Generate map file : #{@generate_map}" puts "Strip objects : #{@stripped}" end
ruby
def dump puts '******************' puts '* RakeOE::Config *' puts '******************' puts "Directories : #{@directories}" puts "Suffixes : #{@suffixes}" puts "Platform : #{@platform}" puts "Release mode : #{@release}" puts "Test framework : #{@test_fw}" puts "Optimization dbg : #{@optimization_dbg}" puts "Optimization release : #{@optimization_release}" puts "Language Standard for C : #{@language_std_c}" puts "Language Standard for C++ : #{@language_std_cpp}" puts "Software version string : #{@sw_version}" puts "Generate bin file : #{@generate_bin}" puts "Generate hex file : #{@generate_hex}" puts "Generate map file : #{@generate_map}" puts "Strip objects : #{@stripped}" end
[ "def", "dump", "puts", "'******************'", "puts", "'* RakeOE::Config *'", "puts", "'******************'", "puts", "\"Directories : #{@directories}\"", "puts", "\"Suffixes : #{@suffixes}\"", "puts", "\"Platform : #{@platform}\"", "puts", "\"Release mode : #{@release}\"", "puts", "\"Test framework : #{@test_fw}\"", "puts", "\"Optimization dbg : #{@optimization_dbg}\"", "puts", "\"Optimization release : #{@optimization_release}\"", "puts", "\"Language Standard for C : #{@language_std_c}\"", "puts", "\"Language Standard for C++ : #{@language_std_cpp}\"", "puts", "\"Software version string : #{@sw_version}\"", "puts", "\"Generate bin file : #{@generate_bin}\"", "puts", "\"Generate hex file : #{@generate_hex}\"", "puts", "\"Generate map file : #{@generate_map}\"", "puts", "\"Strip objects : #{@stripped}\"", "end" ]
Dumps configuration to stdout
[ "Dumps", "configuration", "to", "stdout" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/config.rb#L109-L127
5,667
wwidea/minimalist_authentication
lib/minimalist_authentication/user.rb
MinimalistAuthentication.User.authenticated?
def authenticated?(password) if password_object == password update_hash!(password) if password_object.stale? return true end return false end
ruby
def authenticated?(password) if password_object == password update_hash!(password) if password_object.stale? return true end return false end
[ "def", "authenticated?", "(", "password", ")", "if", "password_object", "==", "password", "update_hash!", "(", "password", ")", "if", "password_object", ".", "stale?", "return", "true", "end", "return", "false", "end" ]
Return true if password matches the hashed_password. If successful checks for an outdated password_hash and updates if necessary.
[ "Return", "true", "if", "password", "matches", "the", "hashed_password", ".", "If", "successful", "checks", "for", "an", "outdated", "password_hash", "and", "updates", "if", "necessary", "." ]
29372225a8ee7132bf3b989b824b36cf306cc656
https://github.com/wwidea/minimalist_authentication/blob/29372225a8ee7132bf3b989b824b36cf306cc656/lib/minimalist_authentication/user.rb#L71-L78
5,668
alg/circuit_b
lib/circuit_b/fuse.rb
CircuitB.Fuse.open
def open put(:state, :open) if config[:on_break] require 'timeout' handlers = [ config[:on_break] ].flatten.map { |handler| (handler.is_a?(Symbol) ? STANDARD_HANDLERS[handler] : handler) }.compact handlers.each do |handler| begin Timeout::timeout(@break_handler_timeout) { handler.call(self) } rescue Timeout::Error # We ignore handler timeouts rescue # We ignore handler errors end end end end
ruby
def open put(:state, :open) if config[:on_break] require 'timeout' handlers = [ config[:on_break] ].flatten.map { |handler| (handler.is_a?(Symbol) ? STANDARD_HANDLERS[handler] : handler) }.compact handlers.each do |handler| begin Timeout::timeout(@break_handler_timeout) { handler.call(self) } rescue Timeout::Error # We ignore handler timeouts rescue # We ignore handler errors end end end end
[ "def", "open", "put", "(", ":state", ",", ":open", ")", "if", "config", "[", ":on_break", "]", "require", "'timeout'", "handlers", "=", "[", "config", "[", ":on_break", "]", "]", ".", "flatten", ".", "map", "{", "|", "handler", "|", "(", "handler", ".", "is_a?", "(", "Symbol", ")", "?", "STANDARD_HANDLERS", "[", "handler", "]", ":", "handler", ")", "}", ".", "compact", "handlers", ".", "each", "do", "|", "handler", "|", "begin", "Timeout", "::", "timeout", "(", "@break_handler_timeout", ")", "{", "handler", ".", "call", "(", "self", ")", "}", "rescue", "Timeout", "::", "Error", "# We ignore handler timeouts", "rescue", "# We ignore handler errors", "end", "end", "end", "end" ]
Open the fuse
[ "Open", "the", "fuse" ]
d9126c59636c6578e37179e47043b3d84834d1d4
https://github.com/alg/circuit_b/blob/d9126c59636c6578e37179e47043b3d84834d1d4/lib/circuit_b/fuse.rb#L87-L107
5,669
j0hnds/cron-spec
lib/cron-spec/cron_specification_factory.rb
CronSpec.CronSpecificationFactory.parse
def parse(value_spec) case value_spec when WildcardPattern WildcardCronValue.new(@lower_limit, @upper_limit) when @single_value_pattern SingleValueCronValue.new(@lower_limit, @upper_limit, convert_value($1)) when @range_pattern RangeCronValue.new(@lower_limit, @upper_limit, convert_value($1), convert_value($2)) when @step_pattern StepCronValue.new(@lower_limit, @upper_limit, $1.to_i) else raise "Unrecognized cron specification pattern." end end
ruby
def parse(value_spec) case value_spec when WildcardPattern WildcardCronValue.new(@lower_limit, @upper_limit) when @single_value_pattern SingleValueCronValue.new(@lower_limit, @upper_limit, convert_value($1)) when @range_pattern RangeCronValue.new(@lower_limit, @upper_limit, convert_value($1), convert_value($2)) when @step_pattern StepCronValue.new(@lower_limit, @upper_limit, $1.to_i) else raise "Unrecognized cron specification pattern." end end
[ "def", "parse", "(", "value_spec", ")", "case", "value_spec", "when", "WildcardPattern", "WildcardCronValue", ".", "new", "(", "@lower_limit", ",", "@upper_limit", ")", "when", "@single_value_pattern", "SingleValueCronValue", ".", "new", "(", "@lower_limit", ",", "@upper_limit", ",", "convert_value", "(", "$1", ")", ")", "when", "@range_pattern", "RangeCronValue", ".", "new", "(", "@lower_limit", ",", "@upper_limit", ",", "convert_value", "(", "$1", ")", ",", "convert_value", "(", "$2", ")", ")", "when", "@step_pattern", "StepCronValue", ".", "new", "(", "@lower_limit", ",", "@upper_limit", ",", "$1", ".", "to_i", ")", "else", "raise", "\"Unrecognized cron specification pattern.\"", "end", "end" ]
Constructs a new CronSpecificationFactory Parses a unit of a cron specification. The supported patterns for parsing are one of: * Wildcard '*' * Single Scalar Value [0-9]+|(sun|mon|tue|wed|thu|fri|sat)|(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec) * Range value (0-9, mon-fri, etc.) * Step value (*/[0-9]+)
[ "Constructs", "a", "new", "CronSpecificationFactory" ]
ac6dfa5cb312ec6d855ddde4e46d0bf2916121aa
https://github.com/j0hnds/cron-spec/blob/ac6dfa5cb312ec6d855ddde4e46d0bf2916121aa/lib/cron-spec/cron_specification_factory.rb#L31-L44
5,670
robertwahler/repo_manager
lib/repo_manager/views/view_helper.rb
RepoManager.ViewHelper.path_to
def path_to(*args) case when args.length == 1 base_path = :repo_manager asset = args when args.length == 2 base_path, asset = *args when args.length > 2 raise ArgumentError, "Too many arguments" else raise ArgumentError, "Specify at least the file asset" end case base_path when :repo_manager root = File.expand_path('../../../../', __FILE__) else raise "unknown base_path" end File.join(root, asset) end
ruby
def path_to(*args) case when args.length == 1 base_path = :repo_manager asset = args when args.length == 2 base_path, asset = *args when args.length > 2 raise ArgumentError, "Too many arguments" else raise ArgumentError, "Specify at least the file asset" end case base_path when :repo_manager root = File.expand_path('../../../../', __FILE__) else raise "unknown base_path" end File.join(root, asset) end
[ "def", "path_to", "(", "*", "args", ")", "case", "when", "args", ".", "length", "==", "1", "base_path", "=", ":repo_manager", "asset", "=", "args", "when", "args", ".", "length", "==", "2", "base_path", ",", "asset", "=", "args", "when", "args", ".", "length", ">", "2", "raise", "ArgumentError", ",", "\"Too many arguments\"", "else", "raise", "ArgumentError", ",", "\"Specify at least the file asset\"", "end", "case", "base_path", "when", ":repo_manager", "root", "=", "File", ".", "expand_path", "(", "'../../../../'", ",", "__FILE__", ")", "else", "raise", "\"unknown base_path\"", "end", "File", ".", "join", "(", "root", ",", "asset", ")", "end" ]
path_to returns absolute installed path to various folders packaged with the RepoManager gem @example manually require and include before use require 'repo_manager/views/view_helper' include RepoManager::ViewHelper @example default to repo_manager root path_to("views/templates/bla.rb") @example repo_manager root path_to(:repo_manager, "views/templates/bla.rb") @example :bootstrap path_to(:bootstrap, "bootstrap/css/bootstrap.css") @overload path_to(*args) @param [Symbol] base_path which gem folder should be root @param [String] file_asset path to file asset parented in the given folder @return [String] absolute path to asset
[ "path_to", "returns", "absolute", "installed", "path", "to", "various", "folders", "packaged", "with", "the", "RepoManager", "gem" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/views/view_helper.rb#L30-L52
5,671
romanbsd/mongoid_colored_logger
lib/mongoid_colored_logger/logger_decorator.rb
MongoidColoredLogger.LoggerDecorator.colorize_legacy_message
def colorize_legacy_message(message) message.sub('MONGODB', color('MONGODB', odd? ? CYAN : MAGENTA)). sub(%r{(?<=\[')([^']+)}) {|m| color(m, BLUE)}. sub(%r{(?<=\]\.)\w+}) {|m| color(m, YELLOW)} end
ruby
def colorize_legacy_message(message) message.sub('MONGODB', color('MONGODB', odd? ? CYAN : MAGENTA)). sub(%r{(?<=\[')([^']+)}) {|m| color(m, BLUE)}. sub(%r{(?<=\]\.)\w+}) {|m| color(m, YELLOW)} end
[ "def", "colorize_legacy_message", "(", "message", ")", "message", ".", "sub", "(", "'MONGODB'", ",", "color", "(", "'MONGODB'", ",", "odd?", "?", "CYAN", ":", "MAGENTA", ")", ")", ".", "sub", "(", "%r{", "\\[", "}", ")", "{", "|", "m", "|", "color", "(", "m", ",", "BLUE", ")", "}", ".", "sub", "(", "%r{", "\\]", "\\.", "\\w", "}", ")", "{", "|", "m", "|", "color", "(", "m", ",", "YELLOW", ")", "}", "end" ]
Used for Mongoid < 3.0
[ "Used", "for", "Mongoid", "<", "3", ".", "0" ]
8b3a88fb442b2d6d3335fcaeb6543b2f94b083d3
https://github.com/romanbsd/mongoid_colored_logger/blob/8b3a88fb442b2d6d3335fcaeb6543b2f94b083d3/lib/mongoid_colored_logger/logger_decorator.rb#L49-L53
5,672
romanbsd/mongoid_colored_logger
lib/mongoid_colored_logger/logger_decorator.rb
MongoidColoredLogger.LoggerDecorator.colorize_message
def colorize_message(message) message = message.sub('MONGODB', color('MONGODB', odd? ? CYAN : MAGENTA)). sub(%r{(?<=\[')([^']+)}) {|m| color(m, BLUE)}. sub(%r{(?<=\]\.)\w+}) {|m| color(m, YELLOW)} message.sub('MOPED:', color('MOPED:', odd? ? CYAN : MAGENTA)). sub(/\{.+?\}\s/) { |m| color(m, BLUE) }. sub(/COMMAND|QUERY|KILL_CURSORS|INSERT|DELETE|UPDATE|GET_MORE|STARTED/) { |m| color(m, YELLOW) }. sub(/SUCCEEDED/) { |m| color(m, GREEN) }. sub(/FAILED/) { |m| color(m, RED) }. sub(/[\d\.]+(s|ms)/) { |m| color(m, GREEN) } end
ruby
def colorize_message(message) message = message.sub('MONGODB', color('MONGODB', odd? ? CYAN : MAGENTA)). sub(%r{(?<=\[')([^']+)}) {|m| color(m, BLUE)}. sub(%r{(?<=\]\.)\w+}) {|m| color(m, YELLOW)} message.sub('MOPED:', color('MOPED:', odd? ? CYAN : MAGENTA)). sub(/\{.+?\}\s/) { |m| color(m, BLUE) }. sub(/COMMAND|QUERY|KILL_CURSORS|INSERT|DELETE|UPDATE|GET_MORE|STARTED/) { |m| color(m, YELLOW) }. sub(/SUCCEEDED/) { |m| color(m, GREEN) }. sub(/FAILED/) { |m| color(m, RED) }. sub(/[\d\.]+(s|ms)/) { |m| color(m, GREEN) } end
[ "def", "colorize_message", "(", "message", ")", "message", "=", "message", ".", "sub", "(", "'MONGODB'", ",", "color", "(", "'MONGODB'", ",", "odd?", "?", "CYAN", ":", "MAGENTA", ")", ")", ".", "sub", "(", "%r{", "\\[", "}", ")", "{", "|", "m", "|", "color", "(", "m", ",", "BLUE", ")", "}", ".", "sub", "(", "%r{", "\\]", "\\.", "\\w", "}", ")", "{", "|", "m", "|", "color", "(", "m", ",", "YELLOW", ")", "}", "message", ".", "sub", "(", "'MOPED:'", ",", "color", "(", "'MOPED:'", ",", "odd?", "?", "CYAN", ":", "MAGENTA", ")", ")", ".", "sub", "(", "/", "\\{", "\\}", "\\s", "/", ")", "{", "|", "m", "|", "color", "(", "m", ",", "BLUE", ")", "}", ".", "sub", "(", "/", "/", ")", "{", "|", "m", "|", "color", "(", "m", ",", "YELLOW", ")", "}", ".", "sub", "(", "/", "/", ")", "{", "|", "m", "|", "color", "(", "m", ",", "GREEN", ")", "}", ".", "sub", "(", "/", "/", ")", "{", "|", "m", "|", "color", "(", "m", ",", "RED", ")", "}", ".", "sub", "(", "/", "\\d", "\\.", "/", ")", "{", "|", "m", "|", "color", "(", "m", ",", "GREEN", ")", "}", "end" ]
Used for Mongoid >= 3.0
[ "Used", "for", "Mongoid", ">", "=", "3", ".", "0" ]
8b3a88fb442b2d6d3335fcaeb6543b2f94b083d3
https://github.com/romanbsd/mongoid_colored_logger/blob/8b3a88fb442b2d6d3335fcaeb6543b2f94b083d3/lib/mongoid_colored_logger/logger_decorator.rb#L56-L66
5,673
GenieBelt/gb-dispatch
lib/gb_dispatch/manager.rb
GBDispatch.Manager.get_queue
def get_queue(name=:default_queue) name = name.to_sym queue = @queues[name] unless queue @queues[name] = GBDispatch::Queue.new(name) queue = @queues[name] end queue end
ruby
def get_queue(name=:default_queue) name = name.to_sym queue = @queues[name] unless queue @queues[name] = GBDispatch::Queue.new(name) queue = @queues[name] end queue end
[ "def", "get_queue", "(", "name", "=", ":default_queue", ")", "name", "=", "name", ".", "to_sym", "queue", "=", "@queues", "[", "name", "]", "unless", "queue", "@queues", "[", "name", "]", "=", "GBDispatch", "::", "Queue", ".", "new", "(", "name", ")", "queue", "=", "@queues", "[", "name", "]", "end", "queue", "end" ]
Returns queue of given name. If queue doesn't exists it will create you a new one. Remember that for each allocated queue, there is new thread allocated. @param name [String, Symbol] if not passed, default queue will be returned. @return [GBDispatch::Queue]
[ "Returns", "queue", "of", "given", "name", "." ]
6ee932de9b397b96c82271478db1bf5933449e94
https://github.com/GenieBelt/gb-dispatch/blob/6ee932de9b397b96c82271478db1bf5933449e94/lib/gb_dispatch/manager.rb#L17-L25
5,674
GenieBelt/gb-dispatch
lib/gb_dispatch/manager.rb
GBDispatch.Manager.run_async_on_queue
def run_async_on_queue(queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue queue.async.perform_now ->() { yield } end
ruby
def run_async_on_queue(queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue queue.async.perform_now ->() { yield } end
[ "def", "run_async_on_queue", "(", "queue", ")", "raise", "ArgumentError", ".", "new", "'Queue must be GBDispatch::Queue'", "unless", "queue", ".", "is_a?", "GBDispatch", "::", "Queue", "queue", ".", "async", ".", "perform_now", "->", "(", ")", "{", "yield", "}", "end" ]
Run asynchronously given block of code on given queue. This is a proxy for {GBDispatch::Queue#perform_now} method. @param queue [GBDispatch::Queue] queue on which block will be executed @return [nil] @example my_queue = GBDispatch::Manager.instance.get_queue :my_queue GBDispatch::Manager.instance.run_async_on_queue my_queue do #my delayed code here - probably slow one :) puts 'Delayed Hello World!' end
[ "Run", "asynchronously", "given", "block", "of", "code", "on", "given", "queue", "." ]
6ee932de9b397b96c82271478db1bf5933449e94
https://github.com/GenieBelt/gb-dispatch/blob/6ee932de9b397b96c82271478db1bf5933449e94/lib/gb_dispatch/manager.rb#L38-L41
5,675
GenieBelt/gb-dispatch
lib/gb_dispatch/manager.rb
GBDispatch.Manager.run_sync_on_queue
def run_sync_on_queue(queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue future = queue.await.perform_now ->() { yield } future.value end
ruby
def run_sync_on_queue(queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue future = queue.await.perform_now ->() { yield } future.value end
[ "def", "run_sync_on_queue", "(", "queue", ")", "raise", "ArgumentError", ".", "new", "'Queue must be GBDispatch::Queue'", "unless", "queue", ".", "is_a?", "GBDispatch", "::", "Queue", "future", "=", "queue", ".", "await", ".", "perform_now", "->", "(", ")", "{", "yield", "}", "future", ".", "value", "end" ]
Run given block of code on given queue and wait for result. This method use {GBDispatch::Queue#perform_now} and wait for result. @param queue [GBDispatch::Queue] queue on which block will be executed @example sets +my_result+ to 42 my_queue = GBDispatch::Manager.instance.get_queue :my_queue my_result = GBDispatch::Manager.instance.run_sync_on_queue my_queue do # my complicated code here puts 'Delayed Hello World!' # return value 42 end
[ "Run", "given", "block", "of", "code", "on", "given", "queue", "and", "wait", "for", "result", "." ]
6ee932de9b397b96c82271478db1bf5933449e94
https://github.com/GenieBelt/gb-dispatch/blob/6ee932de9b397b96c82271478db1bf5933449e94/lib/gb_dispatch/manager.rb#L55-L59
5,676
GenieBelt/gb-dispatch
lib/gb_dispatch/manager.rb
GBDispatch.Manager.run_after_on_queue
def run_after_on_queue(time, queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue queue.perform_after time, ->(){ yield } end
ruby
def run_after_on_queue(time, queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue queue.perform_after time, ->(){ yield } end
[ "def", "run_after_on_queue", "(", "time", ",", "queue", ")", "raise", "ArgumentError", ".", "new", "'Queue must be GBDispatch::Queue'", "unless", "queue", ".", "is_a?", "GBDispatch", "::", "Queue", "queue", ".", "perform_after", "time", ",", "->", "(", ")", "{", "yield", "}", "end" ]
Run given block of code on given queue with delay. @param time [Fixnum, Float] delay in seconds @param queue [GBDispatch::Queue] queue on which block will be executed @return [nil] @example Will print 'Hello word!' after 5 seconds. my_queue = GBDispatch::Manager.instance.get_queue :my_queue my_result = GBDispatch::Manager.instance.run_after_on_queue 5, my_queue do puts 'Hello World!' end
[ "Run", "given", "block", "of", "code", "on", "given", "queue", "with", "delay", "." ]
6ee932de9b397b96c82271478db1bf5933449e94
https://github.com/GenieBelt/gb-dispatch/blob/6ee932de9b397b96c82271478db1bf5933449e94/lib/gb_dispatch/manager.rb#L71-L74
5,677
eanlain/calligraphy
lib/calligraphy/utils.rb
Calligraphy.Utils.map_array_of_hashes
def map_array_of_hashes(arr_hashes) return if arr_hashes.nil? [].tap do |output_array| arr_hashes.each do |hash| output_array.push hash.values end end end
ruby
def map_array_of_hashes(arr_hashes) return if arr_hashes.nil? [].tap do |output_array| arr_hashes.each do |hash| output_array.push hash.values end end end
[ "def", "map_array_of_hashes", "(", "arr_hashes", ")", "return", "if", "arr_hashes", ".", "nil?", "[", "]", ".", "tap", "do", "|", "output_array", "|", "arr_hashes", ".", "each", "do", "|", "hash", "|", "output_array", ".", "push", "hash", ".", "values", "end", "end", "end" ]
Given an array of hashes, returns an array of hash values.
[ "Given", "an", "array", "of", "hashes", "returns", "an", "array", "of", "hash", "values", "." ]
19290d38322287fcb8e0152a7ed3b7f01033b57e
https://github.com/eanlain/calligraphy/blob/19290d38322287fcb8e0152a7ed3b7f01033b57e/lib/calligraphy/utils.rb#L36-L44
5,678
eanlain/calligraphy
lib/calligraphy/utils.rb
Calligraphy.Utils.extract_lock_token
def extract_lock_token(if_header) token = if_header.scan(Calligraphy::LOCK_TOKEN_REGEX) token.flatten.first if token.is_a? Array end
ruby
def extract_lock_token(if_header) token = if_header.scan(Calligraphy::LOCK_TOKEN_REGEX) token.flatten.first if token.is_a? Array end
[ "def", "extract_lock_token", "(", "if_header", ")", "token", "=", "if_header", ".", "scan", "(", "Calligraphy", "::", "LOCK_TOKEN_REGEX", ")", "token", ".", "flatten", ".", "first", "if", "token", ".", "is_a?", "Array", "end" ]
Extracts a lock token from an If headers.
[ "Extracts", "a", "lock", "token", "from", "an", "If", "headers", "." ]
19290d38322287fcb8e0152a7ed3b7f01033b57e
https://github.com/eanlain/calligraphy/blob/19290d38322287fcb8e0152a7ed3b7f01033b57e/lib/calligraphy/utils.rb#L47-L50
5,679
eprothro/cassie
lib/cassie/statements/execution.rb
Cassie::Statements.Execution.execute
def execute(opts={}) @result = result_class.new(session.execute(statement, execution_options.merge(opts)), result_opts) result.success? end
ruby
def execute(opts={}) @result = result_class.new(session.execute(statement, execution_options.merge(opts)), result_opts) result.success? end
[ "def", "execute", "(", "opts", "=", "{", "}", ")", "@result", "=", "result_class", ".", "new", "(", "session", ".", "execute", "(", "statement", ",", "execution_options", ".", "merge", "(", "opts", ")", ")", ",", "result_opts", ")", "result", ".", "success?", "end" ]
Executes the statment and populates result @param [Hash{Symbol => Object}] cassandra_driver execution options @return [Boolean] indicating a successful execution or not
[ "Executes", "the", "statment", "and", "populates", "result" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/statements/execution.rb#L59-L62
5,680
eprothro/cassie
lib/cassie/statements/execution.rb
Cassie::Statements.Execution.execution_options
def execution_options {}.tap do |opts| # @todo rework consistency module to be more # abstract implementation for all execution options opts[:consistency] = consistency if consistency opts[:paging_state] = paging_state if respond_to?(:paging_state) && paging_state opts[:page_size] = stateless_page_size if respond_to?(:stateless_page_size) && stateless_page_size end end
ruby
def execution_options {}.tap do |opts| # @todo rework consistency module to be more # abstract implementation for all execution options opts[:consistency] = consistency if consistency opts[:paging_state] = paging_state if respond_to?(:paging_state) && paging_state opts[:page_size] = stateless_page_size if respond_to?(:stateless_page_size) && stateless_page_size end end
[ "def", "execution_options", "{", "}", ".", "tap", "do", "|", "opts", "|", "# @todo rework consistency module to be more", "# abstract implementation for all execution options", "opts", "[", ":consistency", "]", "=", "consistency", "if", "consistency", "opts", "[", ":paging_state", "]", "=", "paging_state", "if", "respond_to?", "(", ":paging_state", ")", "&&", "paging_state", "opts", "[", ":page_size", "]", "=", "stateless_page_size", "if", "respond_to?", "(", ":stateless_page_size", ")", "&&", "stateless_page_size", "end", "end" ]
The session exection options configured for statement execution @return [Hash{Symbol => Object}]
[ "The", "session", "exection", "options", "configured", "for", "statement", "execution" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/statements/execution.rb#L74-L82
5,681
robertwahler/repo_manager
lib/repo_manager/tasks/add/asset.rb
RepoManager.Add.save_writable_attributes
def save_writable_attributes(asset, attributes) valid_keys = [:parent, :path] accessable_attributes = {} attributes.each do |key, value| accessable_attributes[key] = value.dup if valid_keys.include?(key) end asset.configuration.save(accessable_attributes) end
ruby
def save_writable_attributes(asset, attributes) valid_keys = [:parent, :path] accessable_attributes = {} attributes.each do |key, value| accessable_attributes[key] = value.dup if valid_keys.include?(key) end asset.configuration.save(accessable_attributes) end
[ "def", "save_writable_attributes", "(", "asset", ",", "attributes", ")", "valid_keys", "=", "[", ":parent", ",", ":path", "]", "accessable_attributes", "=", "{", "}", "attributes", ".", "each", "do", "|", "key", ",", "value", "|", "accessable_attributes", "[", "key", "]", "=", "value", ".", "dup", "if", "valid_keys", ".", "include?", "(", "key", ")", "end", "asset", ".", "configuration", ".", "save", "(", "accessable_attributes", ")", "end" ]
write only the attributes that we have set
[ "write", "only", "the", "attributes", "that", "we", "have", "set" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/tasks/add/asset.rb#L199-L206
5,682
jwtd/ekm-omnimeter
lib/ekm-omnimeter/meter.rb
EkmOmnimeter.Meter.method_missing
def method_missing(method_sym, *arguments, &block) # Only refresh data if its more than 0.25 seconds old et = @last_read_timestamp.nil? ? 0 : (Time.now - @last_read_timestamp) @logger.debug "Elapsed time since last read #{et}" if et > 250 @logger.info "More than 250 milliseconds have passed since last read. Triggering refresh." read() end if @values.include? method_sym @values[method_sym] else @logger.debug "method_missing failed to find #{method_sym} in the Meter.values cache" super end end
ruby
def method_missing(method_sym, *arguments, &block) # Only refresh data if its more than 0.25 seconds old et = @last_read_timestamp.nil? ? 0 : (Time.now - @last_read_timestamp) @logger.debug "Elapsed time since last read #{et}" if et > 250 @logger.info "More than 250 milliseconds have passed since last read. Triggering refresh." read() end if @values.include? method_sym @values[method_sym] else @logger.debug "method_missing failed to find #{method_sym} in the Meter.values cache" super end end
[ "def", "method_missing", "(", "method_sym", ",", "*", "arguments", ",", "&", "block", ")", "# Only refresh data if its more than 0.25 seconds old", "et", "=", "@last_read_timestamp", ".", "nil?", "?", "0", ":", "(", "Time", ".", "now", "-", "@last_read_timestamp", ")", "@logger", ".", "debug", "\"Elapsed time since last read #{et}\"", "if", "et", ">", "250", "@logger", ".", "info", "\"More than 250 milliseconds have passed since last read. Triggering refresh.\"", "read", "(", ")", "end", "if", "@values", ".", "include?", "method_sym", "@values", "[", "method_sym", "]", "else", "@logger", ".", "debug", "\"method_missing failed to find #{method_sym} in the Meter.values cache\"", "super", "end", "end" ]
Attribute handler that delegates attribute reads to the values hash
[ "Attribute", "handler", "that", "delegates", "attribute", "reads", "to", "the", "values", "hash" ]
7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401
https://github.com/jwtd/ekm-omnimeter/blob/7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401/lib/ekm-omnimeter/meter.rb#L140-L155
5,683
jwtd/ekm-omnimeter
lib/ekm-omnimeter/meter.rb
EkmOmnimeter.Meter.calculate_measurement
def calculate_measurement(m1, m2, m3) if power_configuration == :single_phase_2wire m1 elsif power_configuration == :single_phase_3wire (m1 + m2) elsif power_configuration == :three_phase_3wire (m1 + m3) elsif power_configuration == :three_phase_4wire (m1 + m2 + m3) end end
ruby
def calculate_measurement(m1, m2, m3) if power_configuration == :single_phase_2wire m1 elsif power_configuration == :single_phase_3wire (m1 + m2) elsif power_configuration == :three_phase_3wire (m1 + m3) elsif power_configuration == :three_phase_4wire (m1 + m2 + m3) end end
[ "def", "calculate_measurement", "(", "m1", ",", "m2", ",", "m3", ")", "if", "power_configuration", "==", ":single_phase_2wire", "m1", "elsif", "power_configuration", "==", ":single_phase_3wire", "(", "m1", "+", "m2", ")", "elsif", "power_configuration", "==", ":three_phase_3wire", "(", "m1", "+", "m3", ")", "elsif", "power_configuration", "==", ":three_phase_4wire", "(", "m1", "+", "m2", "+", "m3", ")", "end", "end" ]
Returns the correct measurement for voltage, current, and power based on the corresponding power_configuration
[ "Returns", "the", "correct", "measurement", "for", "voltage", "current", "and", "power", "based", "on", "the", "corresponding", "power_configuration" ]
7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401
https://github.com/jwtd/ekm-omnimeter/blob/7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401/lib/ekm-omnimeter/meter.rb#L512-L522
5,684
jwtd/ekm-omnimeter
lib/ekm-omnimeter/meter.rb
EkmOmnimeter.Meter.as_datetime
def as_datetime(s) begin d = DateTime.new("20#{s[0,2]}".to_i, s[2,2].to_i, s[4,2].to_i, s[8,2].to_i, s[10,2].to_i, s[12,2].to_i, '-4') rescue logger.error "Could not create valid datetime from #{s}\nDateTime.new(20#{s[0,2]}, #{s[2,2]}, #{s[4,2]}, #{s[8,2]}, #{s[10,2]}, #{s[12,2]}, '-4')" d = DateTime.now() end d end
ruby
def as_datetime(s) begin d = DateTime.new("20#{s[0,2]}".to_i, s[2,2].to_i, s[4,2].to_i, s[8,2].to_i, s[10,2].to_i, s[12,2].to_i, '-4') rescue logger.error "Could not create valid datetime from #{s}\nDateTime.new(20#{s[0,2]}, #{s[2,2]}, #{s[4,2]}, #{s[8,2]}, #{s[10,2]}, #{s[12,2]}, '-4')" d = DateTime.now() end d end
[ "def", "as_datetime", "(", "s", ")", "begin", "d", "=", "DateTime", ".", "new", "(", "\"20#{s[0,2]}\"", ".", "to_i", ",", "s", "[", "2", ",", "2", "]", ".", "to_i", ",", "s", "[", "4", ",", "2", "]", ".", "to_i", ",", "s", "[", "8", ",", "2", "]", ".", "to_i", ",", "s", "[", "10", ",", "2", "]", ".", "to_i", ",", "s", "[", "12", ",", "2", "]", ".", "to_i", ",", "'-4'", ")", "rescue", "logger", ".", "error", "\"Could not create valid datetime from #{s}\\nDateTime.new(20#{s[0,2]}, #{s[2,2]}, #{s[4,2]}, #{s[8,2]}, #{s[10,2]}, #{s[12,2]}, '-4')\"", "d", "=", "DateTime", ".", "now", "(", ")", "end", "d", "end" ]
Returns a Ruby datatime derived from the string representing the time on the meter when the values were captured The raw string's format is YYMMDDWWHHMMSS where YY is year without century, and WW is week day with Sunday as the first day of the week
[ "Returns", "a", "Ruby", "datatime", "derived", "from", "the", "string", "representing", "the", "time", "on", "the", "meter", "when", "the", "values", "were", "captured", "The", "raw", "string", "s", "format", "is", "YYMMDDWWHHMMSS", "where", "YY", "is", "year", "without", "century", "and", "WW", "is", "week", "day", "with", "Sunday", "as", "the", "first", "day", "of", "the", "week" ]
7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401
https://github.com/jwtd/ekm-omnimeter/blob/7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401/lib/ekm-omnimeter/meter.rb#L527-L535
5,685
jwtd/ekm-omnimeter
lib/ekm-omnimeter/meter.rb
EkmOmnimeter.Meter.to_f_with_decimal_places
def to_f_with_decimal_places(s, p=1) unless s.nil? v = (s.to_f / (10 ** p)) logger.debug "Casting #{s.inspect} -> #{v.inspect}" v else logger.error "Could not cast #{s} to #{p} decimal places" end end
ruby
def to_f_with_decimal_places(s, p=1) unless s.nil? v = (s.to_f / (10 ** p)) logger.debug "Casting #{s.inspect} -> #{v.inspect}" v else logger.error "Could not cast #{s} to #{p} decimal places" end end
[ "def", "to_f_with_decimal_places", "(", "s", ",", "p", "=", "1", ")", "unless", "s", ".", "nil?", "v", "=", "(", "s", ".", "to_f", "/", "(", "10", "**", "p", ")", ")", "logger", ".", "debug", "\"Casting #{s.inspect} -> #{v.inspect}\"", "v", "else", "logger", ".", "error", "\"Could not cast #{s} to #{p} decimal places\"", "end", "end" ]
Generic way of casting strings to numbers with the decimal in the correct place
[ "Generic", "way", "of", "casting", "strings", "to", "numbers", "with", "the", "decimal", "in", "the", "correct", "place" ]
7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401
https://github.com/jwtd/ekm-omnimeter/blob/7dd45f9e3f8fae3c9f9ca8c28338d218eb53a401/lib/ekm-omnimeter/meter.rb#L552-L560
5,686
rvolz/docbook_status
lib/docbook_status/history.rb
DocbookStatus.History.add
def add(ts, word_count) # Ruby 1.8 doesn't have DateTime#to_date, so we check that here begin k = ts.to_date rescue NoMethodError k = Date.parse(ts.to_s) end if @history[:archive][k].nil? @history[:archive][k] = { min: word_count, max: word_count, start: word_count, end: word_count, ctr: 1 } else @history[:archive][k][:min] = word_count if @history[:archive][k][:min] > word_count @history[:archive][k][:max] = word_count if @history[:archive][k][:max] < word_count @history[:archive][k][:end] = word_count @history[:archive][k][:ctr] += 1 end end
ruby
def add(ts, word_count) # Ruby 1.8 doesn't have DateTime#to_date, so we check that here begin k = ts.to_date rescue NoMethodError k = Date.parse(ts.to_s) end if @history[:archive][k].nil? @history[:archive][k] = { min: word_count, max: word_count, start: word_count, end: word_count, ctr: 1 } else @history[:archive][k][:min] = word_count if @history[:archive][k][:min] > word_count @history[:archive][k][:max] = word_count if @history[:archive][k][:max] < word_count @history[:archive][k][:end] = word_count @history[:archive][k][:ctr] += 1 end end
[ "def", "add", "(", "ts", ",", "word_count", ")", "# Ruby 1.8 doesn't have DateTime#to_date, so we check that here", "begin", "k", "=", "ts", ".", "to_date", "rescue", "NoMethodError", "k", "=", "Date", ".", "parse", "(", "ts", ".", "to_s", ")", "end", "if", "@history", "[", ":archive", "]", "[", "k", "]", ".", "nil?", "@history", "[", ":archive", "]", "[", "k", "]", "=", "{", "min", ":", "word_count", ",", "max", ":", "word_count", ",", "start", ":", "word_count", ",", "end", ":", "word_count", ",", "ctr", ":", "1", "}", "else", "@history", "[", ":archive", "]", "[", "k", "]", "[", ":min", "]", "=", "word_count", "if", "@history", "[", ":archive", "]", "[", "k", "]", "[", ":min", "]", ">", "word_count", "@history", "[", ":archive", "]", "[", "k", "]", "[", ":max", "]", "=", "word_count", "if", "@history", "[", ":archive", "]", "[", "k", "]", "[", ":max", "]", "<", "word_count", "@history", "[", ":archive", "]", "[", "k", "]", "[", ":end", "]", "=", "word_count", "@history", "[", ":archive", "]", "[", "k", "]", "[", ":ctr", "]", "+=", "1", "end", "end" ]
Add to the history
[ "Add", "to", "the", "history" ]
228602b0eed4f6114fce9ad5327e4201ac2a9c1b
https://github.com/rvolz/docbook_status/blob/228602b0eed4f6114fce9ad5327e4201ac2a9c1b/lib/docbook_status/history.rb#L74-L89
5,687
Falkor/falkorlib
lib/falkorlib/git/flow.rb
FalkorLib.GitFlow.command
def command(name, type = 'feature', action = 'start', path = Dir.pwd, optional_args = '') error "Invalid git-flow type '#{type}'" unless %w(feature release hotfix support).include?(type) error "Invalid action '#{action}'" unless %w(start finish).include?(action) error "You must provide a name" if name == '' error "The name '#{name}' cannot contain spaces" if name =~ /\s+/ exit_status = 1 Dir.chdir( FalkorLib::Git.rootdir(path) ) do exit_status = run %( git flow #{type} #{action} #{optional_args} #{name} ) end exit_status end
ruby
def command(name, type = 'feature', action = 'start', path = Dir.pwd, optional_args = '') error "Invalid git-flow type '#{type}'" unless %w(feature release hotfix support).include?(type) error "Invalid action '#{action}'" unless %w(start finish).include?(action) error "You must provide a name" if name == '' error "The name '#{name}' cannot contain spaces" if name =~ /\s+/ exit_status = 1 Dir.chdir( FalkorLib::Git.rootdir(path) ) do exit_status = run %( git flow #{type} #{action} #{optional_args} #{name} ) end exit_status end
[ "def", "command", "(", "name", ",", "type", "=", "'feature'", ",", "action", "=", "'start'", ",", "path", "=", "Dir", ".", "pwd", ",", "optional_args", "=", "''", ")", "error", "\"Invalid git-flow type '#{type}'\"", "unless", "%w(", "feature", "release", "hotfix", "support", ")", ".", "include?", "(", "type", ")", "error", "\"Invalid action '#{action}'\"", "unless", "%w(", "start", "finish", ")", ".", "include?", "(", "action", ")", "error", "\"You must provide a name\"", "if", "name", "==", "''", "error", "\"The name '#{name}' cannot contain spaces\"", "if", "name", "=~", "/", "\\s", "/", "exit_status", "=", "1", "Dir", ".", "chdir", "(", "FalkorLib", "::", "Git", ".", "rootdir", "(", "path", ")", ")", "do", "exit_status", "=", "run", "%(\n git flow #{type} #{action} #{optional_args} #{name}\n )", "end", "exit_status", "end" ]
generic function to run any of the gitflow commands
[ "generic", "function", "to", "run", "any", "of", "the", "gitflow", "commands" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/flow.rb#L154-L166
5,688
Falkor/falkorlib
lib/falkorlib/git/flow.rb
FalkorLib.GitFlow.guess_gitflow_config
def guess_gitflow_config(dir = Dir.pwd, options = {}) path = normalized_path(dir) use_git = FalkorLib::Git.init?(path) return {} if (!use_git or !FalkorLib::GitFlow.init?(path)) rootdir = FalkorLib::Git.rootdir(path) local_config = FalkorLib::Config.get(rootdir, :local) return local_config[:gitflow] if local_config[:gitflow] config = FalkorLib::Config::GitFlow::DEFAULTS.clone [ :master, :develop ].each do |br| config[:branches][br.to_sym] = FalkorLib::Git.config("gitflow.branch.#{br}", rootdir) end [ :feature, :release, :hotfix, :support, :versiontag ].each do |p| config[:prefix][p.to_sym] = FalkorLib::Git.config("gitflow.prefix.#{p}", rootdir) end config end
ruby
def guess_gitflow_config(dir = Dir.pwd, options = {}) path = normalized_path(dir) use_git = FalkorLib::Git.init?(path) return {} if (!use_git or !FalkorLib::GitFlow.init?(path)) rootdir = FalkorLib::Git.rootdir(path) local_config = FalkorLib::Config.get(rootdir, :local) return local_config[:gitflow] if local_config[:gitflow] config = FalkorLib::Config::GitFlow::DEFAULTS.clone [ :master, :develop ].each do |br| config[:branches][br.to_sym] = FalkorLib::Git.config("gitflow.branch.#{br}", rootdir) end [ :feature, :release, :hotfix, :support, :versiontag ].each do |p| config[:prefix][p.to_sym] = FalkorLib::Git.config("gitflow.prefix.#{p}", rootdir) end config end
[ "def", "guess_gitflow_config", "(", "dir", "=", "Dir", ".", "pwd", ",", "options", "=", "{", "}", ")", "path", "=", "normalized_path", "(", "dir", ")", "use_git", "=", "FalkorLib", "::", "Git", ".", "init?", "(", "path", ")", "return", "{", "}", "if", "(", "!", "use_git", "or", "!", "FalkorLib", "::", "GitFlow", ".", "init?", "(", "path", ")", ")", "rootdir", "=", "FalkorLib", "::", "Git", ".", "rootdir", "(", "path", ")", "local_config", "=", "FalkorLib", "::", "Config", ".", "get", "(", "rootdir", ",", ":local", ")", "return", "local_config", "[", ":gitflow", "]", "if", "local_config", "[", ":gitflow", "]", "config", "=", "FalkorLib", "::", "Config", "::", "GitFlow", "::", "DEFAULTS", ".", "clone", "[", ":master", ",", ":develop", "]", ".", "each", "do", "|", "br", "|", "config", "[", ":branches", "]", "[", "br", ".", "to_sym", "]", "=", "FalkorLib", "::", "Git", ".", "config", "(", "\"gitflow.branch.#{br}\"", ",", "rootdir", ")", "end", "[", ":feature", ",", ":release", ",", ":hotfix", ",", ":support", ",", ":versiontag", "]", ".", "each", "do", "|", "p", "|", "config", "[", ":prefix", "]", "[", "p", ".", "to_sym", "]", "=", "FalkorLib", "::", "Git", ".", "config", "(", "\"gitflow.prefix.#{p}\"", ",", "rootdir", ")", "end", "config", "end" ]
master_branch guess_gitflow_config Guess the gitflow configuration
[ "master_branch", "guess_gitflow_config", "Guess", "the", "gitflow", "configuration" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/flow.rb#L191-L206
5,689
STUDITEMPS/jobmensa_assets
lib/jobmensa_assets/image_processor.rb
JobmensaAssets.ImageProcessor.call
def call(file, *args, format: nil) img = ::MiniMagick::Image.new(file.path) img.quiet img.format(format.to_s.downcase, nil) if format send(@method, img, *args) post_processing(img) ::File.open(img.path, "rb") end
ruby
def call(file, *args, format: nil) img = ::MiniMagick::Image.new(file.path) img.quiet img.format(format.to_s.downcase, nil) if format send(@method, img, *args) post_processing(img) ::File.open(img.path, "rb") end
[ "def", "call", "(", "file", ",", "*", "args", ",", "format", ":", "nil", ")", "img", "=", "::", "MiniMagick", "::", "Image", ".", "new", "(", "file", ".", "path", ")", "img", ".", "quiet", "img", ".", "format", "(", "format", ".", "to_s", ".", "downcase", ",", "nil", ")", "if", "format", "send", "(", "@method", ",", "img", ",", "args", ")", "post_processing", "(", "img", ")", "::", "File", ".", "open", "(", "img", ".", "path", ",", "\"rb\"", ")", "end" ]
Overwrite refile call method to supress format warnings and do post-processing
[ "Overwrite", "refile", "call", "method", "to", "supress", "format", "warnings", "and", "do", "post", "-", "processing" ]
9ef443a28d939130621d4310fdb174764a00baac
https://github.com/STUDITEMPS/jobmensa_assets/blob/9ef443a28d939130621d4310fdb174764a00baac/lib/jobmensa_assets/image_processor.rb#L15-L23
5,690
STUDITEMPS/jobmensa_assets
lib/jobmensa_assets/image_processor.rb
JobmensaAssets.ImageProcessor.post_processing
def post_processing(img) img.combine_options do |cmd| cmd.strip # Deletes metatags cmd.colorspace 'sRGB' # Change colorspace cmd.auto_orient # Reset rotation cmd.quiet # Suppress warnings end end
ruby
def post_processing(img) img.combine_options do |cmd| cmd.strip # Deletes metatags cmd.colorspace 'sRGB' # Change colorspace cmd.auto_orient # Reset rotation cmd.quiet # Suppress warnings end end
[ "def", "post_processing", "(", "img", ")", "img", ".", "combine_options", "do", "|", "cmd", "|", "cmd", ".", "strip", "# Deletes metatags", "cmd", ".", "colorspace", "'sRGB'", "# Change colorspace", "cmd", ".", "auto_orient", "# Reset rotation", "cmd", ".", "quiet", "# Suppress warnings", "end", "end" ]
Should be called for every jobmensa processor
[ "Should", "be", "called", "for", "every", "jobmensa", "processor" ]
9ef443a28d939130621d4310fdb174764a00baac
https://github.com/STUDITEMPS/jobmensa_assets/blob/9ef443a28d939130621d4310fdb174764a00baac/lib/jobmensa_assets/image_processor.rb#L29-L36
5,691
paulRbr/gares
lib/gares/train.rb
Gares.Train.document
def document if !@document @document = Nokogiri::HTML(self.class.request_sncf(number, date)) if !itinerary_available? @document = Nokogiri::HTML(self.class.request_sncf_itinerary(0)) end end if @document.at('#no_results') fail TrainNotFound, @document.at('#no_results b').inner_html end @document end
ruby
def document if !@document @document = Nokogiri::HTML(self.class.request_sncf(number, date)) if !itinerary_available? @document = Nokogiri::HTML(self.class.request_sncf_itinerary(0)) end end if @document.at('#no_results') fail TrainNotFound, @document.at('#no_results b').inner_html end @document end
[ "def", "document", "if", "!", "@document", "@document", "=", "Nokogiri", "::", "HTML", "(", "self", ".", "class", ".", "request_sncf", "(", "number", ",", "date", ")", ")", "if", "!", "itinerary_available?", "@document", "=", "Nokogiri", "::", "HTML", "(", "self", ".", "class", ".", "request_sncf_itinerary", "(", "0", ")", ")", "end", "end", "if", "@document", ".", "at", "(", "'#no_results'", ")", "fail", "TrainNotFound", ",", "@document", ".", "at", "(", "'#no_results b'", ")", ".", "inner_html", "end", "@document", "end" ]
Returns a new Nokogiri document for parsing.
[ "Returns", "a", "new", "Nokogiri", "document", "for", "parsing", "." ]
6646da7c98ffe51f419e9bd6d8d87204ac72da67
https://github.com/paulRbr/gares/blob/6646da7c98ffe51f419e9bd6d8d87204ac72da67/lib/gares/train.rb#L91-L102
5,692
Nedomas/securities
lib/securities/stock.rb
Securities.Stock.generate_history_url
def generate_history_url url = 'http://ichart.finance.yahoo.com/table.csv?s=%s&a=%s&b=%s&c=%s&d=%s&e=%s&f=%s&g=%s&ignore=.csv' % [ @symbol, @start_date.to_date.month - 1, @start_date.to_date.day, @start_date.to_date.year, @end_date.to_date.month - 1, @end_date.to_date.day, @end_date.to_date.year, TYPE_CODES_ARRAY[@type] ] return url end
ruby
def generate_history_url url = 'http://ichart.finance.yahoo.com/table.csv?s=%s&a=%s&b=%s&c=%s&d=%s&e=%s&f=%s&g=%s&ignore=.csv' % [ @symbol, @start_date.to_date.month - 1, @start_date.to_date.day, @start_date.to_date.year, @end_date.to_date.month - 1, @end_date.to_date.day, @end_date.to_date.year, TYPE_CODES_ARRAY[@type] ] return url end
[ "def", "generate_history_url", "url", "=", "'http://ichart.finance.yahoo.com/table.csv?s=%s&a=%s&b=%s&c=%s&d=%s&e=%s&f=%s&g=%s&ignore=.csv'", "%", "[", "@symbol", ",", "@start_date", ".", "to_date", ".", "month", "-", "1", ",", "@start_date", ".", "to_date", ".", "day", ",", "@start_date", ".", "to_date", ".", "year", ",", "@end_date", ".", "to_date", ".", "month", "-", "1", ",", "@end_date", ".", "to_date", ".", "day", ",", "@end_date", ".", "to_date", ".", "year", ",", "TYPE_CODES_ARRAY", "[", "@type", "]", "]", "return", "url", "end" ]
History URL generator Generating URL for various types of requests within stocks. Using Yahoo Finance http://ichart.finance.yahoo.com/table.csv?s=%s&a=%s&b=%s&c=%s&d=%s&e=%s&f=%s&g=%s&ignore=.csv s = stock symbol Period start date a = start month b = start day c = start year Period end date d = end month e = end day f = end year g = type Type values allowed: 'd' for daily (the default), 'w' for weekly, 'm' for monthly and 'v' for dividends.
[ "History", "URL", "generator" ]
e2c4953edcb7315d49663f2e5b71aaf6b27d97d1
https://github.com/Nedomas/securities/blob/e2c4953edcb7315d49663f2e5b71aaf6b27d97d1/lib/securities/stock.rb#L48-L62
5,693
Nedomas/securities
lib/securities/stock.rb
Securities.Stock.validate_input
def validate_input parameters unless parameters.is_a?(Hash) raise StockException, 'Given parameters have to be a hash.' end # Check if stock symbol is specified. unless parameters.has_key?(:symbol) raise StockException, 'No stock symbol specified.' end # Check if stock symbol is a string. unless parameters[:symbol].is_a?(String) raise StockException, 'Stock symbol must be a string.' end # Use today date if :end_date is not specified. unless parameters.has_key?(:end_date) parameters[:end_date] = Date.today.strftime("%Y-%m-%d") end unless parameters.has_key?(:start_date) raise StockException, 'Start date must be specified.' end unless DATE_REGEX.match(parameters[:start_date]) raise StockException, 'Invalid start date specified. Format YYYY-MM-DD.' end unless DATE_REGEX.match(parameters[:end_date]) raise StockException, 'Invalid end date specified. Format YYYY-MM-DD.' end unless parameters[:start_date].to_date < parameters[:end_date].to_date raise StockException, 'End date must be greater than the start date.' end unless parameters[:start_date].to_date < Date.today raise StockException, 'Start date must not be in the future.' end # Set to default :type if key isn't specified. parameters[:type] = :daily if !parameters.has_key?(:type) unless TYPE_CODES_ARRAY.has_key?(parameters[:type]) raise StockException, 'Invalid type specified.' end end
ruby
def validate_input parameters unless parameters.is_a?(Hash) raise StockException, 'Given parameters have to be a hash.' end # Check if stock symbol is specified. unless parameters.has_key?(:symbol) raise StockException, 'No stock symbol specified.' end # Check if stock symbol is a string. unless parameters[:symbol].is_a?(String) raise StockException, 'Stock symbol must be a string.' end # Use today date if :end_date is not specified. unless parameters.has_key?(:end_date) parameters[:end_date] = Date.today.strftime("%Y-%m-%d") end unless parameters.has_key?(:start_date) raise StockException, 'Start date must be specified.' end unless DATE_REGEX.match(parameters[:start_date]) raise StockException, 'Invalid start date specified. Format YYYY-MM-DD.' end unless DATE_REGEX.match(parameters[:end_date]) raise StockException, 'Invalid end date specified. Format YYYY-MM-DD.' end unless parameters[:start_date].to_date < parameters[:end_date].to_date raise StockException, 'End date must be greater than the start date.' end unless parameters[:start_date].to_date < Date.today raise StockException, 'Start date must not be in the future.' end # Set to default :type if key isn't specified. parameters[:type] = :daily if !parameters.has_key?(:type) unless TYPE_CODES_ARRAY.has_key?(parameters[:type]) raise StockException, 'Invalid type specified.' end end
[ "def", "validate_input", "parameters", "unless", "parameters", ".", "is_a?", "(", "Hash", ")", "raise", "StockException", ",", "'Given parameters have to be a hash.'", "end", "# Check if stock symbol is specified.", "unless", "parameters", ".", "has_key?", "(", ":symbol", ")", "raise", "StockException", ",", "'No stock symbol specified.'", "end", "# Check if stock symbol is a string.", "unless", "parameters", "[", ":symbol", "]", ".", "is_a?", "(", "String", ")", "raise", "StockException", ",", "'Stock symbol must be a string.'", "end", "# Use today date if :end_date is not specified.", "unless", "parameters", ".", "has_key?", "(", ":end_date", ")", "parameters", "[", ":end_date", "]", "=", "Date", ".", "today", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "end", "unless", "parameters", ".", "has_key?", "(", ":start_date", ")", "raise", "StockException", ",", "'Start date must be specified.'", "end", "unless", "DATE_REGEX", ".", "match", "(", "parameters", "[", ":start_date", "]", ")", "raise", "StockException", ",", "'Invalid start date specified. Format YYYY-MM-DD.'", "end", "unless", "DATE_REGEX", ".", "match", "(", "parameters", "[", ":end_date", "]", ")", "raise", "StockException", ",", "'Invalid end date specified. Format YYYY-MM-DD.'", "end", "unless", "parameters", "[", ":start_date", "]", ".", "to_date", "<", "parameters", "[", ":end_date", "]", ".", "to_date", "raise", "StockException", ",", "'End date must be greater than the start date.'", "end", "unless", "parameters", "[", ":start_date", "]", ".", "to_date", "<", "Date", ".", "today", "raise", "StockException", ",", "'Start date must not be in the future.'", "end", "# Set to default :type if key isn't specified.", "parameters", "[", ":type", "]", "=", ":daily", "if", "!", "parameters", ".", "has_key?", "(", ":type", ")", "unless", "TYPE_CODES_ARRAY", ".", "has_key?", "(", "parameters", "[", ":type", "]", ")", "raise", "StockException", ",", "'Invalid type specified.'", "end", "end" ]
Input parameters validation
[ "Input", "parameters", "validation" ]
e2c4953edcb7315d49663f2e5b71aaf6b27d97d1
https://github.com/Nedomas/securities/blob/e2c4953edcb7315d49663f2e5b71aaf6b27d97d1/lib/securities/stock.rb#L68-L113
5,694
praxis/praxis-blueprints
lib/praxis-blueprints/renderer.rb
Praxis.Renderer.render_collection
def render_collection(collection, member_fields, view = nil, context: Attributor::DEFAULT_ROOT_CONTEXT) render(collection, [member_fields], view, context: context) end
ruby
def render_collection(collection, member_fields, view = nil, context: Attributor::DEFAULT_ROOT_CONTEXT) render(collection, [member_fields], view, context: context) end
[ "def", "render_collection", "(", "collection", ",", "member_fields", ",", "view", "=", "nil", ",", "context", ":", "Attributor", "::", "DEFAULT_ROOT_CONTEXT", ")", "render", "(", "collection", ",", "[", "member_fields", "]", ",", "view", ",", "context", ":", "context", ")", "end" ]
Renders an a collection using a given list of per-member fields. @param [Object] object the object to render @param [Hash] fields the set of fields, as from FieldExpander, to apply to each member of the collection.
[ "Renders", "an", "a", "collection", "using", "a", "given", "list", "of", "per", "-", "member", "fields", "." ]
57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c
https://github.com/praxis/praxis-blueprints/blob/57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c/lib/praxis-blueprints/renderer.rb#L34-L36
5,695
praxis/praxis-blueprints
lib/praxis-blueprints/renderer.rb
Praxis.Renderer.render
def render(object, fields, view = nil, context: Attributor::DEFAULT_ROOT_CONTEXT) if fields.is_a? Array sub_fields = fields[0] object.each_with_index.collect do |sub_object, i| sub_context = context + ["at(#{i})"] render(sub_object, sub_fields, view, context: sub_context) end elsif object.is_a? Praxis::Blueprint @cache[object.object_id][fields.object_id] ||= _render(object, fields, view, context: context) else _render(object, fields, view, context: context) end rescue SystemStackError raise CircularRenderingError.new(object, context) end
ruby
def render(object, fields, view = nil, context: Attributor::DEFAULT_ROOT_CONTEXT) if fields.is_a? Array sub_fields = fields[0] object.each_with_index.collect do |sub_object, i| sub_context = context + ["at(#{i})"] render(sub_object, sub_fields, view, context: sub_context) end elsif object.is_a? Praxis::Blueprint @cache[object.object_id][fields.object_id] ||= _render(object, fields, view, context: context) else _render(object, fields, view, context: context) end rescue SystemStackError raise CircularRenderingError.new(object, context) end
[ "def", "render", "(", "object", ",", "fields", ",", "view", "=", "nil", ",", "context", ":", "Attributor", "::", "DEFAULT_ROOT_CONTEXT", ")", "if", "fields", ".", "is_a?", "Array", "sub_fields", "=", "fields", "[", "0", "]", "object", ".", "each_with_index", ".", "collect", "do", "|", "sub_object", ",", "i", "|", "sub_context", "=", "context", "+", "[", "\"at(#{i})\"", "]", "render", "(", "sub_object", ",", "sub_fields", ",", "view", ",", "context", ":", "sub_context", ")", "end", "elsif", "object", ".", "is_a?", "Praxis", "::", "Blueprint", "@cache", "[", "object", ".", "object_id", "]", "[", "fields", ".", "object_id", "]", "||=", "_render", "(", "object", ",", "fields", ",", "view", ",", "context", ":", "context", ")", "else", "_render", "(", "object", ",", "fields", ",", "view", ",", "context", ":", "context", ")", "end", "rescue", "SystemStackError", "raise", "CircularRenderingError", ".", "new", "(", "object", ",", "context", ")", "end" ]
Renders an object using a given list of fields. @param [Object] object the object to render @param [Hash] fields the correct set of fields, as from FieldExpander
[ "Renders", "an", "object", "using", "a", "given", "list", "of", "fields", "." ]
57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c
https://github.com/praxis/praxis-blueprints/blob/57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c/lib/praxis-blueprints/renderer.rb#L42-L56
5,696
ohler55/opee
lib/opee/log.rb
Opee.Log.log
def log(severity, message, tid) now = Time.now ss = ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'][severity] ss = '' if ss.nil? if @formatter.nil? msg = "#{ss[0]}, [#{now.strftime('%Y-%m-%dT%H:%M:%S.%6N')} ##{tid}] #{ss} -- : #{message}\n" else msg = @formatter.call(ss, now, tid, message) end @logger.add(severity, msg) @forward.log(severity, message, tid) unless @forward.nil? end
ruby
def log(severity, message, tid) now = Time.now ss = ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'][severity] ss = '' if ss.nil? if @formatter.nil? msg = "#{ss[0]}, [#{now.strftime('%Y-%m-%dT%H:%M:%S.%6N')} ##{tid}] #{ss} -- : #{message}\n" else msg = @formatter.call(ss, now, tid, message) end @logger.add(severity, msg) @forward.log(severity, message, tid) unless @forward.nil? end
[ "def", "log", "(", "severity", ",", "message", ",", "tid", ")", "now", "=", "Time", ".", "now", "ss", "=", "[", "'DEBUG'", ",", "'INFO'", ",", "'WARN'", ",", "'ERROR'", ",", "'FATAL'", "]", "[", "severity", "]", "ss", "=", "''", "if", "ss", ".", "nil?", "if", "@formatter", ".", "nil?", "msg", "=", "\"#{ss[0]}, [#{now.strftime('%Y-%m-%dT%H:%M:%S.%6N')} ##{tid}] #{ss} -- : #{message}\\n\"", "else", "msg", "=", "@formatter", ".", "call", "(", "ss", ",", "now", ",", "tid", ",", "message", ")", "end", "@logger", ".", "add", "(", "severity", ",", "msg", ")", "@forward", ".", "log", "(", "severity", ",", "message", ",", "tid", ")", "unless", "@forward", ".", "nil?", "end" ]
Writes a message if the severity is high enough. This method is executed asynchronously. @param [Fixnum] severity one of the Logger levels @param [String] message string to log @param [Fixnum|String] tid thread id of the thread generating the message
[ "Writes", "a", "message", "if", "the", "severity", "is", "high", "enough", ".", "This", "method", "is", "executed", "asynchronously", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/log.rb#L69-L80
5,697
ohler55/opee
lib/opee/log.rb
Opee.Log.stream=
def stream=(stream) logger = Logger.new(stream) logger.level = @logger.level logger.formatter = @logger.formatter @logger = logger end
ruby
def stream=(stream) logger = Logger.new(stream) logger.level = @logger.level logger.formatter = @logger.formatter @logger = logger end
[ "def", "stream", "=", "(", "stream", ")", "logger", "=", "Logger", ".", "new", "(", "stream", ")", "logger", ".", "level", "=", "@logger", ".", "level", "logger", ".", "formatter", "=", "@logger", ".", "formatter", "@logger", "=", "logger", "end" ]
Sets the logger to use the stream specified. This method is executed asynchronously. @param [IO] stream stream to write log messages to
[ "Sets", "the", "logger", "to", "use", "the", "stream", "specified", ".", "This", "method", "is", "executed", "asynchronously", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/log.rb#L85-L90
5,698
ohler55/opee
lib/opee/log.rb
Opee.Log.set_filename
def set_filename(filename, shift_age=7, shift_size=1048576) logger = Logger.new(filename, shift_age, shift_size) logger.level = @logger.level logger.formatter = @logger.formatter @logger = logger end
ruby
def set_filename(filename, shift_age=7, shift_size=1048576) logger = Logger.new(filename, shift_age, shift_size) logger.level = @logger.level logger.formatter = @logger.formatter @logger = logger end
[ "def", "set_filename", "(", "filename", ",", "shift_age", "=", "7", ",", "shift_size", "=", "1048576", ")", "logger", "=", "Logger", ".", "new", "(", "filename", ",", "shift_age", ",", "shift_size", ")", "logger", ".", "level", "=", "@logger", ".", "level", "logger", ".", "formatter", "=", "@logger", ".", "formatter", "@logger", "=", "logger", "end" ]
Creates a new Logger to write log messages to using the parameters specified. This method is executed asynchronously. @param [String] filename filename of active log file @param [Fixmun] shift_age maximum number of archive files to save @param [Fixmun] shift_size maximum file size
[ "Creates", "a", "new", "Logger", "to", "write", "log", "messages", "to", "using", "the", "parameters", "specified", ".", "This", "method", "is", "executed", "asynchronously", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/log.rb#L97-L102
5,699
ohler55/opee
lib/opee/log.rb
Opee.Log.severity=
def severity=(level) if level.is_a?(String) severity = { 'FATAL' => Logger::Severity::FATAL, 'ERROR' => Logger::Severity::ERROR, 'WARN' => Logger::Severity::WARN, 'INFO' => Logger::Severity::INFO, 'DEBUG' => Logger::Severity::DEBUG, '4' => Logger::Severity::FATAL, '3' => Logger::Severity::ERROR, '2' => Logger::Severity::WARN, '1' => Logger::Severity::INFO, '0' => Logger::Severity::DEBUG }[level.upcase()] raise "#{level} is not a severity" if severity.nil? level = severity elsif level < Logger::Severity::DEBUG || Logger::Severity::FATAL < level raise "#{level} is not a severity" end @logger.level = level end
ruby
def severity=(level) if level.is_a?(String) severity = { 'FATAL' => Logger::Severity::FATAL, 'ERROR' => Logger::Severity::ERROR, 'WARN' => Logger::Severity::WARN, 'INFO' => Logger::Severity::INFO, 'DEBUG' => Logger::Severity::DEBUG, '4' => Logger::Severity::FATAL, '3' => Logger::Severity::ERROR, '2' => Logger::Severity::WARN, '1' => Logger::Severity::INFO, '0' => Logger::Severity::DEBUG }[level.upcase()] raise "#{level} is not a severity" if severity.nil? level = severity elsif level < Logger::Severity::DEBUG || Logger::Severity::FATAL < level raise "#{level} is not a severity" end @logger.level = level end
[ "def", "severity", "=", "(", "level", ")", "if", "level", ".", "is_a?", "(", "String", ")", "severity", "=", "{", "'FATAL'", "=>", "Logger", "::", "Severity", "::", "FATAL", ",", "'ERROR'", "=>", "Logger", "::", "Severity", "::", "ERROR", ",", "'WARN'", "=>", "Logger", "::", "Severity", "::", "WARN", ",", "'INFO'", "=>", "Logger", "::", "Severity", "::", "INFO", ",", "'DEBUG'", "=>", "Logger", "::", "Severity", "::", "DEBUG", ",", "'4'", "=>", "Logger", "::", "Severity", "::", "FATAL", ",", "'3'", "=>", "Logger", "::", "Severity", "::", "ERROR", ",", "'2'", "=>", "Logger", "::", "Severity", "::", "WARN", ",", "'1'", "=>", "Logger", "::", "Severity", "::", "INFO", ",", "'0'", "=>", "Logger", "::", "Severity", "::", "DEBUG", "}", "[", "level", ".", "upcase", "(", ")", "]", "raise", "\"#{level} is not a severity\"", "if", "severity", ".", "nil?", "level", "=", "severity", "elsif", "level", "<", "Logger", "::", "Severity", "::", "DEBUG", "||", "Logger", "::", "Severity", "::", "FATAL", "<", "level", "raise", "\"#{level} is not a severity\"", "end", "@logger", ".", "level", "=", "level", "end" ]
Sets the severity level of the logger. This method is executed asynchronously. @param [String|Fixnum] level value to set the severity to
[ "Sets", "the", "severity", "level", "of", "the", "logger", ".", "This", "method", "is", "executed", "asynchronously", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/log.rb#L121-L141