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
|
---|---|---|---|---|---|---|---|---|---|---|---|
3,600 | josephholsten/rets4r | lib/rets4r/client.rb | RETS4R.Client.get_object | def get_object(resource, type, id, location = false) #:yields: data_object
header = {
'Accept' => mimemap.keys.join(',')
}
data = {
'Resource' => resource,
'Type' => type,
'ID' => id,
'Location' => location ? '1' : '0'
}
response = request(@urls.objects, data, header)
results = block_given? ? 0 : []
if response['content-type'] && response['content-type'].include?('text/xml')
# This probably means that there was an error.
# Response parser will likely raise an exception.
# TODO: test this
rr = ResponseDocument.safe_parse(response.body).validate!.to_transaction
return rr
elsif response['content-type'] && response['content-type'].include?('multipart/parallel')
content_type = process_content_type(response['content-type'])
# TODO: log this
# puts "SPLIT ON #{content_type['boundary']}"
boundary = content_type['boundary']
if boundary =~ /\s*'([^']*)\s*/
boundary = $1
end
parts = response.body.split("\r\n--#{boundary}")
parts.shift # Get rid of the initial boundary
# TODO: log this
# puts "GOT PARTS #{parts.length}"
parts.each do |part|
(raw_header, raw_data) = part.split("\r\n\r\n")
# TODO: log this
# puts raw_data.nil?
next unless raw_data
data_header = process_header(raw_header)
data_object = DataObject.new(data_header, raw_data)
if block_given?
yield data_object
results += 1
else
results << data_object
end
end
else
info = {
'content-type' => response['content-type'], # Compatibility shim. Deprecated.
'Content-Type' => response['content-type'],
'Object-ID' => response['Object-ID'],
'Content-ID' => response['Content-ID']
}
if response['Transfer-Encoding'].to_s.downcase == "chunked" || response['Content-Length'].to_i > 100 then
data_object = DataObject.new(info, response.body)
if block_given?
yield data_object
results += 1
else
results << data_object
end
end
end
results
end | ruby | def get_object(resource, type, id, location = false) #:yields: data_object
header = {
'Accept' => mimemap.keys.join(',')
}
data = {
'Resource' => resource,
'Type' => type,
'ID' => id,
'Location' => location ? '1' : '0'
}
response = request(@urls.objects, data, header)
results = block_given? ? 0 : []
if response['content-type'] && response['content-type'].include?('text/xml')
# This probably means that there was an error.
# Response parser will likely raise an exception.
# TODO: test this
rr = ResponseDocument.safe_parse(response.body).validate!.to_transaction
return rr
elsif response['content-type'] && response['content-type'].include?('multipart/parallel')
content_type = process_content_type(response['content-type'])
# TODO: log this
# puts "SPLIT ON #{content_type['boundary']}"
boundary = content_type['boundary']
if boundary =~ /\s*'([^']*)\s*/
boundary = $1
end
parts = response.body.split("\r\n--#{boundary}")
parts.shift # Get rid of the initial boundary
# TODO: log this
# puts "GOT PARTS #{parts.length}"
parts.each do |part|
(raw_header, raw_data) = part.split("\r\n\r\n")
# TODO: log this
# puts raw_data.nil?
next unless raw_data
data_header = process_header(raw_header)
data_object = DataObject.new(data_header, raw_data)
if block_given?
yield data_object
results += 1
else
results << data_object
end
end
else
info = {
'content-type' => response['content-type'], # Compatibility shim. Deprecated.
'Content-Type' => response['content-type'],
'Object-ID' => response['Object-ID'],
'Content-ID' => response['Content-ID']
}
if response['Transfer-Encoding'].to_s.downcase == "chunked" || response['Content-Length'].to_i > 100 then
data_object = DataObject.new(info, response.body)
if block_given?
yield data_object
results += 1
else
results << data_object
end
end
end
results
end | [
"def",
"get_object",
"(",
"resource",
",",
"type",
",",
"id",
",",
"location",
"=",
"false",
")",
"#:yields: data_object",
"header",
"=",
"{",
"'Accept'",
"=>",
"mimemap",
".",
"keys",
".",
"join",
"(",
"','",
")",
"}",
"data",
"=",
"{",
"'Resource'",
"=>",
"resource",
",",
"'Type'",
"=>",
"type",
",",
"'ID'",
"=>",
"id",
",",
"'Location'",
"=>",
"location",
"?",
"'1'",
":",
"'0'",
"}",
"response",
"=",
"request",
"(",
"@urls",
".",
"objects",
",",
"data",
",",
"header",
")",
"results",
"=",
"block_given?",
"?",
"0",
":",
"[",
"]",
"if",
"response",
"[",
"'content-type'",
"]",
"&&",
"response",
"[",
"'content-type'",
"]",
".",
"include?",
"(",
"'text/xml'",
")",
"# This probably means that there was an error.",
"# Response parser will likely raise an exception.",
"# TODO: test this",
"rr",
"=",
"ResponseDocument",
".",
"safe_parse",
"(",
"response",
".",
"body",
")",
".",
"validate!",
".",
"to_transaction",
"return",
"rr",
"elsif",
"response",
"[",
"'content-type'",
"]",
"&&",
"response",
"[",
"'content-type'",
"]",
".",
"include?",
"(",
"'multipart/parallel'",
")",
"content_type",
"=",
"process_content_type",
"(",
"response",
"[",
"'content-type'",
"]",
")",
"# TODO: log this",
"# puts \"SPLIT ON #{content_type['boundary']}\"",
"boundary",
"=",
"content_type",
"[",
"'boundary'",
"]",
"if",
"boundary",
"=~",
"/",
"\\s",
"\\s",
"/",
"boundary",
"=",
"$1",
"end",
"parts",
"=",
"response",
".",
"body",
".",
"split",
"(",
"\"\\r\\n--#{boundary}\"",
")",
"parts",
".",
"shift",
"# Get rid of the initial boundary",
"# TODO: log this",
"# puts \"GOT PARTS #{parts.length}\"",
"parts",
".",
"each",
"do",
"|",
"part",
"|",
"(",
"raw_header",
",",
"raw_data",
")",
"=",
"part",
".",
"split",
"(",
"\"\\r\\n\\r\\n\"",
")",
"# TODO: log this",
"# puts raw_data.nil?",
"next",
"unless",
"raw_data",
"data_header",
"=",
"process_header",
"(",
"raw_header",
")",
"data_object",
"=",
"DataObject",
".",
"new",
"(",
"data_header",
",",
"raw_data",
")",
"if",
"block_given?",
"yield",
"data_object",
"results",
"+=",
"1",
"else",
"results",
"<<",
"data_object",
"end",
"end",
"else",
"info",
"=",
"{",
"'content-type'",
"=>",
"response",
"[",
"'content-type'",
"]",
",",
"# Compatibility shim. Deprecated.",
"'Content-Type'",
"=>",
"response",
"[",
"'content-type'",
"]",
",",
"'Object-ID'",
"=>",
"response",
"[",
"'Object-ID'",
"]",
",",
"'Content-ID'",
"=>",
"response",
"[",
"'Content-ID'",
"]",
"}",
"if",
"response",
"[",
"'Transfer-Encoding'",
"]",
".",
"to_s",
".",
"downcase",
"==",
"\"chunked\"",
"||",
"response",
"[",
"'Content-Length'",
"]",
".",
"to_i",
">",
"100",
"then",
"data_object",
"=",
"DataObject",
".",
"new",
"(",
"info",
",",
"response",
".",
"body",
")",
"if",
"block_given?",
"yield",
"data_object",
"results",
"+=",
"1",
"else",
"results",
"<<",
"data_object",
"end",
"end",
"end",
"results",
"end"
] | Performs a GetObject transaction on the server. For details on the arguments, please see
the RETS specification on GetObject requests.
This method either returns an Array of DataObject instances, or yields each DataObject
as it is created. If a block is given, the number of objects yielded is returned.
TODO: how much of this could we move over to WEBrick::HTTPRequest#parse? | [
"Performs",
"a",
"GetObject",
"transaction",
"on",
"the",
"server",
".",
"For",
"details",
"on",
"the",
"arguments",
"please",
"see",
"the",
"RETS",
"specification",
"on",
"GetObject",
"requests",
"."
] | ced066582823d2d0cdd2012d36a6898dbe9edb85 | https://github.com/josephholsten/rets4r/blob/ced066582823d2d0cdd2012d36a6898dbe9edb85/lib/rets4r/client.rb#L267-L341 |
3,601 | josephholsten/rets4r | lib/rets4r/client.rb | RETS4R.Client.search | def search(search_type, klass, query, options = false)
header = {}
# Required Data
data = {
'SearchType' => search_type,
'Class' => klass,
'Query' => query,
'QueryType' => 'DMQL2',
'Format' => format,
'Count' => '0'
}
# Options
#--
# We might want to switch this to merge!, but I've kept it like this for now because it
# explicitly casts each value as a string prior to performing the search, so we find out now
# if can't force a value into the string context. I suppose it doesn't really matter when
# that happens, though...
#++
options.each { |k,v| data[k] = v.to_s } if options
response = request(@urls.search, data, header)
# TODO: make parser configurable
results = RETS4R::Client::CompactNokogiriParser.new(response.body)
if block_given?
results.each {|result| yield result}
else
return results.to_a
end
end | ruby | def search(search_type, klass, query, options = false)
header = {}
# Required Data
data = {
'SearchType' => search_type,
'Class' => klass,
'Query' => query,
'QueryType' => 'DMQL2',
'Format' => format,
'Count' => '0'
}
# Options
#--
# We might want to switch this to merge!, but I've kept it like this for now because it
# explicitly casts each value as a string prior to performing the search, so we find out now
# if can't force a value into the string context. I suppose it doesn't really matter when
# that happens, though...
#++
options.each { |k,v| data[k] = v.to_s } if options
response = request(@urls.search, data, header)
# TODO: make parser configurable
results = RETS4R::Client::CompactNokogiriParser.new(response.body)
if block_given?
results.each {|result| yield result}
else
return results.to_a
end
end | [
"def",
"search",
"(",
"search_type",
",",
"klass",
",",
"query",
",",
"options",
"=",
"false",
")",
"header",
"=",
"{",
"}",
"# Required Data",
"data",
"=",
"{",
"'SearchType'",
"=>",
"search_type",
",",
"'Class'",
"=>",
"klass",
",",
"'Query'",
"=>",
"query",
",",
"'QueryType'",
"=>",
"'DMQL2'",
",",
"'Format'",
"=>",
"format",
",",
"'Count'",
"=>",
"'0'",
"}",
"# Options",
"#--",
"# We might want to switch this to merge!, but I've kept it like this for now because it",
"# explicitly casts each value as a string prior to performing the search, so we find out now",
"# if can't force a value into the string context. I suppose it doesn't really matter when",
"# that happens, though...",
"#++",
"options",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"data",
"[",
"k",
"]",
"=",
"v",
".",
"to_s",
"}",
"if",
"options",
"response",
"=",
"request",
"(",
"@urls",
".",
"search",
",",
"data",
",",
"header",
")",
"# TODO: make parser configurable",
"results",
"=",
"RETS4R",
"::",
"Client",
"::",
"CompactNokogiriParser",
".",
"new",
"(",
"response",
".",
"body",
")",
"if",
"block_given?",
"results",
".",
"each",
"{",
"|",
"result",
"|",
"yield",
"result",
"}",
"else",
"return",
"results",
".",
"to_a",
"end",
"end"
] | Peforms a RETS search transaction. Again, please see the RETS specification for details
on what these parameters mean. The options parameter takes a hash of options that will
added to the search statement. | [
"Peforms",
"a",
"RETS",
"search",
"transaction",
".",
"Again",
"please",
"see",
"the",
"RETS",
"specification",
"for",
"details",
"on",
"what",
"these",
"parameters",
"mean",
".",
"The",
"options",
"parameter",
"takes",
"a",
"hash",
"of",
"options",
"that",
"will",
"added",
"to",
"the",
"search",
"statement",
"."
] | ced066582823d2d0cdd2012d36a6898dbe9edb85 | https://github.com/josephholsten/rets4r/blob/ced066582823d2d0cdd2012d36a6898dbe9edb85/lib/rets4r/client.rb#L346-L378 |
3,602 | phatblat/xcode-installer | lib/xcode-installer/install.rb | XcodeInstaller.Install.cp_r | def cp_r(src, dest, options = {})
# fu_check_options options, OPT_TABLE['cp_r']
# fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
options = options.dup
options[:dereference_root] = true unless options.key?(:dereference_root)
fu_each_src_dest(src, dest) do |s, d|
copy_entry s, d, options[:preserve], options[:dereference_root], options[:remove_destination]
end
end | ruby | def cp_r(src, dest, options = {})
# fu_check_options options, OPT_TABLE['cp_r']
# fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
options = options.dup
options[:dereference_root] = true unless options.key?(:dereference_root)
fu_each_src_dest(src, dest) do |s, d|
copy_entry s, d, options[:preserve], options[:dereference_root], options[:remove_destination]
end
end | [
"def",
"cp_r",
"(",
"src",
",",
"dest",
",",
"options",
"=",
"{",
"}",
")",
"# fu_check_options options, OPT_TABLE['cp_r']",
"# fu_output_message \"cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}\" if options[:verbose]",
"return",
"if",
"options",
"[",
":noop",
"]",
"options",
"=",
"options",
".",
"dup",
"options",
"[",
":dereference_root",
"]",
"=",
"true",
"unless",
"options",
".",
"key?",
"(",
":dereference_root",
")",
"fu_each_src_dest",
"(",
"src",
",",
"dest",
")",
"do",
"|",
"s",
",",
"d",
"|",
"copy_entry",
"s",
",",
"d",
",",
"options",
"[",
":preserve",
"]",
",",
"options",
"[",
":dereference_root",
"]",
",",
"options",
"[",
":remove_destination",
"]",
"end",
"end"
] | The following code was copied out of fileutils.rb from ruby 1.9.3-p392 | [
"The",
"following",
"code",
"was",
"copied",
"out",
"of",
"fileutils",
".",
"rb",
"from",
"ruby",
"1",
".",
"9",
".",
"3",
"-",
"p392"
] | f59aebb0fe14d4a2d2eda668dca368fc1f9f9020 | https://github.com/phatblat/xcode-installer/blob/f59aebb0fe14d4a2d2eda668dca368fc1f9f9020/lib/xcode-installer/install.rb#L103-L112 |
3,603 | cblavier/jobbr | lib/jobbr/ohm.rb | Jobbr.Ohm.models | def models(parent = nil)
model_paths = Dir["#{Rails.root}/app/models/*_jobs/*.rb"]
model_paths.each{ |path| require path }
sanitized_model_paths = model_paths.map { |path| path.gsub(/.*\/app\/models\//, '').gsub('.rb', '') }
model_constants = sanitized_model_paths.map do |path|
path.split('/').map { |token| token.camelize }.join('::').constantize
end
model_constants.select { |model| superclasses(model).include?(::Ohm::Model) }
if parent
model_constants.select { |model| model.included_modules.include?(parent) }
else
model_constants
end
end | ruby | def models(parent = nil)
model_paths = Dir["#{Rails.root}/app/models/*_jobs/*.rb"]
model_paths.each{ |path| require path }
sanitized_model_paths = model_paths.map { |path| path.gsub(/.*\/app\/models\//, '').gsub('.rb', '') }
model_constants = sanitized_model_paths.map do |path|
path.split('/').map { |token| token.camelize }.join('::').constantize
end
model_constants.select { |model| superclasses(model).include?(::Ohm::Model) }
if parent
model_constants.select { |model| model.included_modules.include?(parent) }
else
model_constants
end
end | [
"def",
"models",
"(",
"parent",
"=",
"nil",
")",
"model_paths",
"=",
"Dir",
"[",
"\"#{Rails.root}/app/models/*_jobs/*.rb\"",
"]",
"model_paths",
".",
"each",
"{",
"|",
"path",
"|",
"require",
"path",
"}",
"sanitized_model_paths",
"=",
"model_paths",
".",
"map",
"{",
"|",
"path",
"|",
"path",
".",
"gsub",
"(",
"/",
"\\/",
"\\/",
"\\/",
"/",
",",
"''",
")",
".",
"gsub",
"(",
"'.rb'",
",",
"''",
")",
"}",
"model_constants",
"=",
"sanitized_model_paths",
".",
"map",
"do",
"|",
"path",
"|",
"path",
".",
"split",
"(",
"'/'",
")",
".",
"map",
"{",
"|",
"token",
"|",
"token",
".",
"camelize",
"}",
".",
"join",
"(",
"'::'",
")",
".",
"constantize",
"end",
"model_constants",
".",
"select",
"{",
"|",
"model",
"|",
"superclasses",
"(",
"model",
")",
".",
"include?",
"(",
"::",
"Ohm",
"::",
"Model",
")",
"}",
"if",
"parent",
"model_constants",
".",
"select",
"{",
"|",
"model",
"|",
"model",
".",
"included_modules",
".",
"include?",
"(",
"parent",
")",
"}",
"else",
"model_constants",
"end",
"end"
] | Return all Ohm models.
You can also pass a module class to get all models including that module | [
"Return",
"all",
"Ohm",
"models",
".",
"You",
"can",
"also",
"pass",
"a",
"module",
"class",
"to",
"get",
"all",
"models",
"including",
"that",
"module"
] | 2fbfa14f5fe1b942e69333e34ea0a086ad052b38 | https://github.com/cblavier/jobbr/blob/2fbfa14f5fe1b942e69333e34ea0a086ad052b38/lib/jobbr/ohm.rb#L11-L25 |
3,604 | cblavier/jobbr | lib/jobbr/ohm.rb | Jobbr.Ohm.superclasses | def superclasses(klass)
super_classes = []
while klass != Object
klass = klass.superclass
super_classes << klass
end
super_classes
end | ruby | def superclasses(klass)
super_classes = []
while klass != Object
klass = klass.superclass
super_classes << klass
end
super_classes
end | [
"def",
"superclasses",
"(",
"klass",
")",
"super_classes",
"=",
"[",
"]",
"while",
"klass",
"!=",
"Object",
"klass",
"=",
"klass",
".",
"superclass",
"super_classes",
"<<",
"klass",
"end",
"super_classes",
"end"
] | Return all superclasses for a given class. | [
"Return",
"all",
"superclasses",
"for",
"a",
"given",
"class",
"."
] | 2fbfa14f5fe1b942e69333e34ea0a086ad052b38 | https://github.com/cblavier/jobbr/blob/2fbfa14f5fe1b942e69333e34ea0a086ad052b38/lib/jobbr/ohm.rb#L30-L37 |
3,605 | blackwinter/wadl | lib/wadl/has_docs.rb | WADL.HasDocs.define_singleton | def define_singleton(r, sym, method)
name = r.send(sym)
if name && name !~ /\W/ && !r.respond_to?(name) && !respond_to?(name)
instance_eval(%Q{def #{name}\n#{method}('#{name}')\nend})
end
end | ruby | def define_singleton(r, sym, method)
name = r.send(sym)
if name && name !~ /\W/ && !r.respond_to?(name) && !respond_to?(name)
instance_eval(%Q{def #{name}\n#{method}('#{name}')\nend})
end
end | [
"def",
"define_singleton",
"(",
"r",
",",
"sym",
",",
"method",
")",
"name",
"=",
"r",
".",
"send",
"(",
"sym",
")",
"if",
"name",
"&&",
"name",
"!~",
"/",
"\\W",
"/",
"&&",
"!",
"r",
".",
"respond_to?",
"(",
"name",
")",
"&&",
"!",
"respond_to?",
"(",
"name",
")",
"instance_eval",
"(",
"%Q{def #{name}\\n#{method}('#{name}')\\nend}",
")",
"end",
"end"
] | Convenience method to define a no-argument singleton method on
this object. | [
"Convenience",
"method",
"to",
"define",
"a",
"no",
"-",
"argument",
"singleton",
"method",
"on",
"this",
"object",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/has_docs.rb#L37-L43 |
3,606 | pwnall/webkit_remote | lib/webkit_remote/process.rb | WebkitRemote.Process.start | def start
return self if running?
unless @pid = ::Process.spawn(*@cli)
# The launch failed.
stop
return nil
end
(@timeout * 20).times do
# Check if the browser exited.
begin
break if ::Process.wait(@pid, ::Process::WNOHANG)
rescue SystemCallError # no children
break
end
# Check if the browser finished starting up.
begin
browser = WebkitRemote::Browser.new process: self
@running = true
return browser
rescue SystemCallError # most likely ECONNREFUSED
Kernel.sleep 0.05
end
end
# The browser failed, or was too slow to start.
stop
nil
end | ruby | def start
return self if running?
unless @pid = ::Process.spawn(*@cli)
# The launch failed.
stop
return nil
end
(@timeout * 20).times do
# Check if the browser exited.
begin
break if ::Process.wait(@pid, ::Process::WNOHANG)
rescue SystemCallError # no children
break
end
# Check if the browser finished starting up.
begin
browser = WebkitRemote::Browser.new process: self
@running = true
return browser
rescue SystemCallError # most likely ECONNREFUSED
Kernel.sleep 0.05
end
end
# The browser failed, or was too slow to start.
stop
nil
end | [
"def",
"start",
"return",
"self",
"if",
"running?",
"unless",
"@pid",
"=",
"::",
"Process",
".",
"spawn",
"(",
"@cli",
")",
"# The launch failed.",
"stop",
"return",
"nil",
"end",
"(",
"@timeout",
"*",
"20",
")",
".",
"times",
"do",
"# Check if the browser exited.",
"begin",
"break",
"if",
"::",
"Process",
".",
"wait",
"(",
"@pid",
",",
"::",
"Process",
"::",
"WNOHANG",
")",
"rescue",
"SystemCallError",
"# no children",
"break",
"end",
"# Check if the browser finished starting up.",
"begin",
"browser",
"=",
"WebkitRemote",
"::",
"Browser",
".",
"new",
"process",
":",
"self",
"@running",
"=",
"true",
"return",
"browser",
"rescue",
"SystemCallError",
"# most likely ECONNREFUSED",
"Kernel",
".",
"sleep",
"0.05",
"end",
"end",
"# The browser failed, or was too slow to start.",
"stop",
"nil",
"end"
] | Tracker for a yet-unlaunched process.
@param [Hash] opts tweak the options below
@option opts [Integer] port the port used by the remote debugging server;
the default port is 9292
@option opts [Number] timeout number of seconds to wait for the browser
to start; the default timeout is 10 seconds
@option opts [Hash<Symbol, Number>] window set the :left, :top, :width and
:height of the browser window; by default, the browser window is
256x256 starting at 0,0.
@option opts [Boolean] allow_popups when true, the popup blocker is
disabled; this is sometimes necessary when driving a Web UI via
JavaScript
@option opts [Boolean] headless if true, Chrome runs without any dependency
on a display server
@option opts [String] chrome_binary path to the Chrome binary to be used;
by default, the path is automatically detected
Starts the browser process.
@return [WebkitRemote::Browser] master session to the started Browser
process; the session's auto_close is set to false so that it can be
safely discarded; nil if the launch fails | [
"Tracker",
"for",
"a",
"yet",
"-",
"unlaunched",
"process",
"."
] | f38ac7e882726ff00e5c56898d06d91340f8179e | https://github.com/pwnall/webkit_remote/blob/f38ac7e882726ff00e5c56898d06d91340f8179e/lib/webkit_remote/process.rb#L49-L78 |
3,607 | pwnall/webkit_remote | lib/webkit_remote/process.rb | WebkitRemote.Process.stop | def stop
return self unless running?
if @pid
begin
::Process.kill 'TERM', @pid
::Process.wait @pid
rescue SystemCallError
# Process died on its own.
ensure
@pid = nil
end
end
FileUtils.rm_rf @data_dir if File.exist?(@data_dir)
@running = false
self
end | ruby | def stop
return self unless running?
if @pid
begin
::Process.kill 'TERM', @pid
::Process.wait @pid
rescue SystemCallError
# Process died on its own.
ensure
@pid = nil
end
end
FileUtils.rm_rf @data_dir if File.exist?(@data_dir)
@running = false
self
end | [
"def",
"stop",
"return",
"self",
"unless",
"running?",
"if",
"@pid",
"begin",
"::",
"Process",
".",
"kill",
"'TERM'",
",",
"@pid",
"::",
"Process",
".",
"wait",
"@pid",
"rescue",
"SystemCallError",
"# Process died on its own.",
"ensure",
"@pid",
"=",
"nil",
"end",
"end",
"FileUtils",
".",
"rm_rf",
"@data_dir",
"if",
"File",
".",
"exist?",
"(",
"@data_dir",
")",
"@running",
"=",
"false",
"self",
"end"
] | Stops the browser process.
Only call this after you're done with the process.
@return [WebkitRemote::Process] self | [
"Stops",
"the",
"browser",
"process",
"."
] | f38ac7e882726ff00e5c56898d06d91340f8179e | https://github.com/pwnall/webkit_remote/blob/f38ac7e882726ff00e5c56898d06d91340f8179e/lib/webkit_remote/process.rb#L89-L105 |
3,608 | blackwinter/wadl | lib/wadl/response_format.rb | WADL.ResponseFormat.build | def build(http_response)
# Figure out which fault or representation to use.
status = http_response.status[0]
unless response_format = faults.find { |f| f.dereference.status == status }
# Try to match the response to a response format using a media
# type.
response_media_type = http_response.content_type
response_format = representations.find { |f|
t = f.dereference.mediaType and response_media_type.index(t) == 0
}
# If an exact media type match fails, use the mime-types gem to
# match the response to a response format using the underlying
# subtype. This will match "application/xml" with "text/xml".
response_format ||= begin
mime_type = MIME::Types[response_media_type]
raw_sub_type = mime_type[0].raw_sub_type if mime_type && !mime_type.empty?
representations.find { |f|
if t = f.dereference.mediaType
response_mime_type = MIME::Types[t]
response_raw_sub_type = response_mime_type[0].raw_sub_type if response_mime_type && !response_mime_type.empty?
response_raw_sub_type == raw_sub_type
end
}
end
# If all else fails, try to find a response that specifies no
# media type. TODO: check if this would be valid WADL.
response_format ||= representations.find { |f| !f.dereference.mediaType }
end
body = http_response.read
if response_format && response_format.mediaType =~ /xml/
begin
body = REXML::Document.new(body)
# Find the appropriate element of the document
if response_format.element
# TODO: don't strip the damn namespace. I'm not very good at
# namespaces and I don't see how to deal with them here.
element = response_format.element.sub(/.*:/, '')
body = REXML::XPath.first(body, "//#{element}")
end
rescue REXML::ParseException
end
body.extend(XMLRepresentation)
body.representation_of(response_format)
end
klass = response_format.is_a?(FaultFormat) ? response_format.subclass : Response
obj = klass.new(http_response.status, http_response.headers, body, response_format)
obj.is_a?(Exception) ? raise(obj) : obj
end | ruby | def build(http_response)
# Figure out which fault or representation to use.
status = http_response.status[0]
unless response_format = faults.find { |f| f.dereference.status == status }
# Try to match the response to a response format using a media
# type.
response_media_type = http_response.content_type
response_format = representations.find { |f|
t = f.dereference.mediaType and response_media_type.index(t) == 0
}
# If an exact media type match fails, use the mime-types gem to
# match the response to a response format using the underlying
# subtype. This will match "application/xml" with "text/xml".
response_format ||= begin
mime_type = MIME::Types[response_media_type]
raw_sub_type = mime_type[0].raw_sub_type if mime_type && !mime_type.empty?
representations.find { |f|
if t = f.dereference.mediaType
response_mime_type = MIME::Types[t]
response_raw_sub_type = response_mime_type[0].raw_sub_type if response_mime_type && !response_mime_type.empty?
response_raw_sub_type == raw_sub_type
end
}
end
# If all else fails, try to find a response that specifies no
# media type. TODO: check if this would be valid WADL.
response_format ||= representations.find { |f| !f.dereference.mediaType }
end
body = http_response.read
if response_format && response_format.mediaType =~ /xml/
begin
body = REXML::Document.new(body)
# Find the appropriate element of the document
if response_format.element
# TODO: don't strip the damn namespace. I'm not very good at
# namespaces and I don't see how to deal with them here.
element = response_format.element.sub(/.*:/, '')
body = REXML::XPath.first(body, "//#{element}")
end
rescue REXML::ParseException
end
body.extend(XMLRepresentation)
body.representation_of(response_format)
end
klass = response_format.is_a?(FaultFormat) ? response_format.subclass : Response
obj = klass.new(http_response.status, http_response.headers, body, response_format)
obj.is_a?(Exception) ? raise(obj) : obj
end | [
"def",
"build",
"(",
"http_response",
")",
"# Figure out which fault or representation to use.",
"status",
"=",
"http_response",
".",
"status",
"[",
"0",
"]",
"unless",
"response_format",
"=",
"faults",
".",
"find",
"{",
"|",
"f",
"|",
"f",
".",
"dereference",
".",
"status",
"==",
"status",
"}",
"# Try to match the response to a response format using a media",
"# type.",
"response_media_type",
"=",
"http_response",
".",
"content_type",
"response_format",
"=",
"representations",
".",
"find",
"{",
"|",
"f",
"|",
"t",
"=",
"f",
".",
"dereference",
".",
"mediaType",
"and",
"response_media_type",
".",
"index",
"(",
"t",
")",
"==",
"0",
"}",
"# If an exact media type match fails, use the mime-types gem to",
"# match the response to a response format using the underlying",
"# subtype. This will match \"application/xml\" with \"text/xml\".",
"response_format",
"||=",
"begin",
"mime_type",
"=",
"MIME",
"::",
"Types",
"[",
"response_media_type",
"]",
"raw_sub_type",
"=",
"mime_type",
"[",
"0",
"]",
".",
"raw_sub_type",
"if",
"mime_type",
"&&",
"!",
"mime_type",
".",
"empty?",
"representations",
".",
"find",
"{",
"|",
"f",
"|",
"if",
"t",
"=",
"f",
".",
"dereference",
".",
"mediaType",
"response_mime_type",
"=",
"MIME",
"::",
"Types",
"[",
"t",
"]",
"response_raw_sub_type",
"=",
"response_mime_type",
"[",
"0",
"]",
".",
"raw_sub_type",
"if",
"response_mime_type",
"&&",
"!",
"response_mime_type",
".",
"empty?",
"response_raw_sub_type",
"==",
"raw_sub_type",
"end",
"}",
"end",
"# If all else fails, try to find a response that specifies no",
"# media type. TODO: check if this would be valid WADL.",
"response_format",
"||=",
"representations",
".",
"find",
"{",
"|",
"f",
"|",
"!",
"f",
".",
"dereference",
".",
"mediaType",
"}",
"end",
"body",
"=",
"http_response",
".",
"read",
"if",
"response_format",
"&&",
"response_format",
".",
"mediaType",
"=~",
"/",
"/",
"begin",
"body",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"body",
")",
"# Find the appropriate element of the document",
"if",
"response_format",
".",
"element",
"# TODO: don't strip the damn namespace. I'm not very good at",
"# namespaces and I don't see how to deal with them here.",
"element",
"=",
"response_format",
".",
"element",
".",
"sub",
"(",
"/",
"/",
",",
"''",
")",
"body",
"=",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"body",
",",
"\"//#{element}\"",
")",
"end",
"rescue",
"REXML",
"::",
"ParseException",
"end",
"body",
".",
"extend",
"(",
"XMLRepresentation",
")",
"body",
".",
"representation_of",
"(",
"response_format",
")",
"end",
"klass",
"=",
"response_format",
".",
"is_a?",
"(",
"FaultFormat",
")",
"?",
"response_format",
".",
"subclass",
":",
"Response",
"obj",
"=",
"klass",
".",
"new",
"(",
"http_response",
".",
"status",
",",
"http_response",
".",
"headers",
",",
"body",
",",
"response_format",
")",
"obj",
".",
"is_a?",
"(",
"Exception",
")",
"?",
"raise",
"(",
"obj",
")",
":",
"obj",
"end"
] | Builds a service response object out of an HTTPResponse object. | [
"Builds",
"a",
"service",
"response",
"object",
"out",
"of",
"an",
"HTTPResponse",
"object",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/response_format.rb#L41-L99 |
3,609 | badboy/i3-ipc | lib/i3-ipc.rb | I3.IPC.handle_response | def handle_response(type)
# reads 14 bytes
# length of "i3-ipc" + 4 bytes length + 4 bytes type
buffer = read 14
raise WrongMagicCode unless buffer[0, (MAGIC_STRING.length)] == MAGIC_STRING
len, recv_type = buffer[6..-1].unpack("LL")
raise WrongType unless recv_type == type
answer = read len
::JSON.parse(answer)
end | ruby | def handle_response(type)
# reads 14 bytes
# length of "i3-ipc" + 4 bytes length + 4 bytes type
buffer = read 14
raise WrongMagicCode unless buffer[0, (MAGIC_STRING.length)] == MAGIC_STRING
len, recv_type = buffer[6..-1].unpack("LL")
raise WrongType unless recv_type == type
answer = read len
::JSON.parse(answer)
end | [
"def",
"handle_response",
"(",
"type",
")",
"# reads 14 bytes",
"# length of \"i3-ipc\" + 4 bytes length + 4 bytes type",
"buffer",
"=",
"read",
"14",
"raise",
"WrongMagicCode",
"unless",
"buffer",
"[",
"0",
",",
"(",
"MAGIC_STRING",
".",
"length",
")",
"]",
"==",
"MAGIC_STRING",
"len",
",",
"recv_type",
"=",
"buffer",
"[",
"6",
"..",
"-",
"1",
"]",
".",
"unpack",
"(",
"\"LL\"",
")",
"raise",
"WrongType",
"unless",
"recv_type",
"==",
"type",
"answer",
"=",
"read",
"len",
"::",
"JSON",
".",
"parse",
"(",
"answer",
")",
"end"
] | Reads the reply from the socket
and parses the returned json into a ruby object.
Throws WrongMagicCode when magic word is wrong.
Throws WrongType if returned type does not match expected.
This is a bit duplicated code
but I don't know a way to read the full send reply
without knowing its length | [
"Reads",
"the",
"reply",
"from",
"the",
"socket",
"and",
"parses",
"the",
"returned",
"json",
"into",
"a",
"ruby",
"object",
"."
] | 63b6d25552de4e6025fdcad14502d60140b478c3 | https://github.com/badboy/i3-ipc/blob/63b6d25552de4e6025fdcad14502d60140b478c3/lib/i3-ipc.rb#L110-L121 |
3,610 | blackwinter/wadl | lib/wadl/resource_and_address.rb | WADL.ResourceAndAddress.method_missing | def method_missing(name, *args, &block)
if @resource.respond_to?(name)
result = @resource.send(name, *args, &block)
result.is_a?(Resource) ? ResourceAndAddress.new(result, @address.dup) : result
else
super
end
end | ruby | def method_missing(name, *args, &block)
if @resource.respond_to?(name)
result = @resource.send(name, *args, &block)
result.is_a?(Resource) ? ResourceAndAddress.new(result, @address.dup) : result
else
super
end
end | [
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"@resource",
".",
"respond_to?",
"(",
"name",
")",
"result",
"=",
"@resource",
".",
"send",
"(",
"name",
",",
"args",
",",
"block",
")",
"result",
".",
"is_a?",
"(",
"Resource",
")",
"?",
"ResourceAndAddress",
".",
"new",
"(",
"result",
",",
"@address",
".",
"dup",
")",
":",
"result",
"else",
"super",
"end",
"end"
] | method_missing is to catch generated methods that don't get delegated. | [
"method_missing",
"is",
"to",
"catch",
"generated",
"methods",
"that",
"don",
"t",
"get",
"delegated",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/resource_and_address.rb#L82-L89 |
3,611 | blackwinter/wadl | lib/wadl/resource_and_address.rb | WADL.ResourceAndAddress.resource | def resource(*args, &block)
resource = @resource.resource(*args, &block)
resource && ResourceAndAddress.new(resource, @address)
end | ruby | def resource(*args, &block)
resource = @resource.resource(*args, &block)
resource && ResourceAndAddress.new(resource, @address)
end | [
"def",
"resource",
"(",
"*",
"args",
",",
"&",
"block",
")",
"resource",
"=",
"@resource",
".",
"resource",
"(",
"args",
",",
"block",
")",
"resource",
"&&",
"ResourceAndAddress",
".",
"new",
"(",
"resource",
",",
"@address",
")",
"end"
] | method_missing won't catch these guys because they were defined in
the delegation operation. | [
"method_missing",
"won",
"t",
"catch",
"these",
"guys",
"because",
"they",
"were",
"defined",
"in",
"the",
"delegation",
"operation",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/resource_and_address.rb#L93-L96 |
3,612 | cblavier/jobbr | lib/jobbr/whenever.rb | Jobbr.Whenever.schedule_jobs | def schedule_jobs(job_list)
Jobbr::Ohm.models(Jobbr::Scheduled).each do |job|
if job.every
job_list.every job.every[0], job.every[1] do
job_list.jobbr job.task_name
end
end
end
end | ruby | def schedule_jobs(job_list)
Jobbr::Ohm.models(Jobbr::Scheduled).each do |job|
if job.every
job_list.every job.every[0], job.every[1] do
job_list.jobbr job.task_name
end
end
end
end | [
"def",
"schedule_jobs",
"(",
"job_list",
")",
"Jobbr",
"::",
"Ohm",
".",
"models",
"(",
"Jobbr",
"::",
"Scheduled",
")",
".",
"each",
"do",
"|",
"job",
"|",
"if",
"job",
".",
"every",
"job_list",
".",
"every",
"job",
".",
"every",
"[",
"0",
"]",
",",
"job",
".",
"every",
"[",
"1",
"]",
"do",
"job_list",
".",
"jobbr",
"job",
".",
"task_name",
"end",
"end",
"end",
"end"
] | Generates crontab for each scheduled Job using Whenever DSL. | [
"Generates",
"crontab",
"for",
"each",
"scheduled",
"Job",
"using",
"Whenever",
"DSL",
"."
] | 2fbfa14f5fe1b942e69333e34ea0a086ad052b38 | https://github.com/cblavier/jobbr/blob/2fbfa14f5fe1b942e69333e34ea0a086ad052b38/lib/jobbr/whenever.rb#L10-L18 |
3,613 | galetahub/sunrise | app/helpers/sunrise/activities_helper.rb | Sunrise.ActivitiesHelper.timeago_tag | def timeago_tag(time, options = {})
options[:class] ||= "timeago"
content_tag(:abbr, time.to_s, options.merge(:title => time.getutc.iso8601)) if time
end | ruby | def timeago_tag(time, options = {})
options[:class] ||= "timeago"
content_tag(:abbr, time.to_s, options.merge(:title => time.getutc.iso8601)) if time
end | [
"def",
"timeago_tag",
"(",
"time",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":class",
"]",
"||=",
"\"timeago\"",
"content_tag",
"(",
":abbr",
",",
"time",
".",
"to_s",
",",
"options",
".",
"merge",
"(",
":title",
"=>",
"time",
".",
"getutc",
".",
"iso8601",
")",
")",
"if",
"time",
"end"
] | For generating time tags calculated using jquery.timeago | [
"For",
"generating",
"time",
"tags",
"calculated",
"using",
"jquery",
".",
"timeago"
] | c65a8c6150180ae5569e45c57c1ff2c1092d0ab9 | https://github.com/galetahub/sunrise/blob/c65a8c6150180ae5569e45c57c1ff2c1092d0ab9/app/helpers/sunrise/activities_helper.rb#L5-L8 |
3,614 | galetahub/sunrise | app/helpers/sunrise/activities_helper.rb | Sunrise.ActivitiesHelper.link_to_trackable | def link_to_trackable(object, object_type)
model_name = object_type.downcase
if object
link_to(model_name, edit_path(:model_name => model_name.pluralize, :id => object.id))
else
"a #{model_name} which does not exist anymore"
end
end | ruby | def link_to_trackable(object, object_type)
model_name = object_type.downcase
if object
link_to(model_name, edit_path(:model_name => model_name.pluralize, :id => object.id))
else
"a #{model_name} which does not exist anymore"
end
end | [
"def",
"link_to_trackable",
"(",
"object",
",",
"object_type",
")",
"model_name",
"=",
"object_type",
".",
"downcase",
"if",
"object",
"link_to",
"(",
"model_name",
",",
"edit_path",
"(",
":model_name",
"=>",
"model_name",
".",
"pluralize",
",",
":id",
"=>",
"object",
".",
"id",
")",
")",
"else",
"\"a #{model_name} which does not exist anymore\"",
"end",
"end"
] | Check if object still exists in the database and display a link to it,
otherwise display a proper message about it.
This is used in activities that can refer to
objects which no longer exist, like removed posts. | [
"Check",
"if",
"object",
"still",
"exists",
"in",
"the",
"database",
"and",
"display",
"a",
"link",
"to",
"it",
"otherwise",
"display",
"a",
"proper",
"message",
"about",
"it",
".",
"This",
"is",
"used",
"in",
"activities",
"that",
"can",
"refer",
"to",
"objects",
"which",
"no",
"longer",
"exist",
"like",
"removed",
"posts",
"."
] | c65a8c6150180ae5569e45c57c1ff2c1092d0ab9 | https://github.com/galetahub/sunrise/blob/c65a8c6150180ae5569e45c57c1ff2c1092d0ab9/app/helpers/sunrise/activities_helper.rb#L26-L34 |
3,615 | blackwinter/wadl | lib/wadl/address.rb | WADL.Address.deep_copy | def deep_copy
address = Address.new(
_deep_copy_array(@path_fragments),
_deep_copy_array(@query_vars),
_deep_copy_hash(@headers),
@path_params.dup,
@query_params.dup,
@header_params.dup
)
@auth.each { |header, value| address.auth(header, value) }
address
end | ruby | def deep_copy
address = Address.new(
_deep_copy_array(@path_fragments),
_deep_copy_array(@query_vars),
_deep_copy_hash(@headers),
@path_params.dup,
@query_params.dup,
@header_params.dup
)
@auth.each { |header, value| address.auth(header, value) }
address
end | [
"def",
"deep_copy",
"address",
"=",
"Address",
".",
"new",
"(",
"_deep_copy_array",
"(",
"@path_fragments",
")",
",",
"_deep_copy_array",
"(",
"@query_vars",
")",
",",
"_deep_copy_hash",
"(",
"@headers",
")",
",",
"@path_params",
".",
"dup",
",",
"@query_params",
".",
"dup",
",",
"@header_params",
".",
"dup",
")",
"@auth",
".",
"each",
"{",
"|",
"header",
",",
"value",
"|",
"address",
".",
"auth",
"(",
"header",
",",
"value",
")",
"}",
"address",
"end"
] | Perform a deep copy. | [
"Perform",
"a",
"deep",
"copy",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/address.rb#L56-L69 |
3,616 | blackwinter/wadl | lib/wadl/address.rb | WADL.Address.bind! | def bind!(args = {})
path_var_values = args[:path] || {}
query_var_values = args[:query] || {}
header_var_values = args[:headers] || {}
@auth.each { |header, value| header_var_values[header] = value }.clear
# Bind variables found in the path fragments.
path_params_to_delete = []
path_fragments.each { |fragment|
if fragment.respond_to?(:to_str)
# This fragment is a string which might contain {} substitutions.
# Make any substitutions available to the provided path variables.
self.class.embedded_param_names(fragment).each { |name|
value = path_var_values[name] || path_var_values[name.to_sym]
value = if param = path_params[name]
path_params_to_delete << param
param % value
else
Param.default.format(value, name)
end
fragment.gsub!("{#{name}}", value)
}
else
# This fragment is an array of Param objects (style 'matrix'
# or 'plain') which may be bound to strings. As substitutions
# happen, the array will become a mixed array of Param objects
# and strings.
fragment.each_with_index { |param, i|
next unless param.respond_to?(:name)
name = param.name
value = path_var_values[name] || path_var_values[name.to_sym]
value = param % value
fragment[i] = value if value
path_params_to_delete << param
}
end
}
# Delete any embedded path parameters that are now bound from
# our list of unbound parameters.
path_params_to_delete.each { |p| path_params.delete(p.name) }
# Bind query variable values to query parameters
query_var_values.each { |name, value|
param = query_params.delete(name.to_s)
query_vars << param % value if param
}
# Bind header variables to header parameters
header_var_values.each { |name, value|
if param = header_params.delete(name.to_s)
headers[name] = param % value
else
warn %Q{Ignoring unknown header parameter "#{name}"!}
end
}
self
end | ruby | def bind!(args = {})
path_var_values = args[:path] || {}
query_var_values = args[:query] || {}
header_var_values = args[:headers] || {}
@auth.each { |header, value| header_var_values[header] = value }.clear
# Bind variables found in the path fragments.
path_params_to_delete = []
path_fragments.each { |fragment|
if fragment.respond_to?(:to_str)
# This fragment is a string which might contain {} substitutions.
# Make any substitutions available to the provided path variables.
self.class.embedded_param_names(fragment).each { |name|
value = path_var_values[name] || path_var_values[name.to_sym]
value = if param = path_params[name]
path_params_to_delete << param
param % value
else
Param.default.format(value, name)
end
fragment.gsub!("{#{name}}", value)
}
else
# This fragment is an array of Param objects (style 'matrix'
# or 'plain') which may be bound to strings. As substitutions
# happen, the array will become a mixed array of Param objects
# and strings.
fragment.each_with_index { |param, i|
next unless param.respond_to?(:name)
name = param.name
value = path_var_values[name] || path_var_values[name.to_sym]
value = param % value
fragment[i] = value if value
path_params_to_delete << param
}
end
}
# Delete any embedded path parameters that are now bound from
# our list of unbound parameters.
path_params_to_delete.each { |p| path_params.delete(p.name) }
# Bind query variable values to query parameters
query_var_values.each { |name, value|
param = query_params.delete(name.to_s)
query_vars << param % value if param
}
# Bind header variables to header parameters
header_var_values.each { |name, value|
if param = header_params.delete(name.to_s)
headers[name] = param % value
else
warn %Q{Ignoring unknown header parameter "#{name}"!}
end
}
self
end | [
"def",
"bind!",
"(",
"args",
"=",
"{",
"}",
")",
"path_var_values",
"=",
"args",
"[",
":path",
"]",
"||",
"{",
"}",
"query_var_values",
"=",
"args",
"[",
":query",
"]",
"||",
"{",
"}",
"header_var_values",
"=",
"args",
"[",
":headers",
"]",
"||",
"{",
"}",
"@auth",
".",
"each",
"{",
"|",
"header",
",",
"value",
"|",
"header_var_values",
"[",
"header",
"]",
"=",
"value",
"}",
".",
"clear",
"# Bind variables found in the path fragments.",
"path_params_to_delete",
"=",
"[",
"]",
"path_fragments",
".",
"each",
"{",
"|",
"fragment",
"|",
"if",
"fragment",
".",
"respond_to?",
"(",
":to_str",
")",
"# This fragment is a string which might contain {} substitutions.",
"# Make any substitutions available to the provided path variables.",
"self",
".",
"class",
".",
"embedded_param_names",
"(",
"fragment",
")",
".",
"each",
"{",
"|",
"name",
"|",
"value",
"=",
"path_var_values",
"[",
"name",
"]",
"||",
"path_var_values",
"[",
"name",
".",
"to_sym",
"]",
"value",
"=",
"if",
"param",
"=",
"path_params",
"[",
"name",
"]",
"path_params_to_delete",
"<<",
"param",
"param",
"%",
"value",
"else",
"Param",
".",
"default",
".",
"format",
"(",
"value",
",",
"name",
")",
"end",
"fragment",
".",
"gsub!",
"(",
"\"{#{name}}\"",
",",
"value",
")",
"}",
"else",
"# This fragment is an array of Param objects (style 'matrix'",
"# or 'plain') which may be bound to strings. As substitutions",
"# happen, the array will become a mixed array of Param objects",
"# and strings.",
"fragment",
".",
"each_with_index",
"{",
"|",
"param",
",",
"i",
"|",
"next",
"unless",
"param",
".",
"respond_to?",
"(",
":name",
")",
"name",
"=",
"param",
".",
"name",
"value",
"=",
"path_var_values",
"[",
"name",
"]",
"||",
"path_var_values",
"[",
"name",
".",
"to_sym",
"]",
"value",
"=",
"param",
"%",
"value",
"fragment",
"[",
"i",
"]",
"=",
"value",
"if",
"value",
"path_params_to_delete",
"<<",
"param",
"}",
"end",
"}",
"# Delete any embedded path parameters that are now bound from",
"# our list of unbound parameters.",
"path_params_to_delete",
".",
"each",
"{",
"|",
"p",
"|",
"path_params",
".",
"delete",
"(",
"p",
".",
"name",
")",
"}",
"# Bind query variable values to query parameters",
"query_var_values",
".",
"each",
"{",
"|",
"name",
",",
"value",
"|",
"param",
"=",
"query_params",
".",
"delete",
"(",
"name",
".",
"to_s",
")",
"query_vars",
"<<",
"param",
"%",
"value",
"if",
"param",
"}",
"# Bind header variables to header parameters",
"header_var_values",
".",
"each",
"{",
"|",
"name",
",",
"value",
"|",
"if",
"param",
"=",
"header_params",
".",
"delete",
"(",
"name",
".",
"to_s",
")",
"headers",
"[",
"name",
"]",
"=",
"param",
"%",
"value",
"else",
"warn",
"%Q{Ignoring unknown header parameter \"#{name}\"!}",
"end",
"}",
"self",
"end"
] | Binds some or all of the unbound variables in this address to values. | [
"Binds",
"some",
"or",
"all",
"of",
"the",
"unbound",
"variables",
"in",
"this",
"address",
"to",
"values",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/address.rb#L85-L150 |
3,617 | thomasjachmann/launchpad | lib/launchpad/interaction.rb | Launchpad.Interaction.start | def start(opts = nil)
logger.debug "starting Launchpad::Interaction##{object_id}"
opts = {
:detached => false
}.merge(opts || {})
@active = true
@reader_thread ||= Thread.new do
begin
while @active do
@device.read_pending_actions.each do |action|
action_thread = Thread.new(action) do |action|
respond_to_action(action)
end
@action_threads.add(action_thread)
end
sleep @latency# if @latency > 0.0
end
rescue Portmidi::DeviceError => e
logger.fatal "could not read from device, stopping to read actions"
raise CommunicationError.new(e)
rescue Exception => e
logger.fatal "error causing action reading to stop: #{e.inspect}"
raise e
ensure
@device.reset
end
end
@reader_thread.join unless opts[:detached]
end | ruby | def start(opts = nil)
logger.debug "starting Launchpad::Interaction##{object_id}"
opts = {
:detached => false
}.merge(opts || {})
@active = true
@reader_thread ||= Thread.new do
begin
while @active do
@device.read_pending_actions.each do |action|
action_thread = Thread.new(action) do |action|
respond_to_action(action)
end
@action_threads.add(action_thread)
end
sleep @latency# if @latency > 0.0
end
rescue Portmidi::DeviceError => e
logger.fatal "could not read from device, stopping to read actions"
raise CommunicationError.new(e)
rescue Exception => e
logger.fatal "error causing action reading to stop: #{e.inspect}"
raise e
ensure
@device.reset
end
end
@reader_thread.join unless opts[:detached]
end | [
"def",
"start",
"(",
"opts",
"=",
"nil",
")",
"logger",
".",
"debug",
"\"starting Launchpad::Interaction##{object_id}\"",
"opts",
"=",
"{",
":detached",
"=>",
"false",
"}",
".",
"merge",
"(",
"opts",
"||",
"{",
"}",
")",
"@active",
"=",
"true",
"@reader_thread",
"||=",
"Thread",
".",
"new",
"do",
"begin",
"while",
"@active",
"do",
"@device",
".",
"read_pending_actions",
".",
"each",
"do",
"|",
"action",
"|",
"action_thread",
"=",
"Thread",
".",
"new",
"(",
"action",
")",
"do",
"|",
"action",
"|",
"respond_to_action",
"(",
"action",
")",
"end",
"@action_threads",
".",
"add",
"(",
"action_thread",
")",
"end",
"sleep",
"@latency",
"# if @latency > 0.0",
"end",
"rescue",
"Portmidi",
"::",
"DeviceError",
"=>",
"e",
"logger",
".",
"fatal",
"\"could not read from device, stopping to read actions\"",
"raise",
"CommunicationError",
".",
"new",
"(",
"e",
")",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"fatal",
"\"error causing action reading to stop: #{e.inspect}\"",
"raise",
"e",
"ensure",
"@device",
".",
"reset",
"end",
"end",
"@reader_thread",
".",
"join",
"unless",
"opts",
"[",
":detached",
"]",
"end"
] | Starts interacting with the launchpad. Resets the device when
the interaction was properly stopped via stop or close.
Optional options hash:
[<tt>:detached</tt>] <tt>true/false</tt>,
whether to detach the interaction, method is blocking when +false+,
optional, defaults to +false+
Errors raised:
[Launchpad::NoInputAllowedError] when input is not enabled on the interaction's device
[Launchpad::NoOutputAllowedError] when output is not enabled on the interaction's device
[Launchpad::CommunicationError] when anything unexpected happens while communicating with the launchpad | [
"Starts",
"interacting",
"with",
"the",
"launchpad",
".",
"Resets",
"the",
"device",
"when",
"the",
"interaction",
"was",
"properly",
"stopped",
"via",
"stop",
"or",
"close",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/interaction.rb#L108-L139 |
3,618 | thomasjachmann/launchpad | lib/launchpad/interaction.rb | Launchpad.Interaction.stop | def stop
logger.debug "stopping Launchpad::Interaction##{object_id}"
@active = false
if @reader_thread
# run (resume from sleep) and wait for @reader_thread to end
@reader_thread.run if @reader_thread.alive?
@reader_thread.join
@reader_thread = nil
end
ensure
@action_threads.list.each do |thread|
begin
thread.kill
thread.join
rescue Exception => e
logger.error "error when killing action thread: #{e.inspect}"
end
end
nil
end | ruby | def stop
logger.debug "stopping Launchpad::Interaction##{object_id}"
@active = false
if @reader_thread
# run (resume from sleep) and wait for @reader_thread to end
@reader_thread.run if @reader_thread.alive?
@reader_thread.join
@reader_thread = nil
end
ensure
@action_threads.list.each do |thread|
begin
thread.kill
thread.join
rescue Exception => e
logger.error "error when killing action thread: #{e.inspect}"
end
end
nil
end | [
"def",
"stop",
"logger",
".",
"debug",
"\"stopping Launchpad::Interaction##{object_id}\"",
"@active",
"=",
"false",
"if",
"@reader_thread",
"# run (resume from sleep) and wait for @reader_thread to end",
"@reader_thread",
".",
"run",
"if",
"@reader_thread",
".",
"alive?",
"@reader_thread",
".",
"join",
"@reader_thread",
"=",
"nil",
"end",
"ensure",
"@action_threads",
".",
"list",
".",
"each",
"do",
"|",
"thread",
"|",
"begin",
"thread",
".",
"kill",
"thread",
".",
"join",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"\"error when killing action thread: #{e.inspect}\"",
"end",
"end",
"nil",
"end"
] | Stops interacting with the launchpad.
Errors raised:
[Launchpad::NoInputAllowedError] when input is not enabled on the interaction's device
[Launchpad::CommunicationError] when anything unexpected happens while communicating with the | [
"Stops",
"interacting",
"with",
"the",
"launchpad",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/interaction.rb#L147-L166 |
3,619 | thomasjachmann/launchpad | lib/launchpad/interaction.rb | Launchpad.Interaction.response_to | def response_to(types = :all, state = :both, opts = nil, &block)
logger.debug "setting response to #{types.inspect} for state #{state.inspect} with #{opts.inspect}"
types = Array(types)
opts ||= {}
no_response_to(types, state) if opts[:exclusive] == true
Array(state == :both ? %w(down up) : state).each do |state|
types.each do |type|
combined_types(type, opts).each do |combined_type|
responses[combined_type][state.to_sym] << block
end
end
end
nil
end | ruby | def response_to(types = :all, state = :both, opts = nil, &block)
logger.debug "setting response to #{types.inspect} for state #{state.inspect} with #{opts.inspect}"
types = Array(types)
opts ||= {}
no_response_to(types, state) if opts[:exclusive] == true
Array(state == :both ? %w(down up) : state).each do |state|
types.each do |type|
combined_types(type, opts).each do |combined_type|
responses[combined_type][state.to_sym] << block
end
end
end
nil
end | [
"def",
"response_to",
"(",
"types",
"=",
":all",
",",
"state",
"=",
":both",
",",
"opts",
"=",
"nil",
",",
"&",
"block",
")",
"logger",
".",
"debug",
"\"setting response to #{types.inspect} for state #{state.inspect} with #{opts.inspect}\"",
"types",
"=",
"Array",
"(",
"types",
")",
"opts",
"||=",
"{",
"}",
"no_response_to",
"(",
"types",
",",
"state",
")",
"if",
"opts",
"[",
":exclusive",
"]",
"==",
"true",
"Array",
"(",
"state",
"==",
":both",
"?",
"%w(",
"down",
"up",
")",
":",
"state",
")",
".",
"each",
"do",
"|",
"state",
"|",
"types",
".",
"each",
"do",
"|",
"type",
"|",
"combined_types",
"(",
"type",
",",
"opts",
")",
".",
"each",
"do",
"|",
"combined_type",
"|",
"responses",
"[",
"combined_type",
"]",
"[",
"state",
".",
"to_sym",
"]",
"<<",
"block",
"end",
"end",
"end",
"nil",
"end"
] | Registers a response to one or more actions.
Parameters (see Launchpad for values):
[+types+] one or an array of button types to respond to,
additional value <tt>:all</tt> for all buttons
[+state+] button state to respond to,
additional value <tt>:both</tt>
Optional options hash:
[<tt>:exclusive</tt>] <tt>true/false</tt>,
whether to deregister all other responses to the specified actions,
optional, defaults to +false+
[<tt>:x</tt>] x coordinate(s), can contain arrays and ranges, when specified
without y coordinate, it's interpreted as a whole column
[<tt>:y</tt>] y coordinate(s), can contain arrays and ranges, when specified
without x coordinate, it's interpreted as a whole row
Takes a block which will be called when an action matching the parameters occurs.
Block parameters:
[+interaction+] the interaction object that received the action
[+action+] the action received from Launchpad::Device.read_pending_actions | [
"Registers",
"a",
"response",
"to",
"one",
"or",
"more",
"actions",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/interaction.rb#L193-L206 |
3,620 | thomasjachmann/launchpad | lib/launchpad/interaction.rb | Launchpad.Interaction.no_response_to | def no_response_to(types = nil, state = :both, opts = nil)
logger.debug "removing response to #{types.inspect} for state #{state.inspect}"
types = Array(types)
Array(state == :both ? %w(down up) : state).each do |state|
types.each do |type|
combined_types(type, opts).each do |combined_type|
responses[combined_type][state.to_sym].clear
end
end
end
nil
end | ruby | def no_response_to(types = nil, state = :both, opts = nil)
logger.debug "removing response to #{types.inspect} for state #{state.inspect}"
types = Array(types)
Array(state == :both ? %w(down up) : state).each do |state|
types.each do |type|
combined_types(type, opts).each do |combined_type|
responses[combined_type][state.to_sym].clear
end
end
end
nil
end | [
"def",
"no_response_to",
"(",
"types",
"=",
"nil",
",",
"state",
"=",
":both",
",",
"opts",
"=",
"nil",
")",
"logger",
".",
"debug",
"\"removing response to #{types.inspect} for state #{state.inspect}\"",
"types",
"=",
"Array",
"(",
"types",
")",
"Array",
"(",
"state",
"==",
":both",
"?",
"%w(",
"down",
"up",
")",
":",
"state",
")",
".",
"each",
"do",
"|",
"state",
"|",
"types",
".",
"each",
"do",
"|",
"type",
"|",
"combined_types",
"(",
"type",
",",
"opts",
")",
".",
"each",
"do",
"|",
"combined_type",
"|",
"responses",
"[",
"combined_type",
"]",
"[",
"state",
".",
"to_sym",
"]",
".",
"clear",
"end",
"end",
"end",
"nil",
"end"
] | Deregisters all responses to one or more actions.
Parameters (see Launchpad for values):
[+types+] one or an array of button types to respond to,
additional value <tt>:all</tt> for actions on all buttons
(but not meaning "all responses"),
optional, defaults to +nil+, meaning "all responses"
[+state+] button state to respond to,
additional value <tt>:both</tt>
Optional options hash:
[<tt>:x</tt>] x coordinate(s), can contain arrays and ranges, when specified
without y coordinate, it's interpreted as a whole column
[<tt>:y</tt>] y coordinate(s), can contain arrays and ranges, when specified
without x coordinate, it's interpreted as a whole row | [
"Deregisters",
"all",
"responses",
"to",
"one",
"or",
"more",
"actions",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/interaction.rb#L225-L236 |
3,621 | thomasjachmann/launchpad | lib/launchpad/interaction.rb | Launchpad.Interaction.grid_range | def grid_range(range)
return nil if range.nil?
Array(range).flatten.map do |pos|
pos.respond_to?(:to_a) ? pos.to_a : pos
end.flatten.uniq
end | ruby | def grid_range(range)
return nil if range.nil?
Array(range).flatten.map do |pos|
pos.respond_to?(:to_a) ? pos.to_a : pos
end.flatten.uniq
end | [
"def",
"grid_range",
"(",
"range",
")",
"return",
"nil",
"if",
"range",
".",
"nil?",
"Array",
"(",
"range",
")",
".",
"flatten",
".",
"map",
"do",
"|",
"pos",
"|",
"pos",
".",
"respond_to?",
"(",
":to_a",
")",
"?",
"pos",
".",
"to_a",
":",
"pos",
"end",
".",
"flatten",
".",
"uniq",
"end"
] | Returns an array of grid positions for a range.
Parameters:
[+range+] the range definitions, can be
* a Fixnum
* a Range
* an Array of Fixnum, Range or Array objects | [
"Returns",
"an",
"array",
"of",
"grid",
"positions",
"for",
"a",
"range",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/interaction.rb#L270-L275 |
3,622 | pwnall/webkit_remote | lib/webkit_remote/event.rb | WebkitRemote.Event.matches? | def matches?(conditions)
conditions.all? do |key, value|
case key
when :class, :type
kind_of? value
when :name
name == value
else
# Simple cop-out.
send(key) == value
end
end
end | ruby | def matches?(conditions)
conditions.all? do |key, value|
case key
when :class, :type
kind_of? value
when :name
name == value
else
# Simple cop-out.
send(key) == value
end
end
end | [
"def",
"matches?",
"(",
"conditions",
")",
"conditions",
".",
"all?",
"do",
"|",
"key",
",",
"value",
"|",
"case",
"key",
"when",
":class",
",",
":type",
"kind_of?",
"value",
"when",
":name",
"name",
"==",
"value",
"else",
"# Simple cop-out.",
"send",
"(",
"key",
")",
"==",
"value",
"end",
"end",
"end"
] | Checks if the event meets a set of conditions.
This is used in WebkitRemote::Client#wait_for.
@param [Hash<Symbol, Object>] conditions the conditions that must be met
by an event to get out of the waiting loop
@option conditions [Class] class the class of events to wait for; this
condition is met if the event's class is a sub-class of the given class
@option conditions [Class] type synonym for class that can be used with the
Ruby 1.9 hash syntax
@option conditions [String] name the event's name, e.g.
"Page.loadEventFired"
@return [Boolean] true if this event matches all the given conditions | [
"Checks",
"if",
"the",
"event",
"meets",
"a",
"set",
"of",
"conditions",
"."
] | f38ac7e882726ff00e5c56898d06d91340f8179e | https://github.com/pwnall/webkit_remote/blob/f38ac7e882726ff00e5c56898d06d91340f8179e/lib/webkit_remote/event.rb#L30-L42 |
3,623 | printercu/rails_stuff | lib/rails_stuff/statusable.rb | RailsStuff.Statusable.statusable_methods | def statusable_methods
# Include generated methods with a module, not right in class.
@statusable_methods ||= Module.new.tap do |m|
m.const_set :ClassMethods, Module.new
include m
extend m::ClassMethods
end
end | ruby | def statusable_methods
# Include generated methods with a module, not right in class.
@statusable_methods ||= Module.new.tap do |m|
m.const_set :ClassMethods, Module.new
include m
extend m::ClassMethods
end
end | [
"def",
"statusable_methods",
"# Include generated methods with a module, not right in class.",
"@statusable_methods",
"||=",
"Module",
".",
"new",
".",
"tap",
"do",
"|",
"m",
"|",
"m",
".",
"const_set",
":ClassMethods",
",",
"Module",
".",
"new",
"include",
"m",
"extend",
"m",
"::",
"ClassMethods",
"end",
"end"
] | Module to hold generated methods. Single for all status fields in model. | [
"Module",
"to",
"hold",
"generated",
"methods",
".",
"Single",
"for",
"all",
"status",
"fields",
"in",
"model",
"."
] | b3d72daaae6426c8166205f6a7438a89768e8347 | https://github.com/printercu/rails_stuff/blob/b3d72daaae6426c8166205f6a7438a89768e8347/lib/rails_stuff/statusable.rb#L95-L102 |
3,624 | galetahub/sunrise | lib/sunrise/abstract_model.rb | Sunrise.AbstractModel.build_record | def build_record
record = model.new
record.send("#{parent_association.name}=", parent_record) if parent_record
record.build_defaults if record.respond_to?(:build_defaults)
record
end | ruby | def build_record
record = model.new
record.send("#{parent_association.name}=", parent_record) if parent_record
record.build_defaults if record.respond_to?(:build_defaults)
record
end | [
"def",
"build_record",
"record",
"=",
"model",
".",
"new",
"record",
".",
"send",
"(",
"\"#{parent_association.name}=\"",
",",
"parent_record",
")",
"if",
"parent_record",
"record",
".",
"build_defaults",
"if",
"record",
".",
"respond_to?",
"(",
":build_defaults",
")",
"record",
"end"
] | Initialize new model, sets parent record and call build_defaults method | [
"Initialize",
"new",
"model",
"sets",
"parent",
"record",
"and",
"call",
"build_defaults",
"method"
] | c65a8c6150180ae5569e45c57c1ff2c1092d0ab9 | https://github.com/galetahub/sunrise/blob/c65a8c6150180ae5569e45c57c1ff2c1092d0ab9/lib/sunrise/abstract_model.rb#L157-L162 |
3,625 | galetahub/sunrise | lib/sunrise/abstract_model.rb | Sunrise.AbstractModel.apply_scopes | def apply_scopes(params = nil, pagination = true)
raise ::AbstractController::ActionNotFound.new("List config is turn off") if without_index?
params ||= @request_params
scope = default_scope(params)
if current_list == :tree
scope = scope.roots
elsif pagination
scope = page_scope(scope, params[:page], params[:per])
end
scope
end | ruby | def apply_scopes(params = nil, pagination = true)
raise ::AbstractController::ActionNotFound.new("List config is turn off") if without_index?
params ||= @request_params
scope = default_scope(params)
if current_list == :tree
scope = scope.roots
elsif pagination
scope = page_scope(scope, params[:page], params[:per])
end
scope
end | [
"def",
"apply_scopes",
"(",
"params",
"=",
"nil",
",",
"pagination",
"=",
"true",
")",
"raise",
"::",
"AbstractController",
"::",
"ActionNotFound",
".",
"new",
"(",
"\"List config is turn off\"",
")",
"if",
"without_index?",
"params",
"||=",
"@request_params",
"scope",
"=",
"default_scope",
"(",
"params",
")",
"if",
"current_list",
"==",
":tree",
"scope",
"=",
"scope",
".",
"roots",
"elsif",
"pagination",
"scope",
"=",
"page_scope",
"(",
"scope",
",",
"params",
"[",
":page",
"]",
",",
"params",
"[",
":per",
"]",
")",
"end",
"scope",
"end"
] | Convert request params to model scopes | [
"Convert",
"request",
"params",
"to",
"model",
"scopes"
] | c65a8c6150180ae5569e45c57c1ff2c1092d0ab9 | https://github.com/galetahub/sunrise/blob/c65a8c6150180ae5569e45c57c1ff2c1092d0ab9/lib/sunrise/abstract_model.rb#L165-L178 |
3,626 | badboy/i3-ipc | lib/i3-ipc/manpage.rb | I3.Manpage.manpage | def manpage(name)
return "** Can't find groff(1)" unless groff?
require 'open3'
out = nil
Open3.popen3(groff_command) do |stdin, stdout, _|
stdin.puts raw_manpage(name)
stdin.close
out = stdout.read.strip
end
out
end | ruby | def manpage(name)
return "** Can't find groff(1)" unless groff?
require 'open3'
out = nil
Open3.popen3(groff_command) do |stdin, stdout, _|
stdin.puts raw_manpage(name)
stdin.close
out = stdout.read.strip
end
out
end | [
"def",
"manpage",
"(",
"name",
")",
"return",
"\"** Can't find groff(1)\"",
"unless",
"groff?",
"require",
"'open3'",
"out",
"=",
"nil",
"Open3",
".",
"popen3",
"(",
"groff_command",
")",
"do",
"|",
"stdin",
",",
"stdout",
",",
"_",
"|",
"stdin",
".",
"puts",
"raw_manpage",
"(",
"name",
")",
"stdin",
".",
"close",
"out",
"=",
"stdout",
".",
"read",
".",
"strip",
"end",
"out",
"end"
] | Prints a manpage, all pretty and paged.
Returns the terminal-formatted manpage, ready to be printed to
the screen. | [
"Prints",
"a",
"manpage",
"all",
"pretty",
"and",
"paged",
".",
"Returns",
"the",
"terminal",
"-",
"formatted",
"manpage",
"ready",
"to",
"be",
"printed",
"to",
"the",
"screen",
"."
] | 63b6d25552de4e6025fdcad14502d60140b478c3 | https://github.com/badboy/i3-ipc/blob/63b6d25552de4e6025fdcad14502d60140b478c3/lib/i3-ipc/manpage.rb#L12-L23 |
3,627 | badboy/i3-ipc | lib/i3-ipc/manpage.rb | I3.Manpage.raw_manpage | def raw_manpage(name)
if File.exists? file = File.dirname(__FILE__) + "/../../man/#{name}.1"
File.read(file)
else
DATA.read
end
end | ruby | def raw_manpage(name)
if File.exists? file = File.dirname(__FILE__) + "/../../man/#{name}.1"
File.read(file)
else
DATA.read
end
end | [
"def",
"raw_manpage",
"(",
"name",
")",
"if",
"File",
".",
"exists?",
"file",
"=",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
"+",
"\"/../../man/#{name}.1\"",
"File",
".",
"read",
"(",
"file",
")",
"else",
"DATA",
".",
"read",
"end",
"end"
] | Returns the raw manpage. If we're not running in standalone
mode, it's a file sitting at the root under the `man`
directory.
If we are running in standalone mode the manpage will be
included after the __END__ of the file so we can grab it using
DATA. | [
"Returns",
"the",
"raw",
"manpage",
".",
"If",
"we",
"re",
"not",
"running",
"in",
"standalone",
"mode",
"it",
"s",
"a",
"file",
"sitting",
"at",
"the",
"root",
"under",
"the",
"man",
"directory",
"."
] | 63b6d25552de4e6025fdcad14502d60140b478c3 | https://github.com/badboy/i3-ipc/blob/63b6d25552de4e6025fdcad14502d60140b478c3/lib/i3-ipc/manpage.rb#L32-L38 |
3,628 | printercu/rails_stuff | lib/rails_stuff/rspec_helpers.rb | RailsStuff.RSpecHelpers.clear_logs | def clear_logs
::RSpec.configure do |config|
config.add_setting :clear_log_file
config.clear_log_file = Rails.root.join('log', 'test.log') if defined?(Rails.root)
config.add_setting :clear_log_file_proc
config.clear_log_file_proc = ->(file) do
next unless file && File.exist?(file)
FileUtils.cp(file, "#{file}.last")
File.open(file, 'w').close
end
config.after(:suite) do
instance_exec(config.clear_log_file, &config.clear_log_file_proc) unless ENV['KEEP_LOG']
end
end
end | ruby | def clear_logs
::RSpec.configure do |config|
config.add_setting :clear_log_file
config.clear_log_file = Rails.root.join('log', 'test.log') if defined?(Rails.root)
config.add_setting :clear_log_file_proc
config.clear_log_file_proc = ->(file) do
next unless file && File.exist?(file)
FileUtils.cp(file, "#{file}.last")
File.open(file, 'w').close
end
config.after(:suite) do
instance_exec(config.clear_log_file, &config.clear_log_file_proc) unless ENV['KEEP_LOG']
end
end
end | [
"def",
"clear_logs",
"::",
"RSpec",
".",
"configure",
"do",
"|",
"config",
"|",
"config",
".",
"add_setting",
":clear_log_file",
"config",
".",
"clear_log_file",
"=",
"Rails",
".",
"root",
".",
"join",
"(",
"'log'",
",",
"'test.log'",
")",
"if",
"defined?",
"(",
"Rails",
".",
"root",
")",
"config",
".",
"add_setting",
":clear_log_file_proc",
"config",
".",
"clear_log_file_proc",
"=",
"->",
"(",
"file",
")",
"do",
"next",
"unless",
"file",
"&&",
"File",
".",
"exist?",
"(",
"file",
")",
"FileUtils",
".",
"cp",
"(",
"file",
",",
"\"#{file}.last\"",
")",
"File",
".",
"open",
"(",
"file",
",",
"'w'",
")",
".",
"close",
"end",
"config",
".",
"after",
"(",
":suite",
")",
"do",
"instance_exec",
"(",
"config",
".",
"clear_log_file",
",",
"config",
".",
"clear_log_file_proc",
")",
"unless",
"ENV",
"[",
"'KEEP_LOG'",
"]",
"end",
"end",
"end"
] | Clear logs `tail -f`-safely. | [
"Clear",
"logs",
"tail",
"-",
"f",
"-",
"safely",
"."
] | b3d72daaae6426c8166205f6a7438a89768e8347 | https://github.com/printercu/rails_stuff/blob/b3d72daaae6426c8166205f6a7438a89768e8347/lib/rails_stuff/rspec_helpers.rb#L100-L114 |
3,629 | blackwinter/wadl | lib/wadl/request_format.rb | WADL.RequestFormat.uri | def uri(resource, args = {})
uri = resource.uri(args)
query_values = args[:query] || {}
header_values = args[:headers] || {}
params.each { |param|
name = param.name
if param.style == 'header'
value = header_values[name] || header_values[name.to_sym]
value = param % value
uri.headers[name] = value if value
else
value = query_values[name] || query_values[name.to_sym]
value = param.format(value, nil, 'query')
uri.query << value if value && !value.empty?
end
}
uri
end | ruby | def uri(resource, args = {})
uri = resource.uri(args)
query_values = args[:query] || {}
header_values = args[:headers] || {}
params.each { |param|
name = param.name
if param.style == 'header'
value = header_values[name] || header_values[name.to_sym]
value = param % value
uri.headers[name] = value if value
else
value = query_values[name] || query_values[name.to_sym]
value = param.format(value, nil, 'query')
uri.query << value if value && !value.empty?
end
}
uri
end | [
"def",
"uri",
"(",
"resource",
",",
"args",
"=",
"{",
"}",
")",
"uri",
"=",
"resource",
".",
"uri",
"(",
"args",
")",
"query_values",
"=",
"args",
"[",
":query",
"]",
"||",
"{",
"}",
"header_values",
"=",
"args",
"[",
":headers",
"]",
"||",
"{",
"}",
"params",
".",
"each",
"{",
"|",
"param",
"|",
"name",
"=",
"param",
".",
"name",
"if",
"param",
".",
"style",
"==",
"'header'",
"value",
"=",
"header_values",
"[",
"name",
"]",
"||",
"header_values",
"[",
"name",
".",
"to_sym",
"]",
"value",
"=",
"param",
"%",
"value",
"uri",
".",
"headers",
"[",
"name",
"]",
"=",
"value",
"if",
"value",
"else",
"value",
"=",
"query_values",
"[",
"name",
"]",
"||",
"query_values",
"[",
"name",
".",
"to_sym",
"]",
"value",
"=",
"param",
".",
"format",
"(",
"value",
",",
"nil",
",",
"'query'",
")",
"uri",
".",
"query",
"<<",
"value",
"if",
"value",
"&&",
"!",
"value",
".",
"empty?",
"end",
"}",
"uri",
"end"
] | Returns a URI and a set of HTTP headers for this request. | [
"Returns",
"a",
"URI",
"and",
"a",
"set",
"of",
"HTTP",
"headers",
"for",
"this",
"request",
"."
] | 0e99d512f8b8627cb5e13a9e793d89c6af32066e | https://github.com/blackwinter/wadl/blob/0e99d512f8b8627cb5e13a9e793d89c6af32066e/lib/wadl/request_format.rb#L39-L62 |
3,630 | thomasjachmann/launchpad | lib/launchpad/device.rb | Launchpad.Device.change | def change(type, opts = nil)
opts ||= {}
status = %w(up down left right session user1 user2 mixer).include?(type.to_s) ? Status::CC : Status::ON
output(status, note(type, opts), velocity(opts))
end | ruby | def change(type, opts = nil)
opts ||= {}
status = %w(up down left right session user1 user2 mixer).include?(type.to_s) ? Status::CC : Status::ON
output(status, note(type, opts), velocity(opts))
end | [
"def",
"change",
"(",
"type",
",",
"opts",
"=",
"nil",
")",
"opts",
"||=",
"{",
"}",
"status",
"=",
"%w(",
"up",
"down",
"left",
"right",
"session",
"user1",
"user2",
"mixer",
")",
".",
"include?",
"(",
"type",
".",
"to_s",
")",
"?",
"Status",
"::",
"CC",
":",
"Status",
"::",
"ON",
"output",
"(",
"status",
",",
"note",
"(",
"type",
",",
"opts",
")",
",",
"velocity",
"(",
"opts",
")",
")",
"end"
] | Changes a single LED.
Parameters (see Launchpad for values):
[+type+] type of the button to change
Optional options hash (see Launchpad for values):
[<tt>:x</tt>] x coordinate
[<tt>:y</tt>] y coordinate
[<tt>:red</tt>] brightness of red LED
[<tt>:green</tt>] brightness of green LED
[<tt>:mode</tt>] button mode, defaults to <tt>:normal</tt>, one of:
[<tt>:normal/tt>] updates the LED for all circumstances (the new value will be written to both buffers)
[<tt>:flashing/tt>] updates the LED for flashing (the new value will be written to buffer 0 while the LED will be off in buffer 1, see buffering_mode)
[<tt>:buffering/tt>] updates the LED for the current update_buffer only
Errors raised:
[Launchpad::NoValidGridCoordinatesError] when coordinates aren't within the valid range
[Launchpad::NoValidBrightnessError] when brightness values aren't within the valid range
[Launchpad::NoOutputAllowedError] when output is not enabled | [
"Changes",
"a",
"single",
"LED",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/device.rb#L183-L187 |
3,631 | thomasjachmann/launchpad | lib/launchpad/device.rb | Launchpad.Device.change_all | def change_all(*colors)
# ensure that colors is at least and most 80 elements long
colors = colors.flatten[0..79]
colors += [0] * (80 - colors.size) if colors.size < 80
# send normal MIDI message to reset rapid LED change pointer
# in this case, set mapping mode to x-y layout (the default)
output(Status::CC, Status::NIL, GridLayout::XY)
# send colors in slices of 2
messages = []
colors.each_slice(2) do |c1, c2|
messages << message(Status::MULTI, velocity(c1), velocity(c2))
end
output_messages(messages)
end | ruby | def change_all(*colors)
# ensure that colors is at least and most 80 elements long
colors = colors.flatten[0..79]
colors += [0] * (80 - colors.size) if colors.size < 80
# send normal MIDI message to reset rapid LED change pointer
# in this case, set mapping mode to x-y layout (the default)
output(Status::CC, Status::NIL, GridLayout::XY)
# send colors in slices of 2
messages = []
colors.each_slice(2) do |c1, c2|
messages << message(Status::MULTI, velocity(c1), velocity(c2))
end
output_messages(messages)
end | [
"def",
"change_all",
"(",
"*",
"colors",
")",
"# ensure that colors is at least and most 80 elements long",
"colors",
"=",
"colors",
".",
"flatten",
"[",
"0",
"..",
"79",
"]",
"colors",
"+=",
"[",
"0",
"]",
"*",
"(",
"80",
"-",
"colors",
".",
"size",
")",
"if",
"colors",
".",
"size",
"<",
"80",
"# send normal MIDI message to reset rapid LED change pointer",
"# in this case, set mapping mode to x-y layout (the default)",
"output",
"(",
"Status",
"::",
"CC",
",",
"Status",
"::",
"NIL",
",",
"GridLayout",
"::",
"XY",
")",
"# send colors in slices of 2",
"messages",
"=",
"[",
"]",
"colors",
".",
"each_slice",
"(",
"2",
")",
"do",
"|",
"c1",
",",
"c2",
"|",
"messages",
"<<",
"message",
"(",
"Status",
"::",
"MULTI",
",",
"velocity",
"(",
"c1",
")",
",",
"velocity",
"(",
"c2",
")",
")",
"end",
"output_messages",
"(",
"messages",
")",
"end"
] | Changes all LEDs in batch mode.
Parameters (see Launchpad for values):
[+colors] an array of colors, each either being an integer or a Hash
* integer: calculated using the formula
<tt>color = 16 * green + red</tt>
* Hash:
[<tt>:red</tt>] brightness of red LED
[<tt>:green</tt>] brightness of green LED
[<tt>:mode</tt>] button mode, defaults to <tt>:normal</tt>, one of:
[<tt>:normal/tt>] updates the LEDs for all circumstances (the new value will be written to both buffers)
[<tt>:flashing/tt>] updates the LEDs for flashing (the new values will be written to buffer 0 while the LEDs will be off in buffer 1, see buffering_mode)
[<tt>:buffering/tt>] updates the LEDs for the current update_buffer only
the array consists of 64 colors for the grid buttons,
8 colors for the scene buttons (top to bottom)
and 8 colors for the top control buttons (left to right),
maximum 80 values - excessive values will be ignored,
missing values will be filled with 0
Errors raised:
[Launchpad::NoValidBrightnessError] when brightness values aren't within the valid range
[Launchpad::NoOutputAllowedError] when output is not enabled | [
"Changes",
"all",
"LEDs",
"in",
"batch",
"mode",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/device.rb#L213-L226 |
3,632 | thomasjachmann/launchpad | lib/launchpad/device.rb | Launchpad.Device.buffering_mode | def buffering_mode(opts = nil)
opts = {
:display_buffer => 0,
:update_buffer => 0,
:copy => false,
:flashing => false
}.merge(opts || {})
data = opts[:display_buffer] + 4 * opts[:update_buffer] + 32
data += 16 if opts[:copy]
data += 8 if opts[:flashing]
output(Status::CC, Status::NIL, data)
end | ruby | def buffering_mode(opts = nil)
opts = {
:display_buffer => 0,
:update_buffer => 0,
:copy => false,
:flashing => false
}.merge(opts || {})
data = opts[:display_buffer] + 4 * opts[:update_buffer] + 32
data += 16 if opts[:copy]
data += 8 if opts[:flashing]
output(Status::CC, Status::NIL, data)
end | [
"def",
"buffering_mode",
"(",
"opts",
"=",
"nil",
")",
"opts",
"=",
"{",
":display_buffer",
"=>",
"0",
",",
":update_buffer",
"=>",
"0",
",",
":copy",
"=>",
"false",
",",
":flashing",
"=>",
"false",
"}",
".",
"merge",
"(",
"opts",
"||",
"{",
"}",
")",
"data",
"=",
"opts",
"[",
":display_buffer",
"]",
"+",
"4",
"*",
"opts",
"[",
":update_buffer",
"]",
"+",
"32",
"data",
"+=",
"16",
"if",
"opts",
"[",
":copy",
"]",
"data",
"+=",
"8",
"if",
"opts",
"[",
":flashing",
"]",
"output",
"(",
"Status",
"::",
"CC",
",",
"Status",
"::",
"NIL",
",",
"data",
")",
"end"
] | Controls the two buffers.
Optional options hash:
[<tt>:display_buffer</tt>] which buffer to use for display, defaults to +0+
[<tt>:update_buffer</tt>] which buffer to use for updates when <tt>:mode</tt> is set to <tt>:buffering</tt>, defaults to +0+ (see change)
[<tt>:copy</tt>] whether to copy the LEDs states from the new display_buffer over to the new update_buffer, <tt>true/false</tt>, defaults to <tt>false</tt>
[<tt>:flashing</tt>] whether to start flashing by automatically switching between the two buffers for display, <tt>true/false</tt>, defaults to <tt>false</tt>
Errors raised:
[Launchpad::NoOutputAllowedError] when output is not enabled | [
"Controls",
"the",
"two",
"buffers",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/device.rb#L268-L279 |
3,633 | thomasjachmann/launchpad | lib/launchpad/device.rb | Launchpad.Device.output_messages | def output_messages(messages)
if @output.nil?
logger.error "trying to write to device that's not been initialized for output"
raise NoOutputAllowedError
end
logger.debug "writing messages to launchpad:\n #{messages.join("\n ")}" if logger.debug?
@output.write(messages)
nil
end | ruby | def output_messages(messages)
if @output.nil?
logger.error "trying to write to device that's not been initialized for output"
raise NoOutputAllowedError
end
logger.debug "writing messages to launchpad:\n #{messages.join("\n ")}" if logger.debug?
@output.write(messages)
nil
end | [
"def",
"output_messages",
"(",
"messages",
")",
"if",
"@output",
".",
"nil?",
"logger",
".",
"error",
"\"trying to write to device that's not been initialized for output\"",
"raise",
"NoOutputAllowedError",
"end",
"logger",
".",
"debug",
"\"writing messages to launchpad:\\n #{messages.join(\"\\n \")}\"",
"if",
"logger",
".",
"debug?",
"@output",
".",
"write",
"(",
"messages",
")",
"nil",
"end"
] | Writes several messages to the MIDI device.
Parameters:
[+messages+] an array of hashes (usually created with message) with:
[<tt>:message</tt>] an array of
MIDI status code,
MIDI data 1 (note),
MIDI data 2 (velocity)
[<tt>:timestamp</tt>] integer indicating the time when the MIDI message was created | [
"Writes",
"several",
"messages",
"to",
"the",
"MIDI",
"device",
"."
] | 16c775b1e5b66ffb57b87edcb0aed1b716c799b8 | https://github.com/thomasjachmann/launchpad/blob/16c775b1e5b66ffb57b87edcb0aed1b716c799b8/lib/launchpad/device.rb#L405-L413 |
3,634 | ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/provisioner.rb | Impressbox.Provisioner.provision | def provision
mass_loader('provision').each do |configurator|
next unless configurator.can_be_configured?(@machine, @@__loaded_config)
@machine.ui.info configurator.description if configurator.description
configurator.configure @machine, @@__loaded_config
end
end | ruby | def provision
mass_loader('provision').each do |configurator|
next unless configurator.can_be_configured?(@machine, @@__loaded_config)
@machine.ui.info configurator.description if configurator.description
configurator.configure @machine, @@__loaded_config
end
end | [
"def",
"provision",
"mass_loader",
"(",
"'provision'",
")",
".",
"each",
"do",
"|",
"configurator",
"|",
"next",
"unless",
"configurator",
".",
"can_be_configured?",
"(",
"@machine",
",",
"@@__loaded_config",
")",
"@machine",
".",
"ui",
".",
"info",
"configurator",
".",
"description",
"if",
"configurator",
".",
"description",
"configurator",
".",
"configure",
"@machine",
",",
"@@__loaded_config",
"end",
"end"
] | Do provision tasks | [
"Do",
"provision",
"tasks"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/provisioner.rb#L34-L40 |
3,635 | ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/provisioner.rb | Impressbox.Provisioner.run_primaty_configuration | def run_primaty_configuration(root_config)
old_root = root_config.dup
old_loaded = @@__loaded_config.dup
mass_loader('primary').each do |configurator|
next unless configurator.can_be_configured?(old_root, old_loaded)
@machine.ui.info configurator.description if configurator.description
configurator.configure root_config, old_loaded
end
end | ruby | def run_primaty_configuration(root_config)
old_root = root_config.dup
old_loaded = @@__loaded_config.dup
mass_loader('primary').each do |configurator|
next unless configurator.can_be_configured?(old_root, old_loaded)
@machine.ui.info configurator.description if configurator.description
configurator.configure root_config, old_loaded
end
end | [
"def",
"run_primaty_configuration",
"(",
"root_config",
")",
"old_root",
"=",
"root_config",
".",
"dup",
"old_loaded",
"=",
"@@__loaded_config",
".",
"dup",
"mass_loader",
"(",
"'primary'",
")",
".",
"each",
"do",
"|",
"configurator",
"|",
"next",
"unless",
"configurator",
".",
"can_be_configured?",
"(",
"old_root",
",",
"old_loaded",
")",
"@machine",
".",
"ui",
".",
"info",
"configurator",
".",
"description",
"if",
"configurator",
".",
"description",
"configurator",
".",
"configure",
"root_config",
",",
"old_loaded",
"end",
"end"
] | Runs primary configuration
@param root_config [Object] Root Vagrant config | [
"Runs",
"primary",
"configuration"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/provisioner.rb#L47-L55 |
3,636 | ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/provisioner.rb | Impressbox.Provisioner.mass_loader | def mass_loader(type)
namespace = 'Impressbox::Configurators::' + ucfirst(type)
path = File.join('..', 'configurators', type)
Impressbox::Objects::MassFileLoader.new namespace, path
end | ruby | def mass_loader(type)
namespace = 'Impressbox::Configurators::' + ucfirst(type)
path = File.join('..', 'configurators', type)
Impressbox::Objects::MassFileLoader.new namespace, path
end | [
"def",
"mass_loader",
"(",
"type",
")",
"namespace",
"=",
"'Impressbox::Configurators::'",
"+",
"ucfirst",
"(",
"type",
")",
"path",
"=",
"File",
".",
"join",
"(",
"'..'",
",",
"'configurators'",
",",
"type",
")",
"Impressbox",
"::",
"Objects",
"::",
"MassFileLoader",
".",
"new",
"namespace",
",",
"path",
"end"
] | Gets preconfigured MassFileLoader instance
@param type [String] Files type
@return [::Impressbox::Objects::MassFileLoader] | [
"Gets",
"preconfigured",
"MassFileLoader",
"instance"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/provisioner.rb#L62-L66 |
3,637 | ImpressCMS/vagrant-impressbox | lib/vagrant-impressbox/provisioner.rb | Impressbox.Provisioner.xaml_config | def xaml_config
require_relative File.join('objects', 'config_file')
file = detect_file(config.file)
@machine.ui.info "\t" + I18n.t('config.loaded_from_file', file: file)
Impressbox::Objects::ConfigFile.new file
end | ruby | def xaml_config
require_relative File.join('objects', 'config_file')
file = detect_file(config.file)
@machine.ui.info "\t" + I18n.t('config.loaded_from_file', file: file)
Impressbox::Objects::ConfigFile.new file
end | [
"def",
"xaml_config",
"require_relative",
"File",
".",
"join",
"(",
"'objects'",
",",
"'config_file'",
")",
"file",
"=",
"detect_file",
"(",
"config",
".",
"file",
")",
"@machine",
".",
"ui",
".",
"info",
"\"\\t\"",
"+",
"I18n",
".",
"t",
"(",
"'config.loaded_from_file'",
",",
"file",
":",
"file",
")",
"Impressbox",
"::",
"Objects",
"::",
"ConfigFile",
".",
"new",
"file",
"end"
] | Loads xaml config
@return [::Impressbox::Objects::ConfigFile] | [
"Loads",
"xaml",
"config"
] | 78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2 | https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/provisioner.rb#L81-L86 |
3,638 | pwnall/webkit_remote | lib/webkit_remote/client.rb | WebkitRemote.Client.wait_for | def wait_for(conditions)
unless WebkitRemote::Event.can_receive? self, conditions
raise ArgumentError, "Cannot receive event with #{conditions.inspect}"
end
events = []
each_event do |event|
events << event
break if event.matches?(conditions)
end
events
end | ruby | def wait_for(conditions)
unless WebkitRemote::Event.can_receive? self, conditions
raise ArgumentError, "Cannot receive event with #{conditions.inspect}"
end
events = []
each_event do |event|
events << event
break if event.matches?(conditions)
end
events
end | [
"def",
"wait_for",
"(",
"conditions",
")",
"unless",
"WebkitRemote",
"::",
"Event",
".",
"can_receive?",
"self",
",",
"conditions",
"raise",
"ArgumentError",
",",
"\"Cannot receive event with #{conditions.inspect}\"",
"end",
"events",
"=",
"[",
"]",
"each_event",
"do",
"|",
"event",
"|",
"events",
"<<",
"event",
"break",
"if",
"event",
".",
"matches?",
"(",
"conditions",
")",
"end",
"events",
"end"
] | Waits for the remote debugging server to send a specific event.
@param (see WebkitRemote::Event#matches?)
@return [Array<WebkitRemote::Event>] all the events received, including the
event that matches the class requirement | [
"Waits",
"for",
"the",
"remote",
"debugging",
"server",
"to",
"send",
"a",
"specific",
"event",
"."
] | f38ac7e882726ff00e5c56898d06d91340f8179e | https://github.com/pwnall/webkit_remote/blob/f38ac7e882726ff00e5c56898d06d91340f8179e/lib/webkit_remote/client.rb#L72-L83 |
3,639 | esumbar/passphrase | lib/passphrase/wordlist_database.rb | Passphrase.Language.validate | def validate(language_list)
language_list.each do |l|
matches_language = @languages.any? { |language| language.match("^#{l}") }
raise "No language match for #{l}" unless matches_language
end
end | ruby | def validate(language_list)
language_list.each do |l|
matches_language = @languages.any? { |language| language.match("^#{l}") }
raise "No language match for #{l}" unless matches_language
end
end | [
"def",
"validate",
"(",
"language_list",
")",
"language_list",
".",
"each",
"do",
"|",
"l",
"|",
"matches_language",
"=",
"@languages",
".",
"any?",
"{",
"|",
"language",
"|",
"language",
".",
"match",
"(",
"\"^#{l}\"",
")",
"}",
"raise",
"\"No language match for #{l}\"",
"unless",
"matches_language",
"end",
"end"
] | Make sure that each language specification matches at least one
language. | [
"Make",
"sure",
"that",
"each",
"language",
"specification",
"matches",
"at",
"least",
"one",
"language",
"."
] | 5faaa6dcf71f31bc6acad6f683f581408e0b5c32 | https://github.com/esumbar/passphrase/blob/5faaa6dcf71f31bc6acad6f683f581408e0b5c32/lib/passphrase/wordlist_database.rb#L45-L50 |
3,640 | boris-s/y_petri | lib/y_petri/agent/simulation_aspect.rb | YPetri::Agent::SimulationAspect.SimulationPoint.identify | def identify( name: nil, net: nil, cc: nil, imc: nil, ssc: nil, **nn )
name || { net: net, cc: cc, imc: imc, ssc: ssc }.merge( nn )
end | ruby | def identify( name: nil, net: nil, cc: nil, imc: nil, ssc: nil, **nn )
name || { net: net, cc: cc, imc: imc, ssc: ssc }.merge( nn )
end | [
"def",
"identify",
"(",
"name",
":",
"nil",
",",
"net",
":",
"nil",
",",
"cc",
":",
"nil",
",",
"imc",
":",
"nil",
",",
"ssc",
":",
"nil",
",",
"**",
"nn",
")",
"name",
"||",
"{",
"net",
":",
"net",
",",
"cc",
":",
"cc",
",",
"imc",
":",
"imc",
",",
"ssc",
":",
"ssc",
"}",
".",
"merge",
"(",
"nn",
")",
"end"
] | Helper method specifying how a simulation is identified by arguments. | [
"Helper",
"method",
"specifying",
"how",
"a",
"simulation",
"is",
"identified",
"by",
"arguments",
"."
] | f69630d9f1e2ec85c528a9f62e8ba53138e0939e | https://github.com/boris-s/y_petri/blob/f69630d9f1e2ec85c528a9f62e8ba53138e0939e/lib/y_petri/agent/simulation_aspect.rb#L45-L47 |
3,641 | justice3120/danger-conflict_checker | lib/conflict_checker/plugin.rb | Danger.DangerConflictChecker.check_conflict_and_comment | def check_conflict_and_comment()
results = check_conflict()
results.each do |result|
next if result[:mergeable]
message = "<p>This PR conflicts with <a href=\"#{result[:pull_request][:html_url]}\">##{result[:pull_request][:number]}</a>.</p>"
table = '<table><thead><tr><th width="100%">File</th><th>Line</th></tr></thead><tbody>' + result[:conflicts].map do |conflict|
file = conflict[:file]
line = conflict[:line]
line_link = "#{result[:pull_request][:head][:repo][:html_url]}/blob/#{result[:pull_request][:head][:ref]}/#{file}#L#{line}"
"<tr><td>#{file}</td><td><a href=\"#{line_link}\">#L#{line}</a></td></tr>"
end.join('') + '</tbody></table>'
puts (message + table)
warn("<div>" + message + table + "</div>")
end
results
end | ruby | def check_conflict_and_comment()
results = check_conflict()
results.each do |result|
next if result[:mergeable]
message = "<p>This PR conflicts with <a href=\"#{result[:pull_request][:html_url]}\">##{result[:pull_request][:number]}</a>.</p>"
table = '<table><thead><tr><th width="100%">File</th><th>Line</th></tr></thead><tbody>' + result[:conflicts].map do |conflict|
file = conflict[:file]
line = conflict[:line]
line_link = "#{result[:pull_request][:head][:repo][:html_url]}/blob/#{result[:pull_request][:head][:ref]}/#{file}#L#{line}"
"<tr><td>#{file}</td><td><a href=\"#{line_link}\">#L#{line}</a></td></tr>"
end.join('') + '</tbody></table>'
puts (message + table)
warn("<div>" + message + table + "</div>")
end
results
end | [
"def",
"check_conflict_and_comment",
"(",
")",
"results",
"=",
"check_conflict",
"(",
")",
"results",
".",
"each",
"do",
"|",
"result",
"|",
"next",
"if",
"result",
"[",
":mergeable",
"]",
"message",
"=",
"\"<p>This PR conflicts with <a href=\\\"#{result[:pull_request][:html_url]}\\\">##{result[:pull_request][:number]}</a>.</p>\"",
"table",
"=",
"'<table><thead><tr><th width=\"100%\">File</th><th>Line</th></tr></thead><tbody>'",
"+",
"result",
"[",
":conflicts",
"]",
".",
"map",
"do",
"|",
"conflict",
"|",
"file",
"=",
"conflict",
"[",
":file",
"]",
"line",
"=",
"conflict",
"[",
":line",
"]",
"line_link",
"=",
"\"#{result[:pull_request][:head][:repo][:html_url]}/blob/#{result[:pull_request][:head][:ref]}/#{file}#L#{line}\"",
"\"<tr><td>#{file}</td><td><a href=\\\"#{line_link}\\\">#L#{line}</a></td></tr>\"",
"end",
".",
"join",
"(",
"''",
")",
"+",
"'</tbody></table>'",
"puts",
"(",
"message",
"+",
"table",
")",
"warn",
"(",
"\"<div>\"",
"+",
"message",
"+",
"table",
"+",
"\"</div>\"",
")",
"end",
"results",
"end"
] | Warn in PR comment about the conflict between PRs
@return [Array<Hash>] | [
"Warn",
"in",
"PR",
"comment",
"about",
"the",
"conflict",
"between",
"PRs"
] | b3ac6a5f18553e455a9a474b3cd85fa8c2c83ebe | https://github.com/justice3120/danger-conflict_checker/blob/b3ac6a5f18553e455a9a474b3cd85fa8c2c83ebe/lib/conflict_checker/plugin.rb#L88-L105 |
3,642 | bmuller/ankusa | lib/ankusa/cassandra_storage.rb | Ankusa.CassandraStorage.init_tables | def init_tables
# Do nothing if keyspace already exists
if @cassandra.keyspaces.include?(@keyspace)
@cassandra.keyspace = @keyspace
else
freq_table = Cassandra::ColumnFamily.new({:keyspace => @keyspace, :name => "classes"}) # word => {classname => count}
summary_table = Cassandra::ColumnFamily.new({:keyspace => @keyspace, :name => "totals"}) # class => {wordcount => count}
ks_def = Cassandra::Keyspace.new({
:name => @keyspace,
:strategy_class => 'org.apache.cassandra.locator.SimpleStrategy',
:replication_factor => 1,
:cf_defs => [freq_table, summary_table]
})
@cassandra.add_keyspace ks_def
@cassandra.keyspace = @keyspace
end
end | ruby | def init_tables
# Do nothing if keyspace already exists
if @cassandra.keyspaces.include?(@keyspace)
@cassandra.keyspace = @keyspace
else
freq_table = Cassandra::ColumnFamily.new({:keyspace => @keyspace, :name => "classes"}) # word => {classname => count}
summary_table = Cassandra::ColumnFamily.new({:keyspace => @keyspace, :name => "totals"}) # class => {wordcount => count}
ks_def = Cassandra::Keyspace.new({
:name => @keyspace,
:strategy_class => 'org.apache.cassandra.locator.SimpleStrategy',
:replication_factor => 1,
:cf_defs => [freq_table, summary_table]
})
@cassandra.add_keyspace ks_def
@cassandra.keyspace = @keyspace
end
end | [
"def",
"init_tables",
"# Do nothing if keyspace already exists",
"if",
"@cassandra",
".",
"keyspaces",
".",
"include?",
"(",
"@keyspace",
")",
"@cassandra",
".",
"keyspace",
"=",
"@keyspace",
"else",
"freq_table",
"=",
"Cassandra",
"::",
"ColumnFamily",
".",
"new",
"(",
"{",
":keyspace",
"=>",
"@keyspace",
",",
":name",
"=>",
"\"classes\"",
"}",
")",
"# word => {classname => count}",
"summary_table",
"=",
"Cassandra",
"::",
"ColumnFamily",
".",
"new",
"(",
"{",
":keyspace",
"=>",
"@keyspace",
",",
":name",
"=>",
"\"totals\"",
"}",
")",
"# class => {wordcount => count}",
"ks_def",
"=",
"Cassandra",
"::",
"Keyspace",
".",
"new",
"(",
"{",
":name",
"=>",
"@keyspace",
",",
":strategy_class",
"=>",
"'org.apache.cassandra.locator.SimpleStrategy'",
",",
":replication_factor",
"=>",
"1",
",",
":cf_defs",
"=>",
"[",
"freq_table",
",",
"summary_table",
"]",
"}",
")",
"@cassandra",
".",
"add_keyspace",
"ks_def",
"@cassandra",
".",
"keyspace",
"=",
"@keyspace",
"end",
"end"
] | Create required keyspace and column families | [
"Create",
"required",
"keyspace",
"and",
"column",
"families"
] | af946f130aa63532fdb67d8382cfaaf81b38027b | https://github.com/bmuller/ankusa/blob/af946f130aa63532fdb67d8382cfaaf81b38027b/lib/ankusa/cassandra_storage.rb#L62-L78 |
3,643 | bmuller/ankusa | lib/ankusa/cassandra_storage.rb | Ankusa.CassandraStorage.get_word_counts | def get_word_counts(word)
# fetch all (class,count) pairs for a given word
row = @cassandra.get(:classes, word.to_s)
return row.to_hash if row.empty?
row.inject({}){|counts, col| counts[col.first.to_sym] = [col.last.to_f,0].max; counts}
end | ruby | def get_word_counts(word)
# fetch all (class,count) pairs for a given word
row = @cassandra.get(:classes, word.to_s)
return row.to_hash if row.empty?
row.inject({}){|counts, col| counts[col.first.to_sym] = [col.last.to_f,0].max; counts}
end | [
"def",
"get_word_counts",
"(",
"word",
")",
"# fetch all (class,count) pairs for a given word",
"row",
"=",
"@cassandra",
".",
"get",
"(",
":classes",
",",
"word",
".",
"to_s",
")",
"return",
"row",
".",
"to_hash",
"if",
"row",
".",
"empty?",
"row",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"counts",
",",
"col",
"|",
"counts",
"[",
"col",
".",
"first",
".",
"to_sym",
"]",
"=",
"[",
"col",
".",
"last",
".",
"to_f",
",",
"0",
"]",
".",
"max",
";",
"counts",
"}",
"end"
] | Fetch hash of word counts as a single row from cassandra.
Here column_name is the class and column value is the count | [
"Fetch",
"hash",
"of",
"word",
"counts",
"as",
"a",
"single",
"row",
"from",
"cassandra",
".",
"Here",
"column_name",
"is",
"the",
"class",
"and",
"column",
"value",
"is",
"the",
"count"
] | af946f130aa63532fdb67d8382cfaaf81b38027b | https://github.com/bmuller/ankusa/blob/af946f130aa63532fdb67d8382cfaaf81b38027b/lib/ankusa/cassandra_storage.rb#L84-L89 |
3,644 | bmuller/ankusa | lib/ankusa/cassandra_storage.rb | Ankusa.CassandraStorage.incr_total_word_count | def incr_total_word_count(klass, count)
klass = klass.to_s
wordcount = @cassandra.get(:totals, klass, "wordcount").values.last.to_i
wordcount += count
@cassandra.insert(:totals, klass, {"wordcount" => wordcount.to_s})
@klass_word_counts[klass.to_sym] = wordcount
end | ruby | def incr_total_word_count(klass, count)
klass = klass.to_s
wordcount = @cassandra.get(:totals, klass, "wordcount").values.last.to_i
wordcount += count
@cassandra.insert(:totals, klass, {"wordcount" => wordcount.to_s})
@klass_word_counts[klass.to_sym] = wordcount
end | [
"def",
"incr_total_word_count",
"(",
"klass",
",",
"count",
")",
"klass",
"=",
"klass",
".",
"to_s",
"wordcount",
"=",
"@cassandra",
".",
"get",
"(",
":totals",
",",
"klass",
",",
"\"wordcount\"",
")",
".",
"values",
".",
"last",
".",
"to_i",
"wordcount",
"+=",
"count",
"@cassandra",
".",
"insert",
"(",
":totals",
",",
"klass",
",",
"{",
"\"wordcount\"",
"=>",
"wordcount",
".",
"to_s",
"}",
")",
"@klass_word_counts",
"[",
"klass",
".",
"to_sym",
"]",
"=",
"wordcount",
"end"
] | Increment total word count for a given class by 'count' | [
"Increment",
"total",
"word",
"count",
"for",
"a",
"given",
"class",
"by",
"count"
] | af946f130aa63532fdb67d8382cfaaf81b38027b | https://github.com/bmuller/ankusa/blob/af946f130aa63532fdb67d8382cfaaf81b38027b/lib/ankusa/cassandra_storage.rb#L148-L154 |
3,645 | bmuller/ankusa | lib/ankusa/cassandra_storage.rb | Ankusa.CassandraStorage.incr_doc_count | def incr_doc_count(klass, count)
klass = klass.to_s
doc_count = @cassandra.get(:totals, klass, "doc_count").values.last.to_i
doc_count += count
@cassandra.insert(:totals, klass, {"doc_count" => doc_count.to_s})
@klass_doc_counts[klass.to_sym] = doc_count
end | ruby | def incr_doc_count(klass, count)
klass = klass.to_s
doc_count = @cassandra.get(:totals, klass, "doc_count").values.last.to_i
doc_count += count
@cassandra.insert(:totals, klass, {"doc_count" => doc_count.to_s})
@klass_doc_counts[klass.to_sym] = doc_count
end | [
"def",
"incr_doc_count",
"(",
"klass",
",",
"count",
")",
"klass",
"=",
"klass",
".",
"to_s",
"doc_count",
"=",
"@cassandra",
".",
"get",
"(",
":totals",
",",
"klass",
",",
"\"doc_count\"",
")",
".",
"values",
".",
"last",
".",
"to_i",
"doc_count",
"+=",
"count",
"@cassandra",
".",
"insert",
"(",
":totals",
",",
"klass",
",",
"{",
"\"doc_count\"",
"=>",
"doc_count",
".",
"to_s",
"}",
")",
"@klass_doc_counts",
"[",
"klass",
".",
"to_sym",
"]",
"=",
"doc_count",
"end"
] | Increment total document count for a given class by 'count' | [
"Increment",
"total",
"document",
"count",
"for",
"a",
"given",
"class",
"by",
"count"
] | af946f130aa63532fdb67d8382cfaaf81b38027b | https://github.com/bmuller/ankusa/blob/af946f130aa63532fdb67d8382cfaaf81b38027b/lib/ankusa/cassandra_storage.rb#L159-L165 |
3,646 | bmuller/ankusa | lib/ankusa/cassandra_storage.rb | Ankusa.CassandraStorage.get_summary | def get_summary(name)
counts = {}
@cassandra.get_range(:totals, {:start => '', :finish => '', :count => @max_classes}).each do |key_slice|
# keyslice is a clunky thrift object, map into a ruby hash
row = key_slice.columns.inject({}){|hsh, c| hsh[c.column.name] = c.column.value; hsh}
counts[key_slice.key.to_sym] = row[name].to_f
end
counts
end | ruby | def get_summary(name)
counts = {}
@cassandra.get_range(:totals, {:start => '', :finish => '', :count => @max_classes}).each do |key_slice|
# keyslice is a clunky thrift object, map into a ruby hash
row = key_slice.columns.inject({}){|hsh, c| hsh[c.column.name] = c.column.value; hsh}
counts[key_slice.key.to_sym] = row[name].to_f
end
counts
end | [
"def",
"get_summary",
"(",
"name",
")",
"counts",
"=",
"{",
"}",
"@cassandra",
".",
"get_range",
"(",
":totals",
",",
"{",
":start",
"=>",
"''",
",",
":finish",
"=>",
"''",
",",
":count",
"=>",
"@max_classes",
"}",
")",
".",
"each",
"do",
"|",
"key_slice",
"|",
"# keyslice is a clunky thrift object, map into a ruby hash",
"row",
"=",
"key_slice",
".",
"columns",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"hsh",
",",
"c",
"|",
"hsh",
"[",
"c",
".",
"column",
".",
"name",
"]",
"=",
"c",
".",
"column",
".",
"value",
";",
"hsh",
"}",
"counts",
"[",
"key_slice",
".",
"key",
".",
"to_sym",
"]",
"=",
"row",
"[",
"name",
"]",
".",
"to_f",
"end",
"counts",
"end"
] | Fetch 100 rows from summary table, yes, increase if necessary | [
"Fetch",
"100",
"rows",
"from",
"summary",
"table",
"yes",
"increase",
"if",
"necessary"
] | af946f130aa63532fdb67d8382cfaaf81b38027b | https://github.com/bmuller/ankusa/blob/af946f130aa63532fdb67d8382cfaaf81b38027b/lib/ankusa/cassandra_storage.rb#L182-L190 |
3,647 | jmdeldin/cross_validation | lib/cross_validation/runner.rb | CrossValidation.Runner.valid? | def valid?
@errors = []
@critical_keys.each do |k|
any_error = public_send(k).nil?
@errors << k if any_error
end
@errors.size == 0
end | ruby | def valid?
@errors = []
@critical_keys.each do |k|
any_error = public_send(k).nil?
@errors << k if any_error
end
@errors.size == 0
end | [
"def",
"valid?",
"@errors",
"=",
"[",
"]",
"@critical_keys",
".",
"each",
"do",
"|",
"k",
"|",
"any_error",
"=",
"public_send",
"(",
"k",
")",
".",
"nil?",
"@errors",
"<<",
"k",
"if",
"any_error",
"end",
"@errors",
".",
"size",
"==",
"0",
"end"
] | Checks if all of the required run parameters are set.
@return [Boolean] | [
"Checks",
"if",
"all",
"of",
"the",
"required",
"run",
"parameters",
"are",
"set",
"."
] | 048938169231f051c1612af608cde673ccc77529 | https://github.com/jmdeldin/cross_validation/blob/048938169231f051c1612af608cde673ccc77529/lib/cross_validation/runner.rb#L69-L77 |
3,648 | jmdeldin/cross_validation | lib/cross_validation/runner.rb | CrossValidation.Runner.run | def run
fail_if_invalid
partitions = Partitioner.subset(documents, k)
results = partitions.map.with_index do |part, i|
training_samples = Partitioner.exclude_index(documents, i)
classifier_instance = classifier.call()
train(classifier_instance, training_samples)
# fetch confusion keys
part.each do |x|
prediction = classify(classifier_instance, x)
matrix.store(prediction, fetch_sample_class.call(x))
end
end
matrix
end | ruby | def run
fail_if_invalid
partitions = Partitioner.subset(documents, k)
results = partitions.map.with_index do |part, i|
training_samples = Partitioner.exclude_index(documents, i)
classifier_instance = classifier.call()
train(classifier_instance, training_samples)
# fetch confusion keys
part.each do |x|
prediction = classify(classifier_instance, x)
matrix.store(prediction, fetch_sample_class.call(x))
end
end
matrix
end | [
"def",
"run",
"fail_if_invalid",
"partitions",
"=",
"Partitioner",
".",
"subset",
"(",
"documents",
",",
"k",
")",
"results",
"=",
"partitions",
".",
"map",
".",
"with_index",
"do",
"|",
"part",
",",
"i",
"|",
"training_samples",
"=",
"Partitioner",
".",
"exclude_index",
"(",
"documents",
",",
"i",
")",
"classifier_instance",
"=",
"classifier",
".",
"call",
"(",
")",
"train",
"(",
"classifier_instance",
",",
"training_samples",
")",
"# fetch confusion keys",
"part",
".",
"each",
"do",
"|",
"x",
"|",
"prediction",
"=",
"classify",
"(",
"classifier_instance",
",",
"x",
")",
"matrix",
".",
"store",
"(",
"prediction",
",",
"fetch_sample_class",
".",
"call",
"(",
"x",
")",
")",
"end",
"end",
"matrix",
"end"
] | Performs k-fold cross-validation and returns a confusion matrix.
The algorithm is as follows (Mitchell, 1997, p147):
partitions = partition data into k-equal sized subsets (folds)
for i = 1 -> k:
T = data \ partitions[i]
train(T)
classify(partitions[i])
output confusion matrix
@raise [ArgumentError] if the runner is missing required attributes
@return [ConfusionMatrix] | [
"Performs",
"k",
"-",
"fold",
"cross",
"-",
"validation",
"and",
"returns",
"a",
"confusion",
"matrix",
"."
] | 048938169231f051c1612af608cde673ccc77529 | https://github.com/jmdeldin/cross_validation/blob/048938169231f051c1612af608cde673ccc77529/lib/cross_validation/runner.rb#L97-L117 |
3,649 | kkirsche/medium-sdk-ruby | lib/medium/publications.rb | Medium.Publications.create_post | def create_post(publication, opts)
response = @client.post "publications/#{publication['id']}/posts",
build_request_with(opts)
Medium::Client.validate response
end | ruby | def create_post(publication, opts)
response = @client.post "publications/#{publication['id']}/posts",
build_request_with(opts)
Medium::Client.validate response
end | [
"def",
"create_post",
"(",
"publication",
",",
"opts",
")",
"response",
"=",
"@client",
".",
"post",
"\"publications/#{publication['id']}/posts\"",
",",
"build_request_with",
"(",
"opts",
")",
"Medium",
"::",
"Client",
".",
"validate",
"response",
"end"
] | Creates a post in a publication on behalf of the authenticated user.
@param publication [Publication] A publication object.
@param opts [Hash] A hash of options to use when creating a post. The opts
hash requires the keys: `:title`, `:content_format`, and `:content`. The
following keys are optional: `:tags`, `:canonical_url`,
`:publish_status`, and `:license`
@return [Hash] The response is a Post object within a data envelope.
Example response:
```
HTTP/1.1 201 OK
Content-Type: application/json; charset=utf-8
{
"data": {
"id": "e6f36a",
"title": "Liverpool FC",
"authorId": "5303d74c64f66366f00cb9b2a94f3251bf5",
"tags": ["football", "sport", "Liverpool"],
"url": "https://medium.com/@majelbstoat/liverpool-fc-e6f36a",
"canonicalUrl": "http://jamietalbot.com/posts/liverpool-fc",
"publishStatus": "public",
"publishedAt": 1442286338435,
"license": "all-rights-reserved",
"licenseUrl": "https://medium.com/policy/9db0094a1e0f",
"publicationId": "e3ef7f020bd"
}
}
``` | [
"Creates",
"a",
"post",
"in",
"a",
"publication",
"on",
"behalf",
"of",
"the",
"authenticated",
"user",
"."
] | eb3bbab3233737d4a60936c8a3b9dfdaf5e855bb | https://github.com/kkirsche/medium-sdk-ruby/blob/eb3bbab3233737d4a60936c8a3b9dfdaf5e855bb/lib/medium/publications.rb#L64-L68 |
3,650 | damir/okta-jwt | lib/okta/jwt.rb | Okta.Jwt.sign_in_user | def sign_in_user(username:, password:, client_id:, client_secret:, scope: 'openid')
client(issuer).post do |req|
req.url "/oauth2/#{auth_server_id}/v1/token"
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.headers['Authorization'] = 'Basic: ' + Base64.strict_encode64("#{client_id}:#{client_secret}")
req.body = URI.encode_www_form username: username, password: password, scope: scope, grant_type: 'password'
end
end | ruby | def sign_in_user(username:, password:, client_id:, client_secret:, scope: 'openid')
client(issuer).post do |req|
req.url "/oauth2/#{auth_server_id}/v1/token"
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.headers['Authorization'] = 'Basic: ' + Base64.strict_encode64("#{client_id}:#{client_secret}")
req.body = URI.encode_www_form username: username, password: password, scope: scope, grant_type: 'password'
end
end | [
"def",
"sign_in_user",
"(",
"username",
":",
",",
"password",
":",
",",
"client_id",
":",
",",
"client_secret",
":",
",",
"scope",
":",
"'openid'",
")",
"client",
"(",
"issuer",
")",
".",
"post",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"\"/oauth2/#{auth_server_id}/v1/token\"",
"req",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/x-www-form-urlencoded'",
"req",
".",
"headers",
"[",
"'Authorization'",
"]",
"=",
"'Basic: '",
"+",
"Base64",
".",
"strict_encode64",
"(",
"\"#{client_id}:#{client_secret}\"",
")",
"req",
".",
"body",
"=",
"URI",
".",
"encode_www_form",
"username",
":",
"username",
",",
"password",
":",
"password",
",",
"scope",
":",
"scope",
",",
"grant_type",
":",
"'password'",
"end",
"end"
] | sign in user to get tokens | [
"sign",
"in",
"user",
"to",
"get",
"tokens"
] | 14ddc262bba35b9118fef40855faad908a6401c1 | https://github.com/damir/okta-jwt/blob/14ddc262bba35b9118fef40855faad908a6401c1/lib/okta/jwt.rb#L27-L34 |
3,651 | damir/okta-jwt | lib/okta/jwt.rb | Okta.Jwt.sign_in_client | def sign_in_client(client_id:, client_secret:, scope:)
client(issuer).post do |req|
req.url "/oauth2/#{auth_server_id}/v1/token"
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.headers['Authorization'] = 'Basic: ' + Base64.strict_encode64("#{client_id}:#{client_secret}")
req.body = URI.encode_www_form scope: scope, grant_type: 'client_credentials'
end
end | ruby | def sign_in_client(client_id:, client_secret:, scope:)
client(issuer).post do |req|
req.url "/oauth2/#{auth_server_id}/v1/token"
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.headers['Authorization'] = 'Basic: ' + Base64.strict_encode64("#{client_id}:#{client_secret}")
req.body = URI.encode_www_form scope: scope, grant_type: 'client_credentials'
end
end | [
"def",
"sign_in_client",
"(",
"client_id",
":",
",",
"client_secret",
":",
",",
"scope",
":",
")",
"client",
"(",
"issuer",
")",
".",
"post",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"\"/oauth2/#{auth_server_id}/v1/token\"",
"req",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/x-www-form-urlencoded'",
"req",
".",
"headers",
"[",
"'Authorization'",
"]",
"=",
"'Basic: '",
"+",
"Base64",
".",
"strict_encode64",
"(",
"\"#{client_id}:#{client_secret}\"",
")",
"req",
".",
"body",
"=",
"URI",
".",
"encode_www_form",
"scope",
":",
"scope",
",",
"grant_type",
":",
"'client_credentials'",
"end",
"end"
] | sign in client to get access_token | [
"sign",
"in",
"client",
"to",
"get",
"access_token"
] | 14ddc262bba35b9118fef40855faad908a6401c1 | https://github.com/damir/okta-jwt/blob/14ddc262bba35b9118fef40855faad908a6401c1/lib/okta/jwt.rb#L37-L44 |
3,652 | damir/okta-jwt | lib/okta/jwt.rb | Okta.Jwt.verify_token | def verify_token(token, issuer:, audience:, client_id:)
header, payload = token.split('.').first(2).map{|encoded| JSON.parse(Base64.decode64(encoded))}
# validate claims
raise InvalidToken.new('Invalid issuer') if payload['iss'] != issuer
raise InvalidToken.new('Invalid audience') if payload['aud'] != audience
raise InvalidToken.new('Invalid client') if !Array(client_id).include?(payload['cid'])
raise InvalidToken.new('Token is expired') if payload['exp'].to_i <= Time.now.to_i
# validate signature
jwk = JSON::JWK.new(get_jwk(header, payload))
JSON::JWT.decode(token, jwk.to_key)
end | ruby | def verify_token(token, issuer:, audience:, client_id:)
header, payload = token.split('.').first(2).map{|encoded| JSON.parse(Base64.decode64(encoded))}
# validate claims
raise InvalidToken.new('Invalid issuer') if payload['iss'] != issuer
raise InvalidToken.new('Invalid audience') if payload['aud'] != audience
raise InvalidToken.new('Invalid client') if !Array(client_id).include?(payload['cid'])
raise InvalidToken.new('Token is expired') if payload['exp'].to_i <= Time.now.to_i
# validate signature
jwk = JSON::JWK.new(get_jwk(header, payload))
JSON::JWT.decode(token, jwk.to_key)
end | [
"def",
"verify_token",
"(",
"token",
",",
"issuer",
":",
",",
"audience",
":",
",",
"client_id",
":",
")",
"header",
",",
"payload",
"=",
"token",
".",
"split",
"(",
"'.'",
")",
".",
"first",
"(",
"2",
")",
".",
"map",
"{",
"|",
"encoded",
"|",
"JSON",
".",
"parse",
"(",
"Base64",
".",
"decode64",
"(",
"encoded",
")",
")",
"}",
"# validate claims",
"raise",
"InvalidToken",
".",
"new",
"(",
"'Invalid issuer'",
")",
"if",
"payload",
"[",
"'iss'",
"]",
"!=",
"issuer",
"raise",
"InvalidToken",
".",
"new",
"(",
"'Invalid audience'",
")",
"if",
"payload",
"[",
"'aud'",
"]",
"!=",
"audience",
"raise",
"InvalidToken",
".",
"new",
"(",
"'Invalid client'",
")",
"if",
"!",
"Array",
"(",
"client_id",
")",
".",
"include?",
"(",
"payload",
"[",
"'cid'",
"]",
")",
"raise",
"InvalidToken",
".",
"new",
"(",
"'Token is expired'",
")",
"if",
"payload",
"[",
"'exp'",
"]",
".",
"to_i",
"<=",
"Time",
".",
"now",
".",
"to_i",
"# validate signature",
"jwk",
"=",
"JSON",
"::",
"JWK",
".",
"new",
"(",
"get_jwk",
"(",
"header",
",",
"payload",
")",
")",
"JSON",
"::",
"JWT",
".",
"decode",
"(",
"token",
",",
"jwk",
".",
"to_key",
")",
"end"
] | validate the token | [
"validate",
"the",
"token"
] | 14ddc262bba35b9118fef40855faad908a6401c1 | https://github.com/damir/okta-jwt/blob/14ddc262bba35b9118fef40855faad908a6401c1/lib/okta/jwt.rb#L47-L59 |
3,653 | damir/okta-jwt | lib/okta/jwt.rb | Okta.Jwt.get_jwk | def get_jwk(header, payload)
kid = header['kid']
# cache hit
return JWKS_CACHE[kid] if JWKS_CACHE[kid]
# fetch jwk
logger.info("[Okta::Jwt] Fetching public key: kid => #{kid} ...") if logger
jwks_response = client(payload['iss']).get do |req|
req.url get_metadata(payload)['jwks_uri']
end
jwk = JSON.parse(jwks_response.body)['keys'].find do |key|
key.dig('kid') == kid
end
# cache and return the key
jwk.tap{JWKS_CACHE[kid] = jwk}
end | ruby | def get_jwk(header, payload)
kid = header['kid']
# cache hit
return JWKS_CACHE[kid] if JWKS_CACHE[kid]
# fetch jwk
logger.info("[Okta::Jwt] Fetching public key: kid => #{kid} ...") if logger
jwks_response = client(payload['iss']).get do |req|
req.url get_metadata(payload)['jwks_uri']
end
jwk = JSON.parse(jwks_response.body)['keys'].find do |key|
key.dig('kid') == kid
end
# cache and return the key
jwk.tap{JWKS_CACHE[kid] = jwk}
end | [
"def",
"get_jwk",
"(",
"header",
",",
"payload",
")",
"kid",
"=",
"header",
"[",
"'kid'",
"]",
"# cache hit",
"return",
"JWKS_CACHE",
"[",
"kid",
"]",
"if",
"JWKS_CACHE",
"[",
"kid",
"]",
"# fetch jwk",
"logger",
".",
"info",
"(",
"\"[Okta::Jwt] Fetching public key: kid => #{kid} ...\"",
")",
"if",
"logger",
"jwks_response",
"=",
"client",
"(",
"payload",
"[",
"'iss'",
"]",
")",
".",
"get",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"get_metadata",
"(",
"payload",
")",
"[",
"'jwks_uri'",
"]",
"end",
"jwk",
"=",
"JSON",
".",
"parse",
"(",
"jwks_response",
".",
"body",
")",
"[",
"'keys'",
"]",
".",
"find",
"do",
"|",
"key",
"|",
"key",
".",
"dig",
"(",
"'kid'",
")",
"==",
"kid",
"end",
"# cache and return the key",
"jwk",
".",
"tap",
"{",
"JWKS_CACHE",
"[",
"kid",
"]",
"=",
"jwk",
"}",
"end"
] | extract public key from metadata's jwks_uri using kid | [
"extract",
"public",
"key",
"from",
"metadata",
"s",
"jwks_uri",
"using",
"kid"
] | 14ddc262bba35b9118fef40855faad908a6401c1 | https://github.com/damir/okta-jwt/blob/14ddc262bba35b9118fef40855faad908a6401c1/lib/okta/jwt.rb#L62-L79 |
3,654 | jmdeldin/cross_validation | lib/cross_validation/confusion_matrix.rb | CrossValidation.ConfusionMatrix.store | def store(actual, truth)
key = @keys_for.call(truth, actual)
if @values.key?(key)
@values[key] += 1
else
fail IndexError, "#{key} not found in confusion matrix"
end
self
end | ruby | def store(actual, truth)
key = @keys_for.call(truth, actual)
if @values.key?(key)
@values[key] += 1
else
fail IndexError, "#{key} not found in confusion matrix"
end
self
end | [
"def",
"store",
"(",
"actual",
",",
"truth",
")",
"key",
"=",
"@keys_for",
".",
"call",
"(",
"truth",
",",
"actual",
")",
"if",
"@values",
".",
"key?",
"(",
"key",
")",
"@values",
"[",
"key",
"]",
"+=",
"1",
"else",
"fail",
"IndexError",
",",
"\"#{key} not found in confusion matrix\"",
"end",
"self",
"end"
] | Save the result of classification
@param [Object] actual The classified value
@param [Object] truth The known, expected value
@return [self] | [
"Save",
"the",
"result",
"of",
"classification"
] | 048938169231f051c1612af608cde673ccc77529 | https://github.com/jmdeldin/cross_validation/blob/048938169231f051c1612af608cde673ccc77529/lib/cross_validation/confusion_matrix.rb#L36-L46 |
3,655 | jmdeldin/cross_validation | lib/cross_validation/confusion_matrix.rb | CrossValidation.ConfusionMatrix.fscore | def fscore(beta)
b2 = Float(beta**2)
((b2 + 1) * precision * recall) / (b2 * precision + recall)
end | ruby | def fscore(beta)
b2 = Float(beta**2)
((b2 + 1) * precision * recall) / (b2 * precision + recall)
end | [
"def",
"fscore",
"(",
"beta",
")",
"b2",
"=",
"Float",
"(",
"beta",
"**",
"2",
")",
"(",
"(",
"b2",
"+",
"1",
")",
"*",
"precision",
"*",
"recall",
")",
"/",
"(",
"b2",
"*",
"precision",
"+",
"recall",
")",
"end"
] | Returns the F-measure of the classifier's precision and recall.
@param [Float] beta Favor precision (<1), recall (>1), or both (1)
@return [Float] | [
"Returns",
"the",
"F",
"-",
"measure",
"of",
"the",
"classifier",
"s",
"precision",
"and",
"recall",
"."
] | 048938169231f051c1612af608cde673ccc77529 | https://github.com/jmdeldin/cross_validation/blob/048938169231f051c1612af608cde673ccc77529/lib/cross_validation/confusion_matrix.rb#L73-L76 |
3,656 | tario/evalhook | lib/evalhook.rb | EvalHook.HookHandler.packet | def packet(code)
@global_variable_name = nil
partialruby_packet = partialruby_context.packet(code)
@all_packets ||= []
newpacket = EvalHook::Packet.new(partialruby_packet, @global_variable_name)
@all_packets << newpacket
newpacket
end | ruby | def packet(code)
@global_variable_name = nil
partialruby_packet = partialruby_context.packet(code)
@all_packets ||= []
newpacket = EvalHook::Packet.new(partialruby_packet, @global_variable_name)
@all_packets << newpacket
newpacket
end | [
"def",
"packet",
"(",
"code",
")",
"@global_variable_name",
"=",
"nil",
"partialruby_packet",
"=",
"partialruby_context",
".",
"packet",
"(",
"code",
")",
"@all_packets",
"||=",
"[",
"]",
"newpacket",
"=",
"EvalHook",
"::",
"Packet",
".",
"new",
"(",
"partialruby_packet",
",",
"@global_variable_name",
")",
"@all_packets",
"<<",
"newpacket",
"newpacket",
"end"
] | Creates a packet of preprocessed ruby code to run it later
, useful to execute the same code repeatedly and avoid heavy
preprocessing of ruby code all the times.
See EvalHook::Packet for more information
Example:
hook_handler = HookHandler.new
pack = hook_handler.packet('print "hello world\n"')
10.times do
pack.run
end
pack.dispose | [
"Creates",
"a",
"packet",
"of",
"preprocessed",
"ruby",
"code",
"to",
"run",
"it",
"later",
"useful",
"to",
"execute",
"the",
"same",
"code",
"repeatedly",
"and",
"avoid",
"heavy",
"preprocessing",
"of",
"ruby",
"code",
"all",
"the",
"times",
"."
] | 56645703b4f648ae0ad1c56962bf9f786fe2d74d | https://github.com/tario/evalhook/blob/56645703b4f648ae0ad1c56962bf9f786fe2d74d/lib/evalhook.rb#L284-L292 |
3,657 | chrismoos/fastr | lib/fastr/application.rb | Fastr.Application.boot | def boot
Thread.new do
sleep 1 until EM.reactor_running?
begin
log.info "Loading application..."
app_init
load_settings
Fastr::Plugin.load(self)
load_app_classes
setup_router
setup_watcher
log.info "Application loaded successfully."
@booting = false
plugin_after_boot
rescue Exception => e
log.error "#{e}"
puts e.backtrace
log.fatal "Exiting due to previous errors..."
exit(1)
end
end
end | ruby | def boot
Thread.new do
sleep 1 until EM.reactor_running?
begin
log.info "Loading application..."
app_init
load_settings
Fastr::Plugin.load(self)
load_app_classes
setup_router
setup_watcher
log.info "Application loaded successfully."
@booting = false
plugin_after_boot
rescue Exception => e
log.error "#{e}"
puts e.backtrace
log.fatal "Exiting due to previous errors..."
exit(1)
end
end
end | [
"def",
"boot",
"Thread",
".",
"new",
"do",
"sleep",
"1",
"until",
"EM",
".",
"reactor_running?",
"begin",
"log",
".",
"info",
"\"Loading application...\"",
"app_init",
"load_settings",
"Fastr",
"::",
"Plugin",
".",
"load",
"(",
"self",
")",
"load_app_classes",
"setup_router",
"setup_watcher",
"log",
".",
"info",
"\"Application loaded successfully.\"",
"@booting",
"=",
"false",
"plugin_after_boot",
"rescue",
"Exception",
"=>",
"e",
"log",
".",
"error",
"\"#{e}\"",
"puts",
"e",
".",
"backtrace",
"log",
".",
"fatal",
"\"Exiting due to previous errors...\"",
"exit",
"(",
"1",
")",
"end",
"end",
"end"
] | This is used to initialize the application.
It runs in a thread because startup depends on EventMachine running | [
"This",
"is",
"used",
"to",
"initialize",
"the",
"application",
".",
"It",
"runs",
"in",
"a",
"thread",
"because",
"startup",
"depends",
"on",
"EventMachine",
"running"
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/application.rb#L65-L90 |
3,658 | chrismoos/fastr | lib/fastr/application.rb | Fastr.Application.load_app_classes | def load_app_classes
@@load_paths.each do |name, path|
log.debug "Loading #{name} classes..."
Dir["#{self.app_path}/#{path}"].each do |f|
log.debug "Loading: #{f}"
load(f)
end
end
end | ruby | def load_app_classes
@@load_paths.each do |name, path|
log.debug "Loading #{name} classes..."
Dir["#{self.app_path}/#{path}"].each do |f|
log.debug "Loading: #{f}"
load(f)
end
end
end | [
"def",
"load_app_classes",
"@@load_paths",
".",
"each",
"do",
"|",
"name",
",",
"path",
"|",
"log",
".",
"debug",
"\"Loading #{name} classes...\"",
"Dir",
"[",
"\"#{self.app_path}/#{path}\"",
"]",
".",
"each",
"do",
"|",
"f",
"|",
"log",
".",
"debug",
"\"Loading: #{f}\"",
"load",
"(",
"f",
")",
"end",
"end",
"end"
] | Loads all application classes. Called on startup. | [
"Loads",
"all",
"application",
"classes",
".",
"Called",
"on",
"startup",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/application.rb#L99-L108 |
3,659 | chrismoos/fastr | lib/fastr/application.rb | Fastr.Application.setup_watcher | def setup_watcher
this = self
Handler.send(:define_method, :app) do
this
end
@@load_paths.each do |name, path|
Dir["#{self.app_path}/#{path}"].each do |f|
EM.watch_file(f, Handler)
end
end
end | ruby | def setup_watcher
this = self
Handler.send(:define_method, :app) do
this
end
@@load_paths.each do |name, path|
Dir["#{self.app_path}/#{path}"].each do |f|
EM.watch_file(f, Handler)
end
end
end | [
"def",
"setup_watcher",
"this",
"=",
"self",
"Handler",
".",
"send",
"(",
":define_method",
",",
":app",
")",
"do",
"this",
"end",
"@@load_paths",
".",
"each",
"do",
"|",
"name",
",",
"path",
"|",
"Dir",
"[",
"\"#{self.app_path}/#{path}\"",
"]",
".",
"each",
"do",
"|",
"f",
"|",
"EM",
".",
"watch_file",
"(",
"f",
",",
"Handler",
")",
"end",
"end",
"end"
] | Watch for any file changes in the load paths. | [
"Watch",
"for",
"any",
"file",
"changes",
"in",
"the",
"load",
"paths",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/application.rb#L126-L137 |
3,660 | cldwalker/datomic-client | lib/datomic/client.rb | Datomic.Client.transact | def transact(dbname, data)
data = transmute_data(data)
RestClient.post(db_url(dbname) + "/", {"tx-data" => data},
:Accept => 'application/edn', &HANDLE_RESPONSE)
end | ruby | def transact(dbname, data)
data = transmute_data(data)
RestClient.post(db_url(dbname) + "/", {"tx-data" => data},
:Accept => 'application/edn', &HANDLE_RESPONSE)
end | [
"def",
"transact",
"(",
"dbname",
",",
"data",
")",
"data",
"=",
"transmute_data",
"(",
"data",
")",
"RestClient",
".",
"post",
"(",
"db_url",
"(",
"dbname",
")",
"+",
"\"/\"",
",",
"{",
"\"tx-data\"",
"=>",
"data",
"}",
",",
":Accept",
"=>",
"'application/edn'",
",",
"HANDLE_RESPONSE",
")",
"end"
] | Data can be a ruby data structure or a string representing clojure data | [
"Data",
"can",
"be",
"a",
"ruby",
"data",
"structure",
"or",
"a",
"string",
"representing",
"clojure",
"data"
] | 49147cc1a7241dfd38c381ff0301e5d83335ed9c | https://github.com/cldwalker/datomic-client/blob/49147cc1a7241dfd38c381ff0301e5d83335ed9c/lib/datomic/client.rb#L30-L34 |
3,661 | cldwalker/datomic-client | lib/datomic/client.rb | Datomic.Client.query | def query(query, args_or_dbname, params = {})
query = transmute_data(query)
args = args_or_dbname.is_a?(String) ? [db_alias(args_or_dbname)] : args_or_dbname
args = transmute_data(args)
get root_url("api/query"), params.merge(:q => query, :args => args)
end | ruby | def query(query, args_or_dbname, params = {})
query = transmute_data(query)
args = args_or_dbname.is_a?(String) ? [db_alias(args_or_dbname)] : args_or_dbname
args = transmute_data(args)
get root_url("api/query"), params.merge(:q => query, :args => args)
end | [
"def",
"query",
"(",
"query",
",",
"args_or_dbname",
",",
"params",
"=",
"{",
"}",
")",
"query",
"=",
"transmute_data",
"(",
"query",
")",
"args",
"=",
"args_or_dbname",
".",
"is_a?",
"(",
"String",
")",
"?",
"[",
"db_alias",
"(",
"args_or_dbname",
")",
"]",
":",
"args_or_dbname",
"args",
"=",
"transmute_data",
"(",
"args",
")",
"get",
"root_url",
"(",
"\"api/query\"",
")",
",",
"params",
".",
"merge",
"(",
":q",
"=>",
"query",
",",
":args",
"=>",
"args",
")",
"end"
] | Query can be a ruby data structure or a string representing clojure data
If the args_or_dbname is a String, it will be converted into one arg
pointing to that database. | [
"Query",
"can",
"be",
"a",
"ruby",
"data",
"structure",
"or",
"a",
"string",
"representing",
"clojure",
"data",
"If",
"the",
"args_or_dbname",
"is",
"a",
"String",
"it",
"will",
"be",
"converted",
"into",
"one",
"arg",
"pointing",
"to",
"that",
"database",
"."
] | 49147cc1a7241dfd38c381ff0301e5d83335ed9c | https://github.com/cldwalker/datomic-client/blob/49147cc1a7241dfd38c381ff0301e5d83335ed9c/lib/datomic/client.rb#L58-L63 |
3,662 | LatoTeam/lato_view | app/helpers/lato_view/application_helper.rb | LatoView.ApplicationHelper.view | def view(*names)
# mantain compatibility with old cells (lato_view 1.0)
if names.length === 1
puts "YOU ARE USING AND OLD VERSION OF CELLS. PLEASE CONSIDER TO UPDATE YOUR CODE"
old_cell = "LatoView::CellsV1::#{names.first.capitalize}::Cell".constantize
return old_cell
end
# return correct cell
cell_class = "LatoView::"
names.each do |name|
cell_class = "#{cell_class}#{name.capitalize}::"
end
cell_class = "#{cell_class}Cell".constantize
return cell_class
end | ruby | def view(*names)
# mantain compatibility with old cells (lato_view 1.0)
if names.length === 1
puts "YOU ARE USING AND OLD VERSION OF CELLS. PLEASE CONSIDER TO UPDATE YOUR CODE"
old_cell = "LatoView::CellsV1::#{names.first.capitalize}::Cell".constantize
return old_cell
end
# return correct cell
cell_class = "LatoView::"
names.each do |name|
cell_class = "#{cell_class}#{name.capitalize}::"
end
cell_class = "#{cell_class}Cell".constantize
return cell_class
end | [
"def",
"view",
"(",
"*",
"names",
")",
"# mantain compatibility with old cells (lato_view 1.0)",
"if",
"names",
".",
"length",
"===",
"1",
"puts",
"\"YOU ARE USING AND OLD VERSION OF CELLS. PLEASE CONSIDER TO UPDATE YOUR CODE\"",
"old_cell",
"=",
"\"LatoView::CellsV1::#{names.first.capitalize}::Cell\"",
".",
"constantize",
"return",
"old_cell",
"end",
"# return correct cell",
"cell_class",
"=",
"\"LatoView::\"",
"names",
".",
"each",
"do",
"|",
"name",
"|",
"cell_class",
"=",
"\"#{cell_class}#{name.capitalize}::\"",
"end",
"cell_class",
"=",
"\"#{cell_class}Cell\"",
".",
"constantize",
"return",
"cell_class",
"end"
] | This function render a cell set with params. | [
"This",
"function",
"render",
"a",
"cell",
"set",
"with",
"params",
"."
] | cd7fafe82e4cfdc7cd6d8533e695e76185dede09 | https://github.com/LatoTeam/lato_view/blob/cd7fafe82e4cfdc7cd6d8533e695e76185dede09/app/helpers/lato_view/application_helper.rb#L6-L20 |
3,663 | LatoTeam/lato_view | lib/lato_view/interface/images.rb | LatoView.Interface::Images.view_getSidebarLogo | def view_getSidebarLogo
return VIEW_SIDEBARLOGO if defined? VIEW_SIDEBARLOGO
dir = "#{Rails.root}/app/assets/images/lato/"
if File.exist?("#{dir}/sidebar_logo.svg")
return "lato/sidebar_logo.svg"
end
if File.exist?("#{dir}/sidebar_logo.png")
return "lato/sidebar_logo.png"
end
if File.exist?("#{dir}/sidebar_logo.jpg")
return "lato/sidebar_logo.jpg"
end
if File.exist?("#{dir}/sidebar_logo.gif")
return "lato/sidebar_logo.gif"
end
return view_getApplicationLogo
end | ruby | def view_getSidebarLogo
return VIEW_SIDEBARLOGO if defined? VIEW_SIDEBARLOGO
dir = "#{Rails.root}/app/assets/images/lato/"
if File.exist?("#{dir}/sidebar_logo.svg")
return "lato/sidebar_logo.svg"
end
if File.exist?("#{dir}/sidebar_logo.png")
return "lato/sidebar_logo.png"
end
if File.exist?("#{dir}/sidebar_logo.jpg")
return "lato/sidebar_logo.jpg"
end
if File.exist?("#{dir}/sidebar_logo.gif")
return "lato/sidebar_logo.gif"
end
return view_getApplicationLogo
end | [
"def",
"view_getSidebarLogo",
"return",
"VIEW_SIDEBARLOGO",
"if",
"defined?",
"VIEW_SIDEBARLOGO",
"dir",
"=",
"\"#{Rails.root}/app/assets/images/lato/\"",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/sidebar_logo.svg\"",
")",
"return",
"\"lato/sidebar_logo.svg\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/sidebar_logo.png\"",
")",
"return",
"\"lato/sidebar_logo.png\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/sidebar_logo.jpg\"",
")",
"return",
"\"lato/sidebar_logo.jpg\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/sidebar_logo.gif\"",
")",
"return",
"\"lato/sidebar_logo.gif\"",
"end",
"return",
"view_getApplicationLogo",
"end"
] | This function return the url of sidebar logo. | [
"This",
"function",
"return",
"the",
"url",
"of",
"sidebar",
"logo",
"."
] | cd7fafe82e4cfdc7cd6d8533e695e76185dede09 | https://github.com/LatoTeam/lato_view/blob/cd7fafe82e4cfdc7cd6d8533e695e76185dede09/lib/lato_view/interface/images.rb#L6-L22 |
3,664 | LatoTeam/lato_view | lib/lato_view/interface/images.rb | LatoView.Interface::Images.view_getLoginLogo | def view_getLoginLogo
return VIEW_LOGINLOGO if defined? VIEW_LOGINLOGO
dir = "#{Rails.root}/app/assets/images/lato/"
if File.exist?("#{dir}/login_logo.svg")
return "lato/login_logo.svg"
end
if File.exist?("#{dir}/login_logo.png")
return "lato/login_logo.png"
end
if File.exist?("#{dir}/login_logo.jpg")
return "lato/login_logo.jpg"
end
if File.exist?("#{dir}/login_logo.gif")
return "lato/login_logo.gif"
end
return view_getApplicationLogo
end | ruby | def view_getLoginLogo
return VIEW_LOGINLOGO if defined? VIEW_LOGINLOGO
dir = "#{Rails.root}/app/assets/images/lato/"
if File.exist?("#{dir}/login_logo.svg")
return "lato/login_logo.svg"
end
if File.exist?("#{dir}/login_logo.png")
return "lato/login_logo.png"
end
if File.exist?("#{dir}/login_logo.jpg")
return "lato/login_logo.jpg"
end
if File.exist?("#{dir}/login_logo.gif")
return "lato/login_logo.gif"
end
return view_getApplicationLogo
end | [
"def",
"view_getLoginLogo",
"return",
"VIEW_LOGINLOGO",
"if",
"defined?",
"VIEW_LOGINLOGO",
"dir",
"=",
"\"#{Rails.root}/app/assets/images/lato/\"",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/login_logo.svg\"",
")",
"return",
"\"lato/login_logo.svg\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/login_logo.png\"",
")",
"return",
"\"lato/login_logo.png\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/login_logo.jpg\"",
")",
"return",
"\"lato/login_logo.jpg\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/login_logo.gif\"",
")",
"return",
"\"lato/login_logo.gif\"",
"end",
"return",
"view_getApplicationLogo",
"end"
] | This function return the url of login logo. | [
"This",
"function",
"return",
"the",
"url",
"of",
"login",
"logo",
"."
] | cd7fafe82e4cfdc7cd6d8533e695e76185dede09 | https://github.com/LatoTeam/lato_view/blob/cd7fafe82e4cfdc7cd6d8533e695e76185dede09/lib/lato_view/interface/images.rb#L25-L41 |
3,665 | LatoTeam/lato_view | lib/lato_view/interface/images.rb | LatoView.Interface::Images.view_getApplicationLogo | def view_getApplicationLogo
return VIEW_APPLOGO if defined? VIEW_APPLOGO
dir = "#{Rails.root}/app/assets/images/lato/"
if File.exist?("#{dir}/logo.svg")
return "lato/logo.svg"
end
if File.exist?("#{dir}/logo.png")
return "lato/logo.png"
end
if File.exist?("#{dir}/logo.jpg")
return "lato/logo.jpg"
end
if File.exist?("#{dir}/logo.gif")
return "lato/logo.gif"
end
return false
end | ruby | def view_getApplicationLogo
return VIEW_APPLOGO if defined? VIEW_APPLOGO
dir = "#{Rails.root}/app/assets/images/lato/"
if File.exist?("#{dir}/logo.svg")
return "lato/logo.svg"
end
if File.exist?("#{dir}/logo.png")
return "lato/logo.png"
end
if File.exist?("#{dir}/logo.jpg")
return "lato/logo.jpg"
end
if File.exist?("#{dir}/logo.gif")
return "lato/logo.gif"
end
return false
end | [
"def",
"view_getApplicationLogo",
"return",
"VIEW_APPLOGO",
"if",
"defined?",
"VIEW_APPLOGO",
"dir",
"=",
"\"#{Rails.root}/app/assets/images/lato/\"",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/logo.svg\"",
")",
"return",
"\"lato/logo.svg\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/logo.png\"",
")",
"return",
"\"lato/logo.png\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/logo.jpg\"",
")",
"return",
"\"lato/logo.jpg\"",
"end",
"if",
"File",
".",
"exist?",
"(",
"\"#{dir}/logo.gif\"",
")",
"return",
"\"lato/logo.gif\"",
"end",
"return",
"false",
"end"
] | This function return the url of application logo. | [
"This",
"function",
"return",
"the",
"url",
"of",
"application",
"logo",
"."
] | cd7fafe82e4cfdc7cd6d8533e695e76185dede09 | https://github.com/LatoTeam/lato_view/blob/cd7fafe82e4cfdc7cd6d8533e695e76185dede09/lib/lato_view/interface/images.rb#L44-L60 |
3,666 | chrismoos/fastr | lib/fastr/dispatch.rb | Fastr.Dispatch.dispatch | def dispatch(env)
return [500, {'Content-Type' => 'text/plain'}, ["Server Not Ready"]] if @booting
begin
new_env = plugin_before_dispatch(env)
plugin_after_dispatch(new_env, do_dispatch(new_env))
rescue Exception => e
bt = e.backtrace.join("\n")
[500, {'Content-Type' => 'text/plain'}, ["Exception: #{e}\n\n#{bt}"]]
end
end | ruby | def dispatch(env)
return [500, {'Content-Type' => 'text/plain'}, ["Server Not Ready"]] if @booting
begin
new_env = plugin_before_dispatch(env)
plugin_after_dispatch(new_env, do_dispatch(new_env))
rescue Exception => e
bt = e.backtrace.join("\n")
[500, {'Content-Type' => 'text/plain'}, ["Exception: #{e}\n\n#{bt}"]]
end
end | [
"def",
"dispatch",
"(",
"env",
")",
"return",
"[",
"500",
",",
"{",
"'Content-Type'",
"=>",
"'text/plain'",
"}",
",",
"[",
"\"Server Not Ready\"",
"]",
"]",
"if",
"@booting",
"begin",
"new_env",
"=",
"plugin_before_dispatch",
"(",
"env",
")",
"plugin_after_dispatch",
"(",
"new_env",
",",
"do_dispatch",
"(",
"new_env",
")",
")",
"rescue",
"Exception",
"=>",
"e",
"bt",
"=",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
"[",
"500",
",",
"{",
"'Content-Type'",
"=>",
"'text/plain'",
"}",
",",
"[",
"\"Exception: #{e}\\n\\n#{bt}\"",
"]",
"]",
"end",
"end"
] | Convenience wrapper for do_dispatch
This is the heart of the server, called indirectly by a Rack aware server.
@param env [Hash]
@return [Array] | [
"Convenience",
"wrapper",
"for",
"do_dispatch",
"This",
"is",
"the",
"heart",
"of",
"the",
"server",
"called",
"indirectly",
"by",
"a",
"Rack",
"aware",
"server",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/dispatch.rb#L11-L21 |
3,667 | chrismoos/fastr | lib/fastr/dispatch.rb | Fastr.Dispatch.do_dispatch | def do_dispatch(env)
path = env['PATH_INFO']
# Try to serve a public file
ret = dispatch_public(env, path)
return ret if not ret.nil?
log.debug "Checking for routes that match: #{path}"
route = router.match(env)
if route.has_key? :ok
dispatch_controller(route, env)
else
[404, {"Content-Type" => "text/plain"}, ["404 Not Found: #{path}"]]
end
end | ruby | def do_dispatch(env)
path = env['PATH_INFO']
# Try to serve a public file
ret = dispatch_public(env, path)
return ret if not ret.nil?
log.debug "Checking for routes that match: #{path}"
route = router.match(env)
if route.has_key? :ok
dispatch_controller(route, env)
else
[404, {"Content-Type" => "text/plain"}, ["404 Not Found: #{path}"]]
end
end | [
"def",
"do_dispatch",
"(",
"env",
")",
"path",
"=",
"env",
"[",
"'PATH_INFO'",
"]",
"# Try to serve a public file",
"ret",
"=",
"dispatch_public",
"(",
"env",
",",
"path",
")",
"return",
"ret",
"if",
"not",
"ret",
".",
"nil?",
"log",
".",
"debug",
"\"Checking for routes that match: #{path}\"",
"route",
"=",
"router",
".",
"match",
"(",
"env",
")",
"if",
"route",
".",
"has_key?",
":ok",
"dispatch_controller",
"(",
"route",
",",
"env",
")",
"else",
"[",
"404",
",",
"{",
"\"Content-Type\"",
"=>",
"\"text/plain\"",
"}",
",",
"[",
"\"404 Not Found: #{path}\"",
"]",
"]",
"end",
"end"
] | Route, instantiate controller, return response from controller's action. | [
"Route",
"instantiate",
"controller",
"return",
"response",
"from",
"controller",
"s",
"action",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/dispatch.rb#L24-L39 |
3,668 | chrismoos/fastr | lib/fastr/dispatch.rb | Fastr.Dispatch.setup_controller | def setup_controller(controller, env, vars)
controller.env = env
controller.headers = {}
setup_controller_params(controller, env, vars)
controller.cookies = Fastr::HTTP.parse_cookies(env)
controller.app = self
end | ruby | def setup_controller(controller, env, vars)
controller.env = env
controller.headers = {}
setup_controller_params(controller, env, vars)
controller.cookies = Fastr::HTTP.parse_cookies(env)
controller.app = self
end | [
"def",
"setup_controller",
"(",
"controller",
",",
"env",
",",
"vars",
")",
"controller",
".",
"env",
"=",
"env",
"controller",
".",
"headers",
"=",
"{",
"}",
"setup_controller_params",
"(",
"controller",
",",
"env",
",",
"vars",
")",
"controller",
".",
"cookies",
"=",
"Fastr",
"::",
"HTTP",
".",
"parse_cookies",
"(",
"env",
")",
"controller",
".",
"app",
"=",
"self",
"end"
] | Sets up a controller for a request. | [
"Sets",
"up",
"a",
"controller",
"for",
"a",
"request",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/dispatch.rb#L95-L103 |
3,669 | chrismoos/fastr | lib/fastr/dispatch.rb | Fastr.Dispatch.setup_controller_params | def setup_controller_params(controller, env, vars)
if Fastr::HTTP.method?(env, :get)
controller.get_params = Fastr::HTTP.parse_query_string(env['QUERY_STRING'])
controller.params = controller.get_params.merge(vars)
elsif Fastr::HTTP.method?(env, :post)
controller.post_params = {}
controller.post_params = Fastr::HTTP.parse_query_string(env['rack.input'].read) if env['rack.input']
controller.params = controller.post_params.merge(vars)
else
controller.params = vars
end
end | ruby | def setup_controller_params(controller, env, vars)
if Fastr::HTTP.method?(env, :get)
controller.get_params = Fastr::HTTP.parse_query_string(env['QUERY_STRING'])
controller.params = controller.get_params.merge(vars)
elsif Fastr::HTTP.method?(env, :post)
controller.post_params = {}
controller.post_params = Fastr::HTTP.parse_query_string(env['rack.input'].read) if env['rack.input']
controller.params = controller.post_params.merge(vars)
else
controller.params = vars
end
end | [
"def",
"setup_controller_params",
"(",
"controller",
",",
"env",
",",
"vars",
")",
"if",
"Fastr",
"::",
"HTTP",
".",
"method?",
"(",
"env",
",",
":get",
")",
"controller",
".",
"get_params",
"=",
"Fastr",
"::",
"HTTP",
".",
"parse_query_string",
"(",
"env",
"[",
"'QUERY_STRING'",
"]",
")",
"controller",
".",
"params",
"=",
"controller",
".",
"get_params",
".",
"merge",
"(",
"vars",
")",
"elsif",
"Fastr",
"::",
"HTTP",
".",
"method?",
"(",
"env",
",",
":post",
")",
"controller",
".",
"post_params",
"=",
"{",
"}",
"controller",
".",
"post_params",
"=",
"Fastr",
"::",
"HTTP",
".",
"parse_query_string",
"(",
"env",
"[",
"'rack.input'",
"]",
".",
"read",
")",
"if",
"env",
"[",
"'rack.input'",
"]",
"controller",
".",
"params",
"=",
"controller",
".",
"post_params",
".",
"merge",
"(",
"vars",
")",
"else",
"controller",
".",
"params",
"=",
"vars",
"end",
"end"
] | Populate the parameters based on the HTTP method. | [
"Populate",
"the",
"parameters",
"based",
"on",
"the",
"HTTP",
"method",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/dispatch.rb#L106-L117 |
3,670 | chrismoos/fastr | lib/fastr/dispatch.rb | Fastr.Dispatch.plugin_before_dispatch | def plugin_before_dispatch(env)
new_env = env
self.plugins.each do |plugin|
if plugin.respond_to? :before_dispatch
new_env = plugin.send(:before_dispatch, self, env)
end
end
new_env
end | ruby | def plugin_before_dispatch(env)
new_env = env
self.plugins.each do |plugin|
if plugin.respond_to? :before_dispatch
new_env = plugin.send(:before_dispatch, self, env)
end
end
new_env
end | [
"def",
"plugin_before_dispatch",
"(",
"env",
")",
"new_env",
"=",
"env",
"self",
".",
"plugins",
".",
"each",
"do",
"|",
"plugin",
"|",
"if",
"plugin",
".",
"respond_to?",
":before_dispatch",
"new_env",
"=",
"plugin",
".",
"send",
"(",
":before_dispatch",
",",
"self",
",",
"env",
")",
"end",
"end",
"new_env",
"end"
] | Runs before_dispatch in all plugins.
@param env [Hash]
@return [Hash] | [
"Runs",
"before_dispatch",
"in",
"all",
"plugins",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/dispatch.rb#L123-L133 |
3,671 | chrismoos/fastr | lib/fastr/dispatch.rb | Fastr.Dispatch.plugin_after_dispatch | def plugin_after_dispatch(env, response)
new_response = response
self.plugins.each do |plugin|
if plugin.respond_to? :after_dispatch
new_response = plugin.send(:after_dispatch, self, env, response)
end
end
new_response
end | ruby | def plugin_after_dispatch(env, response)
new_response = response
self.plugins.each do |plugin|
if plugin.respond_to? :after_dispatch
new_response = plugin.send(:after_dispatch, self, env, response)
end
end
new_response
end | [
"def",
"plugin_after_dispatch",
"(",
"env",
",",
"response",
")",
"new_response",
"=",
"response",
"self",
".",
"plugins",
".",
"each",
"do",
"|",
"plugin",
"|",
"if",
"plugin",
".",
"respond_to?",
":after_dispatch",
"new_response",
"=",
"plugin",
".",
"send",
"(",
":after_dispatch",
",",
"self",
",",
"env",
",",
"response",
")",
"end",
"end",
"new_response",
"end"
] | Runs after_dispatch in all plugins.
@param env [Hash]
@return [Hash] | [
"Runs",
"after_dispatch",
"in",
"all",
"plugins",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/dispatch.rb#L139-L149 |
3,672 | jonahoffline/filepreviews-ruby | lib/filepreviews/cli.rb | Filepreviews.CLI.options | def options(opts)
opts.version = Filepreviews::VERSION
opts.banner = BANNER
opts.set_program_name 'Filepreviews.io'
opts.on('-k', '--api_key [key]', String,
'use API key from Filepreviews.io') do |api_key|
Filepreviews.api_key = api_key
end
opts.on('-s', '--secret_key [key]', String,
'use Secret key from Filepreviews.io') do |secret_key|
Filepreviews.secret_key = secret_key
end
opts.on('-m', '--metadata', 'load metadata response') do
@metadata = true
end
opts.on_tail('-v', '--version', 'display the version of Filepreviews') do
puts opts.version
exit
end
opts.on_tail('-h', '--help', 'print this help') do
puts opts.help
exit
end
end | ruby | def options(opts)
opts.version = Filepreviews::VERSION
opts.banner = BANNER
opts.set_program_name 'Filepreviews.io'
opts.on('-k', '--api_key [key]', String,
'use API key from Filepreviews.io') do |api_key|
Filepreviews.api_key = api_key
end
opts.on('-s', '--secret_key [key]', String,
'use Secret key from Filepreviews.io') do |secret_key|
Filepreviews.secret_key = secret_key
end
opts.on('-m', '--metadata', 'load metadata response') do
@metadata = true
end
opts.on_tail('-v', '--version', 'display the version of Filepreviews') do
puts opts.version
exit
end
opts.on_tail('-h', '--help', 'print this help') do
puts opts.help
exit
end
end | [
"def",
"options",
"(",
"opts",
")",
"opts",
".",
"version",
"=",
"Filepreviews",
"::",
"VERSION",
"opts",
".",
"banner",
"=",
"BANNER",
"opts",
".",
"set_program_name",
"'Filepreviews.io'",
"opts",
".",
"on",
"(",
"'-k'",
",",
"'--api_key [key]'",
",",
"String",
",",
"'use API key from Filepreviews.io'",
")",
"do",
"|",
"api_key",
"|",
"Filepreviews",
".",
"api_key",
"=",
"api_key",
"end",
"opts",
".",
"on",
"(",
"'-s'",
",",
"'--secret_key [key]'",
",",
"String",
",",
"'use Secret key from Filepreviews.io'",
")",
"do",
"|",
"secret_key",
"|",
"Filepreviews",
".",
"secret_key",
"=",
"secret_key",
"end",
"opts",
".",
"on",
"(",
"'-m'",
",",
"'--metadata'",
",",
"'load metadata response'",
")",
"do",
"@metadata",
"=",
"true",
"end",
"opts",
".",
"on_tail",
"(",
"'-v'",
",",
"'--version'",
",",
"'display the version of Filepreviews'",
")",
"do",
"puts",
"opts",
".",
"version",
"exit",
"end",
"opts",
".",
"on_tail",
"(",
"'-h'",
",",
"'--help'",
",",
"'print this help'",
")",
"do",
"puts",
"opts",
".",
"help",
"exit",
"end",
"end"
] | Passes arguments from ARGV and sets metadata flag
@param args [Array<String>] The command-line arguments
Configures the arguments for the command
@param opts [OptionParser] | [
"Passes",
"arguments",
"from",
"ARGV",
"and",
"sets",
"metadata",
"flag"
] | b7357e1f8125626d6c451191acadf91c7a9ef6de | https://github.com/jonahoffline/filepreviews-ruby/blob/b7357e1f8125626d6c451191acadf91c7a9ef6de/lib/filepreviews/cli.rb#L22-L50 |
3,673 | jonahoffline/filepreviews-ruby | lib/filepreviews/cli.rb | Filepreviews.CLI.parse | def parse
opts = OptionParser.new(&method(:options))
opts.parse!(@args)
return opts.help if @args.last.nil?
file_preview = Filepreviews.generate(@args.last)
@metadata ? file_preview.metadata(js: true) : file_preview
end | ruby | def parse
opts = OptionParser.new(&method(:options))
opts.parse!(@args)
return opts.help if @args.last.nil?
file_preview = Filepreviews.generate(@args.last)
@metadata ? file_preview.metadata(js: true) : file_preview
end | [
"def",
"parse",
"opts",
"=",
"OptionParser",
".",
"new",
"(",
"method",
"(",
":options",
")",
")",
"opts",
".",
"parse!",
"(",
"@args",
")",
"return",
"opts",
".",
"help",
"if",
"@args",
".",
"last",
".",
"nil?",
"file_preview",
"=",
"Filepreviews",
".",
"generate",
"(",
"@args",
".",
"last",
")",
"@metadata",
"?",
"file_preview",
".",
"metadata",
"(",
"js",
":",
"true",
")",
":",
"file_preview",
"end"
] | Parses options sent from command-line | [
"Parses",
"options",
"sent",
"from",
"command",
"-",
"line"
] | b7357e1f8125626d6c451191acadf91c7a9ef6de | https://github.com/jonahoffline/filepreviews-ruby/blob/b7357e1f8125626d6c451191acadf91c7a9ef6de/lib/filepreviews/cli.rb#L53-L60 |
3,674 | shideneyu/ownlan | lib/ownlan/config.rb | Ownlan.Configuration.source_mac | def source_mac
@source_mac ||= if self.victim_ip
::ServiceObjects::NetworkInformation.self_mac(interface)
else
gateway_ip = ServiceObjects::NetworkInformation.gateway_ip
mac = ::Ownlan::Attack::Base.new(self).ip_to_mac(gateway_ip)
end
end | ruby | def source_mac
@source_mac ||= if self.victim_ip
::ServiceObjects::NetworkInformation.self_mac(interface)
else
gateway_ip = ServiceObjects::NetworkInformation.gateway_ip
mac = ::Ownlan::Attack::Base.new(self).ip_to_mac(gateway_ip)
end
end | [
"def",
"source_mac",
"@source_mac",
"||=",
"if",
"self",
".",
"victim_ip",
"::",
"ServiceObjects",
"::",
"NetworkInformation",
".",
"self_mac",
"(",
"interface",
")",
"else",
"gateway_ip",
"=",
"ServiceObjects",
"::",
"NetworkInformation",
".",
"gateway_ip",
"mac",
"=",
"::",
"Ownlan",
"::",
"Attack",
"::",
"Base",
".",
"new",
"(",
"self",
")",
".",
"ip_to_mac",
"(",
"gateway_ip",
")",
"end",
"end"
] | Create a new instance.
@return [Ownlan::Configuration] | [
"Create",
"a",
"new",
"instance",
"."
] | 2815a8be08e0fdbf18f9e422776d8d354a60a902 | https://github.com/shideneyu/ownlan/blob/2815a8be08e0fdbf18f9e422776d8d354a60a902/lib/ownlan/config.rb#L45-L52 |
3,675 | esumbar/passphrase | lib/passphrase/diceware_random.rb | Passphrase.DicewareRandom.die_rolls | def die_rolls(number_of_words)
# The Diceware method specifies five rolls of the die for each word.
die_rolls_per_word = 5
total_die_rolls = number_of_words * die_rolls_per_word
die_roll_sequence = generate_random_numbers(total_die_rolls, 6, 1)
group_die_rolls(die_roll_sequence, number_of_words, die_rolls_per_word)
end | ruby | def die_rolls(number_of_words)
# The Diceware method specifies five rolls of the die for each word.
die_rolls_per_word = 5
total_die_rolls = number_of_words * die_rolls_per_word
die_roll_sequence = generate_random_numbers(total_die_rolls, 6, 1)
group_die_rolls(die_roll_sequence, number_of_words, die_rolls_per_word)
end | [
"def",
"die_rolls",
"(",
"number_of_words",
")",
"# The Diceware method specifies five rolls of the die for each word.",
"die_rolls_per_word",
"=",
"5",
"total_die_rolls",
"=",
"number_of_words",
"*",
"die_rolls_per_word",
"die_roll_sequence",
"=",
"generate_random_numbers",
"(",
"total_die_rolls",
",",
"6",
",",
"1",
")",
"group_die_rolls",
"(",
"die_roll_sequence",
",",
"number_of_words",
",",
"die_rolls_per_word",
")",
"end"
] | Returns an array of strings where each string comprises five numeric
characters, each one representing one roll of a die. The number of
elements in the array equals the number of words specified for the
passphrase.
@param number_of_words [Integer] the desired number of words in the
passphrase
@return [Array<String>] an array of strings each one of which represents
five rolls of a die | [
"Returns",
"an",
"array",
"of",
"strings",
"where",
"each",
"string",
"comprises",
"five",
"numeric",
"characters",
"each",
"one",
"representing",
"one",
"roll",
"of",
"a",
"die",
".",
"The",
"number",
"of",
"elements",
"in",
"the",
"array",
"equals",
"the",
"number",
"of",
"words",
"specified",
"for",
"the",
"passphrase",
"."
] | 5faaa6dcf71f31bc6acad6f683f581408e0b5c32 | https://github.com/esumbar/passphrase/blob/5faaa6dcf71f31bc6acad6f683f581408e0b5c32/lib/passphrase/diceware_random.rb#L46-L52 |
3,676 | jonahoffline/filepreviews-ruby | lib/filepreviews/utils.rb | Filepreviews.Utils.process_params | def process_params(params)
parameters = { url: CGI.unescape(params.url) }
if params.metadata
parameters[:metadata] = extract_metadata(params.metadata)
end
parameters
end | ruby | def process_params(params)
parameters = { url: CGI.unescape(params.url) }
if params.metadata
parameters[:metadata] = extract_metadata(params.metadata)
end
parameters
end | [
"def",
"process_params",
"(",
"params",
")",
"parameters",
"=",
"{",
"url",
":",
"CGI",
".",
"unescape",
"(",
"params",
".",
"url",
")",
"}",
"if",
"params",
".",
"metadata",
"parameters",
"[",
":metadata",
"]",
"=",
"extract_metadata",
"(",
"params",
".",
"metadata",
")",
"end",
"parameters",
"end"
] | Returns processed options and url as parameters
@param params [Hash<Symbol>] :url and :metadata
@return [Hash<Symbol>] processed parameters for http request | [
"Returns",
"processed",
"options",
"and",
"url",
"as",
"parameters"
] | b7357e1f8125626d6c451191acadf91c7a9ef6de | https://github.com/jonahoffline/filepreviews-ruby/blob/b7357e1f8125626d6c451191acadf91c7a9ef6de/lib/filepreviews/utils.rb#L41-L49 |
3,677 | chrismoos/fastr | lib/fastr/router.rb | Fastr.Router.match | def match(env)
self.routes.each do |info|
# If the route didn't specify method(s) to limit by, then all HTTP methods are valid.
# If the route specified method(s), we check the request's HTTP method and validate
# that it exists in that list.
next unless info[:methods].nil? or info[:methods].include?(env["REQUEST_METHOD"].downcase.to_sym)
match = env['PATH_INFO'].match(info[:regex])
# See if a route matches
if not match.nil?
# Map any parameters in our matched string
vars = {}
info[:vars].each_index do |i|
var = info[:vars][i]
vars[var] = match[i+1]
end
return {:ok => vars.merge!(info[:hash]) }
end
end
{:error => :not_found}
end | ruby | def match(env)
self.routes.each do |info|
# If the route didn't specify method(s) to limit by, then all HTTP methods are valid.
# If the route specified method(s), we check the request's HTTP method and validate
# that it exists in that list.
next unless info[:methods].nil? or info[:methods].include?(env["REQUEST_METHOD"].downcase.to_sym)
match = env['PATH_INFO'].match(info[:regex])
# See if a route matches
if not match.nil?
# Map any parameters in our matched string
vars = {}
info[:vars].each_index do |i|
var = info[:vars][i]
vars[var] = match[i+1]
end
return {:ok => vars.merge!(info[:hash]) }
end
end
{:error => :not_found}
end | [
"def",
"match",
"(",
"env",
")",
"self",
".",
"routes",
".",
"each",
"do",
"|",
"info",
"|",
"# If the route didn't specify method(s) to limit by, then all HTTP methods are valid.",
"# If the route specified method(s), we check the request's HTTP method and validate",
"# that it exists in that list.",
"next",
"unless",
"info",
"[",
":methods",
"]",
".",
"nil?",
"or",
"info",
"[",
":methods",
"]",
".",
"include?",
"(",
"env",
"[",
"\"REQUEST_METHOD\"",
"]",
".",
"downcase",
".",
"to_sym",
")",
"match",
"=",
"env",
"[",
"'PATH_INFO'",
"]",
".",
"match",
"(",
"info",
"[",
":regex",
"]",
")",
"# See if a route matches",
"if",
"not",
"match",
".",
"nil?",
"# Map any parameters in our matched string",
"vars",
"=",
"{",
"}",
"info",
"[",
":vars",
"]",
".",
"each_index",
"do",
"|",
"i",
"|",
"var",
"=",
"info",
"[",
":vars",
"]",
"[",
"i",
"]",
"vars",
"[",
"var",
"]",
"=",
"match",
"[",
"i",
"+",
"1",
"]",
"end",
"return",
"{",
":ok",
"=>",
"vars",
".",
"merge!",
"(",
"info",
"[",
":hash",
"]",
")",
"}",
"end",
"end",
"{",
":error",
"=>",
":not_found",
"}",
"end"
] | Searches the routes for a match given a Rack env.
{#match} looks in the {#routes} to find a match.
This method looks at PATH_INFO in +env+ to get the current request's path.
== Return
No Match:
{:error => :not_found}
Match:
{:ok => {:controller => 'controller', :action => 'action', :var => 'value'}}
@param env [Hash]
@return [Hash] | [
"Searches",
"the",
"routes",
"for",
"a",
"match",
"given",
"a",
"Rack",
"env",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/router.rb#L51-L77 |
3,678 | chrismoos/fastr | lib/fastr/router.rb | Fastr.Router.for | def for(path, *args)
arg = args[0]
log.debug "Adding route, path: #{path}, args: #{args.inspect}"
match = get_regex_for_route(path, arg)
hash = get_to_hash(arg)
route_info = {:regex => match[:regex], :args => arg, :vars => match[:vars], :hash => hash}
# Add the HTTP methods for this route if they exist in options
route_info[:methods] = arg[:methods] if not arg.nil? and arg.has_key? :methods
self.routes.push(route_info)
end | ruby | def for(path, *args)
arg = args[0]
log.debug "Adding route, path: #{path}, args: #{args.inspect}"
match = get_regex_for_route(path, arg)
hash = get_to_hash(arg)
route_info = {:regex => match[:regex], :args => arg, :vars => match[:vars], :hash => hash}
# Add the HTTP methods for this route if they exist in options
route_info[:methods] = arg[:methods] if not arg.nil? and arg.has_key? :methods
self.routes.push(route_info)
end | [
"def",
"for",
"(",
"path",
",",
"*",
"args",
")",
"arg",
"=",
"args",
"[",
"0",
"]",
"log",
".",
"debug",
"\"Adding route, path: #{path}, args: #{args.inspect}\"",
"match",
"=",
"get_regex_for_route",
"(",
"path",
",",
"arg",
")",
"hash",
"=",
"get_to_hash",
"(",
"arg",
")",
"route_info",
"=",
"{",
":regex",
"=>",
"match",
"[",
":regex",
"]",
",",
":args",
"=>",
"arg",
",",
":vars",
"=>",
"match",
"[",
":vars",
"]",
",",
":hash",
"=>",
"hash",
"}",
"# Add the HTTP methods for this route if they exist in options",
"route_info",
"[",
":methods",
"]",
"=",
"arg",
"[",
":methods",
"]",
"if",
"not",
"arg",
".",
"nil?",
"and",
"arg",
".",
"has_key?",
":methods",
"self",
".",
"routes",
".",
"push",
"(",
"route_info",
")",
"end"
] | Adds a route for a path and arguments.
@param path [String]
@param args [Array] | [
"Adds",
"a",
"route",
"for",
"a",
"path",
"and",
"arguments",
"."
] | aa3c72221983092b8964894ad0c97f60ea029d6e | https://github.com/chrismoos/fastr/blob/aa3c72221983092b8964894ad0c97f60ea029d6e/lib/fastr/router.rb#L92-L104 |
3,679 | delano/uri-redis | lib/uri/redis.rb | URI.Redis.conf | def conf
hsh = {
:host => host,
:port => port,
:db => db
}.merge parse_query(query)
hsh[:password] = password if password
hsh
end | ruby | def conf
hsh = {
:host => host,
:port => port,
:db => db
}.merge parse_query(query)
hsh[:password] = password if password
hsh
end | [
"def",
"conf",
"hsh",
"=",
"{",
":host",
"=>",
"host",
",",
":port",
"=>",
"port",
",",
":db",
"=>",
"db",
"}",
".",
"merge",
"parse_query",
"(",
"query",
")",
"hsh",
"[",
":password",
"]",
"=",
"password",
"if",
"password",
"hsh",
"end"
] | Returns a hash suitable for sending to Redis.new.
The hash is generated from the host, port, db and
password from the URI as well as any query vars.
e.g.
uri = URI.parse "redis://127.0.0.1/6/?timeout=5"
uri.conf
# => {:db=>6, :timeout=>"5", :host=>"127.0.0.1", :port=>6379} | [
"Returns",
"a",
"hash",
"suitable",
"for",
"sending",
"to",
"Redis",
".",
"new",
".",
"The",
"hash",
"is",
"generated",
"from",
"the",
"host",
"port",
"db",
"and",
"password",
"from",
"the",
"URI",
"as",
"well",
"as",
"any",
"query",
"vars",
"."
] | 4264526318117264df09fd6f5a42ee605f1db0fd | https://github.com/delano/uri-redis/blob/4264526318117264df09fd6f5a42ee605f1db0fd/lib/uri/redis.rb#L55-L63 |
3,680 | LatoTeam/lato_view | lib/lato_view/interface/themes.rb | LatoView.Interface::Themes.view_getCurrentTemplateName | def view_getCurrentTemplateName
return VIEW_CURRENTTEMPLATENAME if defined? VIEW_CURRENTTEMPLATENAME
directory = core_getCacheDirectory
if File.exist? "#{directory}/view.yml"
# accedo al view.yml
config = YAML.load(
File.read(File.expand_path("#{directory}/view.yml", __FILE__))
)
# verifico esistenza dati
if !config || !config['template']
return false
end
# verifico che il template sia valido
unless VIEW_TEMPLATES.include? config['template']
raise 'Template value is not correct on view.yml config file' and return false
end
# ritorno nome template
return config['template']
else
return false
end
end | ruby | def view_getCurrentTemplateName
return VIEW_CURRENTTEMPLATENAME if defined? VIEW_CURRENTTEMPLATENAME
directory = core_getCacheDirectory
if File.exist? "#{directory}/view.yml"
# accedo al view.yml
config = YAML.load(
File.read(File.expand_path("#{directory}/view.yml", __FILE__))
)
# verifico esistenza dati
if !config || !config['template']
return false
end
# verifico che il template sia valido
unless VIEW_TEMPLATES.include? config['template']
raise 'Template value is not correct on view.yml config file' and return false
end
# ritorno nome template
return config['template']
else
return false
end
end | [
"def",
"view_getCurrentTemplateName",
"return",
"VIEW_CURRENTTEMPLATENAME",
"if",
"defined?",
"VIEW_CURRENTTEMPLATENAME",
"directory",
"=",
"core_getCacheDirectory",
"if",
"File",
".",
"exist?",
"\"#{directory}/view.yml\"",
"# accedo al view.yml",
"config",
"=",
"YAML",
".",
"load",
"(",
"File",
".",
"read",
"(",
"File",
".",
"expand_path",
"(",
"\"#{directory}/view.yml\"",
",",
"__FILE__",
")",
")",
")",
"# verifico esistenza dati",
"if",
"!",
"config",
"||",
"!",
"config",
"[",
"'template'",
"]",
"return",
"false",
"end",
"# verifico che il template sia valido",
"unless",
"VIEW_TEMPLATES",
".",
"include?",
"config",
"[",
"'template'",
"]",
"raise",
"'Template value is not correct on view.yml config file'",
"and",
"return",
"false",
"end",
"# ritorno nome template",
"return",
"config",
"[",
"'template'",
"]",
"else",
"return",
"false",
"end",
"end"
] | This function return the name of the current theme used for the
application. | [
"This",
"function",
"return",
"the",
"name",
"of",
"the",
"current",
"theme",
"used",
"for",
"the",
"application",
"."
] | cd7fafe82e4cfdc7cd6d8533e695e76185dede09 | https://github.com/LatoTeam/lato_view/blob/cd7fafe82e4cfdc7cd6d8533e695e76185dede09/lib/lato_view/interface/themes.rb#L7-L28 |
3,681 | timrogers/rapgenius | lib/rapgenius/artist.rb | RapGenius.Artist.songs | def songs(options = {page: 1})
songs_url = "/artists/#{@id}/songs/?page=#{options[:page]}"
fetch(songs_url)["response"]["songs"].map do |song|
Song.new(
artist: Artist.new(
name: song["primary_artist"]["name"],
id: song["primary_artist"]["id"],
type: :primary
),
title: song["title"],
id: song["id"]
)
end
end | ruby | def songs(options = {page: 1})
songs_url = "/artists/#{@id}/songs/?page=#{options[:page]}"
fetch(songs_url)["response"]["songs"].map do |song|
Song.new(
artist: Artist.new(
name: song["primary_artist"]["name"],
id: song["primary_artist"]["id"],
type: :primary
),
title: song["title"],
id: song["id"]
)
end
end | [
"def",
"songs",
"(",
"options",
"=",
"{",
"page",
":",
"1",
"}",
")",
"songs_url",
"=",
"\"/artists/#{@id}/songs/?page=#{options[:page]}\"",
"fetch",
"(",
"songs_url",
")",
"[",
"\"response\"",
"]",
"[",
"\"songs\"",
"]",
".",
"map",
"do",
"|",
"song",
"|",
"Song",
".",
"new",
"(",
"artist",
":",
"Artist",
".",
"new",
"(",
"name",
":",
"song",
"[",
"\"primary_artist\"",
"]",
"[",
"\"name\"",
"]",
",",
"id",
":",
"song",
"[",
"\"primary_artist\"",
"]",
"[",
"\"id\"",
"]",
",",
"type",
":",
":primary",
")",
",",
"title",
":",
"song",
"[",
"\"title\"",
"]",
",",
"id",
":",
"song",
"[",
"\"id\"",
"]",
")",
"end",
"end"
] | You seem to be able to load 20 songs at a time for an artist. I haven't
found a way to vary the number you get back from the query, but you can
paginate through in blocks of 20 songs. | [
"You",
"seem",
"to",
"be",
"able",
"to",
"load",
"20",
"songs",
"at",
"a",
"time",
"for",
"an",
"artist",
".",
"I",
"haven",
"t",
"found",
"a",
"way",
"to",
"vary",
"the",
"number",
"you",
"get",
"back",
"from",
"the",
"query",
"but",
"you",
"can",
"paginate",
"through",
"in",
"blocks",
"of",
"20",
"songs",
"."
] | 6c1c9f4e98828ae12ae2deea2570e30b31d1e6b7 | https://github.com/timrogers/rapgenius/blob/6c1c9f4e98828ae12ae2deea2570e30b31d1e6b7/lib/rapgenius/artist.rb#L40-L54 |
3,682 | LatoTeam/lato_view | lib/lato_view/interface/assets.rb | LatoView.Interface::Assets.view_getApplicationsAssetsItems | def view_getApplicationsAssetsItems
return VIEW_APPASSETS if defined? VIEW_APPASSETS
# inizializzo la lista delle voci della navbar
assets = []
directory = core_getCacheDirectory
if File.exist? "#{directory}/view.yml"
# accedo al view.yml
config = YAML.load(
File.read(File.expand_path("#{directory}/view.yml", __FILE__))
)
# estraggo i dati dallo yaml
data = getConfigAssets(config)
# aggiungo i dati nella risposta
data.each do |single_asset|
assets.push(single_asset)
end
end
# ritorno il risultato
return assets
end | ruby | def view_getApplicationsAssetsItems
return VIEW_APPASSETS if defined? VIEW_APPASSETS
# inizializzo la lista delle voci della navbar
assets = []
directory = core_getCacheDirectory
if File.exist? "#{directory}/view.yml"
# accedo al view.yml
config = YAML.load(
File.read(File.expand_path("#{directory}/view.yml", __FILE__))
)
# estraggo i dati dallo yaml
data = getConfigAssets(config)
# aggiungo i dati nella risposta
data.each do |single_asset|
assets.push(single_asset)
end
end
# ritorno il risultato
return assets
end | [
"def",
"view_getApplicationsAssetsItems",
"return",
"VIEW_APPASSETS",
"if",
"defined?",
"VIEW_APPASSETS",
"# inizializzo la lista delle voci della navbar",
"assets",
"=",
"[",
"]",
"directory",
"=",
"core_getCacheDirectory",
"if",
"File",
".",
"exist?",
"\"#{directory}/view.yml\"",
"# accedo al view.yml",
"config",
"=",
"YAML",
".",
"load",
"(",
"File",
".",
"read",
"(",
"File",
".",
"expand_path",
"(",
"\"#{directory}/view.yml\"",
",",
"__FILE__",
")",
")",
")",
"# estraggo i dati dallo yaml",
"data",
"=",
"getConfigAssets",
"(",
"config",
")",
"# aggiungo i dati nella risposta",
"data",
".",
"each",
"do",
"|",
"single_asset",
"|",
"assets",
".",
"push",
"(",
"single_asset",
")",
"end",
"end",
"# ritorno il risultato",
"return",
"assets",
"end"
] | This function return an array of url of assets from the main application. | [
"This",
"function",
"return",
"an",
"array",
"of",
"url",
"of",
"assets",
"from",
"the",
"main",
"application",
"."
] | cd7fafe82e4cfdc7cd6d8533e695e76185dede09 | https://github.com/LatoTeam/lato_view/blob/cd7fafe82e4cfdc7cd6d8533e695e76185dede09/lib/lato_view/interface/assets.rb#L51-L70 |
3,683 | jonahoffline/filepreviews-ruby | lib/filepreviews/http.rb | Filepreviews.HTTP.default_connection | def default_connection(url = BASE_URL, debug = false)
Faraday.new(url: url) do |conn|
conn.adapter :typhoeus
conn.headers[:user_agent] = USER_AGENT
conn.headers[:content_type] = 'application/json'
configure_api_auth_header(conn.headers)
configure_logger(conn) if debug
end
end | ruby | def default_connection(url = BASE_URL, debug = false)
Faraday.new(url: url) do |conn|
conn.adapter :typhoeus
conn.headers[:user_agent] = USER_AGENT
conn.headers[:content_type] = 'application/json'
configure_api_auth_header(conn.headers)
configure_logger(conn) if debug
end
end | [
"def",
"default_connection",
"(",
"url",
"=",
"BASE_URL",
",",
"debug",
"=",
"false",
")",
"Faraday",
".",
"new",
"(",
"url",
":",
"url",
")",
"do",
"|",
"conn",
"|",
"conn",
".",
"adapter",
":typhoeus",
"conn",
".",
"headers",
"[",
":user_agent",
"]",
"=",
"USER_AGENT",
"conn",
".",
"headers",
"[",
":content_type",
"]",
"=",
"'application/json'",
"configure_api_auth_header",
"(",
"conn",
".",
"headers",
")",
"configure_logger",
"(",
"conn",
")",
"if",
"debug",
"end",
"end"
] | Returns custom Typhoeus connection configuration
@param url [String] API url to be used as base
@param debug [Boolean] flag to log responses into STDOUT
@return [Typhoeus::Connection] configured http client for requests to API | [
"Returns",
"custom",
"Typhoeus",
"connection",
"configuration"
] | b7357e1f8125626d6c451191acadf91c7a9ef6de | https://github.com/jonahoffline/filepreviews-ruby/blob/b7357e1f8125626d6c451191acadf91c7a9ef6de/lib/filepreviews/http.rb#L22-L30 |
3,684 | jonahoffline/filepreviews-ruby | lib/filepreviews/http.rb | Filepreviews.HTTP.prepare_request | def prepare_request(params)
request = process_params(params)
request.store(:sizes, [extract_size(params.size)]) if params.size
request.store(:format, params.format) if params.format
request.store(:data, params.data) if params.data
request.store(:uploader, params.uploader) if params.uploader
request.store(:pages, params.pages) if params.pages
request
end | ruby | def prepare_request(params)
request = process_params(params)
request.store(:sizes, [extract_size(params.size)]) if params.size
request.store(:format, params.format) if params.format
request.store(:data, params.data) if params.data
request.store(:uploader, params.uploader) if params.uploader
request.store(:pages, params.pages) if params.pages
request
end | [
"def",
"prepare_request",
"(",
"params",
")",
"request",
"=",
"process_params",
"(",
"params",
")",
"request",
".",
"store",
"(",
":sizes",
",",
"[",
"extract_size",
"(",
"params",
".",
"size",
")",
"]",
")",
"if",
"params",
".",
"size",
"request",
".",
"store",
"(",
":format",
",",
"params",
".",
"format",
")",
"if",
"params",
".",
"format",
"request",
".",
"store",
"(",
":data",
",",
"params",
".",
"data",
")",
"if",
"params",
".",
"data",
"request",
".",
"store",
"(",
":uploader",
",",
"params",
".",
"uploader",
")",
"if",
"params",
".",
"uploader",
"request",
".",
"store",
"(",
":pages",
",",
"params",
".",
"pages",
")",
"if",
"params",
".",
"pages",
"request",
"end"
] | Returns processed metadata, and image attributes params
@param params [Hash<Symbol>] metadata and image attributes
@return [Hash<Symbol>] processed parameters | [
"Returns",
"processed",
"metadata",
"and",
"image",
"attributes",
"params"
] | b7357e1f8125626d6c451191acadf91c7a9ef6de | https://github.com/jonahoffline/filepreviews-ruby/blob/b7357e1f8125626d6c451191acadf91c7a9ef6de/lib/filepreviews/http.rb#L63-L71 |
3,685 | jonahoffline/filepreviews-ruby | lib/filepreviews/http.rb | Filepreviews.HTTP.fetch | def fetch(params, endpoint_path = 'previews')
options = prepare_request(params)
response = default_connection(BASE_URL, params.debug)
.post do |req|
req.url("/v2/#{endpoint_path}/")
req.body = JSON.generate(options)
end
parse(response.body)
end | ruby | def fetch(params, endpoint_path = 'previews')
options = prepare_request(params)
response = default_connection(BASE_URL, params.debug)
.post do |req|
req.url("/v2/#{endpoint_path}/")
req.body = JSON.generate(options)
end
parse(response.body)
end | [
"def",
"fetch",
"(",
"params",
",",
"endpoint_path",
"=",
"'previews'",
")",
"options",
"=",
"prepare_request",
"(",
"params",
")",
"response",
"=",
"default_connection",
"(",
"BASE_URL",
",",
"params",
".",
"debug",
")",
".",
"post",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"(",
"\"/v2/#{endpoint_path}/\"",
")",
"req",
".",
"body",
"=",
"JSON",
".",
"generate",
"(",
"options",
")",
"end",
"parse",
"(",
"response",
".",
"body",
")",
"end"
] | Returns parsed response from API
@return [Filepreviews::Response] json response as callable methods | [
"Returns",
"parsed",
"response",
"from",
"API"
] | b7357e1f8125626d6c451191acadf91c7a9ef6de | https://github.com/jonahoffline/filepreviews-ruby/blob/b7357e1f8125626d6c451191acadf91c7a9ef6de/lib/filepreviews/http.rb#L75-L84 |
3,686 | lloeki/ruby-skyjam | lib/skyjam/client.rb | SkyJam.Client.loadalltracks | def loadalltracks
uri = URI(@service_url + 'loadalltracks')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri.path)
req.set_form_data('u' => 0, 'xt' => @cookie)
req['Authorization'] = 'GoogleLogin auth=%s' % @auth
res = http.request(req)
unless res.is_a? Net::HTTPSuccess
fail Error, 'loadalltracks failed: #{res.code}'
end
JSON.parse(res.body)
end | ruby | def loadalltracks
uri = URI(@service_url + 'loadalltracks')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri.path)
req.set_form_data('u' => 0, 'xt' => @cookie)
req['Authorization'] = 'GoogleLogin auth=%s' % @auth
res = http.request(req)
unless res.is_a? Net::HTTPSuccess
fail Error, 'loadalltracks failed: #{res.code}'
end
JSON.parse(res.body)
end | [
"def",
"loadalltracks",
"uri",
"=",
"URI",
"(",
"@service_url",
"+",
"'loadalltracks'",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"http",
".",
"use_ssl",
"=",
"true",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"path",
")",
"req",
".",
"set_form_data",
"(",
"'u'",
"=>",
"0",
",",
"'xt'",
"=>",
"@cookie",
")",
"req",
"[",
"'Authorization'",
"]",
"=",
"'GoogleLogin auth=%s'",
"%",
"@auth",
"res",
"=",
"http",
".",
"request",
"(",
"req",
")",
"unless",
"res",
".",
"is_a?",
"Net",
"::",
"HTTPSuccess",
"fail",
"Error",
",",
"'loadalltracks failed: #{res.code}'",
"end",
"JSON",
".",
"parse",
"(",
"res",
".",
"body",
")",
"end"
] | Web Client API | [
"Web",
"Client",
"API"
] | af435d56303b6a0790d299f4aa627d83c650a8b3 | https://github.com/lloeki/ruby-skyjam/blob/af435d56303b6a0790d299f4aa627d83c650a8b3/lib/skyjam/client.rb#L66-L82 |
3,687 | lloeki/ruby-skyjam | lib/skyjam/client.rb | SkyJam.Client.mac_addr | def mac_addr
case RUBY_PLATFORM
when /darwin/
if (m = `ifconfig en0`.match(/ether (\S{17})/))
m[1].upcase
end
when /linux/
devices = Dir['/sys/class/net/*/address'].reject { |a| a =~ %r{/lo/} }
dev = devices.first
File.read(dev).chomp.upcase
end
end | ruby | def mac_addr
case RUBY_PLATFORM
when /darwin/
if (m = `ifconfig en0`.match(/ether (\S{17})/))
m[1].upcase
end
when /linux/
devices = Dir['/sys/class/net/*/address'].reject { |a| a =~ %r{/lo/} }
dev = devices.first
File.read(dev).chomp.upcase
end
end | [
"def",
"mac_addr",
"case",
"RUBY_PLATFORM",
"when",
"/",
"/",
"if",
"(",
"m",
"=",
"`",
"`",
".",
"match",
"(",
"/",
"\\S",
"/",
")",
")",
"m",
"[",
"1",
"]",
".",
"upcase",
"end",
"when",
"/",
"/",
"devices",
"=",
"Dir",
"[",
"'/sys/class/net/*/address'",
"]",
".",
"reject",
"{",
"|",
"a",
"|",
"a",
"=~",
"%r{",
"}",
"}",
"dev",
"=",
"devices",
".",
"first",
"File",
".",
"read",
"(",
"dev",
")",
".",
"chomp",
".",
"upcase",
"end",
"end"
] | MusicManager Uploader identification | [
"MusicManager",
"Uploader",
"identification"
] | af435d56303b6a0790d299f4aa627d83c650a8b3 | https://github.com/lloeki/ruby-skyjam/blob/af435d56303b6a0790d299f4aa627d83c650a8b3/lib/skyjam/client.rb#L163-L174 |
3,688 | lbeder/rediska | lib/rediska/driver.rb | Rediska.Driver.zscan_each | def zscan_each(key, *args, &block)
data_type_check(key, ZSet)
return [] unless data[key]
return to_enum(:zscan_each, key, options) unless block_given?
cursor = 0
loop do
cursor, values = zscan(key, cursor, options)
values.each(&block)
break if cursor == '0'
end
end | ruby | def zscan_each(key, *args, &block)
data_type_check(key, ZSet)
return [] unless data[key]
return to_enum(:zscan_each, key, options) unless block_given?
cursor = 0
loop do
cursor, values = zscan(key, cursor, options)
values.each(&block)
break if cursor == '0'
end
end | [
"def",
"zscan_each",
"(",
"key",
",",
"*",
"args",
",",
"&",
"block",
")",
"data_type_check",
"(",
"key",
",",
"ZSet",
")",
"return",
"[",
"]",
"unless",
"data",
"[",
"key",
"]",
"return",
"to_enum",
"(",
":zscan_each",
",",
"key",
",",
"options",
")",
"unless",
"block_given?",
"cursor",
"=",
"0",
"loop",
"do",
"cursor",
",",
"values",
"=",
"zscan",
"(",
"key",
",",
"cursor",
",",
"options",
")",
"values",
".",
"each",
"(",
"block",
")",
"break",
"if",
"cursor",
"==",
"'0'",
"end",
"end"
] | Originally from redis-rb | [
"Originally",
"from",
"redis",
"-",
"rb"
] | b02c1558c4aef0f5bbbac06f1216359dafe6d36c | https://github.com/lbeder/rediska/blob/b02c1558c4aef0f5bbbac06f1216359dafe6d36c/lib/rediska/driver.rb#L1128-L1139 |
3,689 | philou/storexplore | lib/storexplore/walker_page.rb | Storexplore.WalkerPage.get_all | def get_all(selector, separator)
elements = @mechanize_page.search(selector)
throw_if_empty(elements, "elements", selector)
(elements.map &:text).join(separator)
end | ruby | def get_all(selector, separator)
elements = @mechanize_page.search(selector)
throw_if_empty(elements, "elements", selector)
(elements.map &:text).join(separator)
end | [
"def",
"get_all",
"(",
"selector",
",",
"separator",
")",
"elements",
"=",
"@mechanize_page",
".",
"search",
"(",
"selector",
")",
"throw_if_empty",
"(",
"elements",
",",
"\"elements\"",
",",
"selector",
")",
"(",
"elements",
".",
"map",
":text",
")",
".",
"join",
"(",
"separator",
")",
"end"
] | String with the text of all matching elements, separated by separator. | [
"String",
"with",
"the",
"text",
"of",
"all",
"matching",
"elements",
"separated",
"by",
"separator",
"."
] | 475ff912bb79142a0f5f2ac2092f66c605176af5 | https://github.com/philou/storexplore/blob/475ff912bb79142a0f5f2ac2092f66c605176af5/lib/storexplore/walker_page.rb#L58-L63 |
3,690 | hybridgroup/taskmapper | lib/taskmapper/helper.rb | TaskMapper::Provider.Helper.easy_finder | def easy_finder(api, symbol, options, at_index = 0)
if api.is_a? Class
return api if options.length == 0 and symbol == :first
options.insert(at_index, symbol) if options[at_index].is_a?(Hash)
api.find(*options)
else
raise TaskMapper::Exception.new("#{Helper.name}::#{this_method} method must be implemented by the provider")
end
end | ruby | def easy_finder(api, symbol, options, at_index = 0)
if api.is_a? Class
return api if options.length == 0 and symbol == :first
options.insert(at_index, symbol) if options[at_index].is_a?(Hash)
api.find(*options)
else
raise TaskMapper::Exception.new("#{Helper.name}::#{this_method} method must be implemented by the provider")
end
end | [
"def",
"easy_finder",
"(",
"api",
",",
"symbol",
",",
"options",
",",
"at_index",
"=",
"0",
")",
"if",
"api",
".",
"is_a?",
"Class",
"return",
"api",
"if",
"options",
".",
"length",
"==",
"0",
"and",
"symbol",
"==",
":first",
"options",
".",
"insert",
"(",
"at_index",
",",
"symbol",
")",
"if",
"options",
"[",
"at_index",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"api",
".",
"find",
"(",
"options",
")",
"else",
"raise",
"TaskMapper",
"::",
"Exception",
".",
"new",
"(",
"\"#{Helper.name}::#{this_method} method must be implemented by the provider\"",
")",
"end",
"end"
] | A helper method for easy finding | [
"A",
"helper",
"method",
"for",
"easy",
"finding"
] | 80af7b43d955e7a9f360fec3b4137e2cd1b418d6 | https://github.com/hybridgroup/taskmapper/blob/80af7b43d955e7a9f360fec3b4137e2cd1b418d6/lib/taskmapper/helper.rb#L13-L21 |
3,691 | hybridgroup/taskmapper | lib/taskmapper/helper.rb | TaskMapper::Provider.Helper.search_by_attribute | def search_by_attribute(things, options = {}, limit = 1000)
things.find_all do |thing|
options.inject(true) do |memo, kv|
break unless memo
key, value = kv
begin
memo &= thing.send(key) == value
rescue NoMethodError
memo = false
end
memo
end and (limit -= 1) > 0
end
end | ruby | def search_by_attribute(things, options = {}, limit = 1000)
things.find_all do |thing|
options.inject(true) do |memo, kv|
break unless memo
key, value = kv
begin
memo &= thing.send(key) == value
rescue NoMethodError
memo = false
end
memo
end and (limit -= 1) > 0
end
end | [
"def",
"search_by_attribute",
"(",
"things",
",",
"options",
"=",
"{",
"}",
",",
"limit",
"=",
"1000",
")",
"things",
".",
"find_all",
"do",
"|",
"thing",
"|",
"options",
".",
"inject",
"(",
"true",
")",
"do",
"|",
"memo",
",",
"kv",
"|",
"break",
"unless",
"memo",
"key",
",",
"value",
"=",
"kv",
"begin",
"memo",
"&=",
"thing",
".",
"send",
"(",
"key",
")",
"==",
"value",
"rescue",
"NoMethodError",
"memo",
"=",
"false",
"end",
"memo",
"end",
"and",
"(",
"limit",
"-=",
"1",
")",
">",
"0",
"end",
"end"
] | Goes through all the things and returns results that match the options attributes hash | [
"Goes",
"through",
"all",
"the",
"things",
"and",
"returns",
"results",
"that",
"match",
"the",
"options",
"attributes",
"hash"
] | 80af7b43d955e7a9f360fec3b4137e2cd1b418d6 | https://github.com/hybridgroup/taskmapper/blob/80af7b43d955e7a9f360fec3b4137e2cd1b418d6/lib/taskmapper/helper.rb#L34-L47 |
3,692 | glebpom/daemonizer | lib/daemonizer/stats.rb | Daemonizer::Stats.MemoryStats.determine_private_dirty_rss | def determine_private_dirty_rss(pid)
total = 0
File.read("/proc/#{pid}/smaps").split("\n").each do |line|
line =~ /^(Private)_Dirty: +(\d+)/
if $2
total += $2.to_i
end
end
if total == 0
return nil
else
return total
end
rescue Errno::EACCES, Errno::ENOENT
return nil
end | ruby | def determine_private_dirty_rss(pid)
total = 0
File.read("/proc/#{pid}/smaps").split("\n").each do |line|
line =~ /^(Private)_Dirty: +(\d+)/
if $2
total += $2.to_i
end
end
if total == 0
return nil
else
return total
end
rescue Errno::EACCES, Errno::ENOENT
return nil
end | [
"def",
"determine_private_dirty_rss",
"(",
"pid",
")",
"total",
"=",
"0",
"File",
".",
"read",
"(",
"\"/proc/#{pid}/smaps\"",
")",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"each",
"do",
"|",
"line",
"|",
"line",
"=~",
"/",
"\\d",
"/",
"if",
"$2",
"total",
"+=",
"$2",
".",
"to_i",
"end",
"end",
"if",
"total",
"==",
"0",
"return",
"nil",
"else",
"return",
"total",
"end",
"rescue",
"Errno",
"::",
"EACCES",
",",
"Errno",
"::",
"ENOENT",
"return",
"nil",
"end"
] | Returns the private dirty RSS for the given process, in KB. | [
"Returns",
"the",
"private",
"dirty",
"RSS",
"for",
"the",
"given",
"process",
"in",
"KB",
"."
] | 18b5ba213fb7dfb03acd25dac6af20860added57 | https://github.com/glebpom/daemonizer/blob/18b5ba213fb7dfb03acd25dac6af20860added57/lib/daemonizer/stats.rb#L255-L270 |
3,693 | bmuller/ankusa | lib/ankusa/classifier.rb | Ankusa.Classifier.train | def train(klass, text)
th = TextHash.new(text)
th.each { |word, count|
@storage.incr_word_count klass, word, count
yield word, count if block_given?
}
@storage.incr_total_word_count klass, th.word_count
doccount = (text.kind_of? Array) ? text.length : 1
@storage.incr_doc_count klass, doccount
@classnames << klass unless @classnames.include? klass
# cache is now dirty of these vars
@doc_count_totals = nil
@vocab_sizes = nil
th
end | ruby | def train(klass, text)
th = TextHash.new(text)
th.each { |word, count|
@storage.incr_word_count klass, word, count
yield word, count if block_given?
}
@storage.incr_total_word_count klass, th.word_count
doccount = (text.kind_of? Array) ? text.length : 1
@storage.incr_doc_count klass, doccount
@classnames << klass unless @classnames.include? klass
# cache is now dirty of these vars
@doc_count_totals = nil
@vocab_sizes = nil
th
end | [
"def",
"train",
"(",
"klass",
",",
"text",
")",
"th",
"=",
"TextHash",
".",
"new",
"(",
"text",
")",
"th",
".",
"each",
"{",
"|",
"word",
",",
"count",
"|",
"@storage",
".",
"incr_word_count",
"klass",
",",
"word",
",",
"count",
"yield",
"word",
",",
"count",
"if",
"block_given?",
"}",
"@storage",
".",
"incr_total_word_count",
"klass",
",",
"th",
".",
"word_count",
"doccount",
"=",
"(",
"text",
".",
"kind_of?",
"Array",
")",
"?",
"text",
".",
"length",
":",
"1",
"@storage",
".",
"incr_doc_count",
"klass",
",",
"doccount",
"@classnames",
"<<",
"klass",
"unless",
"@classnames",
".",
"include?",
"klass",
"# cache is now dirty of these vars",
"@doc_count_totals",
"=",
"nil",
"@vocab_sizes",
"=",
"nil",
"th",
"end"
] | text can be either an array of strings or a string
klass is a symbol | [
"text",
"can",
"be",
"either",
"an",
"array",
"of",
"strings",
"or",
"a",
"string",
"klass",
"is",
"a",
"symbol"
] | af946f130aa63532fdb67d8382cfaaf81b38027b | https://github.com/bmuller/ankusa/blob/af946f130aa63532fdb67d8382cfaaf81b38027b/lib/ankusa/classifier.rb#L14-L28 |
3,694 | danielb2/trakt | lib/trakt/show.rb | Trakt.Show.unseen | def unseen(title)
all = seasons title
episodes_per_season = {}
episodes_to_remove = []
all.each do |season_info|
season_num = season_info['season']
next if season_num == 0 # dont need to remove specials
episodes = season_info['episodes']
1.upto(episodes) do |episode|
episodes_to_remove << { season: season_num, episode: episode }
end
end
episode_unseen tvdb_id: title, episodes: episodes_to_remove
end | ruby | def unseen(title)
all = seasons title
episodes_per_season = {}
episodes_to_remove = []
all.each do |season_info|
season_num = season_info['season']
next if season_num == 0 # dont need to remove specials
episodes = season_info['episodes']
1.upto(episodes) do |episode|
episodes_to_remove << { season: season_num, episode: episode }
end
end
episode_unseen tvdb_id: title, episodes: episodes_to_remove
end | [
"def",
"unseen",
"(",
"title",
")",
"all",
"=",
"seasons",
"title",
"episodes_per_season",
"=",
"{",
"}",
"episodes_to_remove",
"=",
"[",
"]",
"all",
".",
"each",
"do",
"|",
"season_info",
"|",
"season_num",
"=",
"season_info",
"[",
"'season'",
"]",
"next",
"if",
"season_num",
"==",
"0",
"# dont need to remove specials",
"episodes",
"=",
"season_info",
"[",
"'episodes'",
"]",
"1",
".",
"upto",
"(",
"episodes",
")",
"do",
"|",
"episode",
"|",
"episodes_to_remove",
"<<",
"{",
"season",
":",
"season_num",
",",
"episode",
":",
"episode",
"}",
"end",
"end",
"episode_unseen",
"tvdb_id",
":",
"title",
",",
"episodes",
":",
"episodes_to_remove",
"end"
] | need to use thetvdb id here since the slug can't be used for unseen | [
"need",
"to",
"use",
"thetvdb",
"id",
"here",
"since",
"the",
"slug",
"can",
"t",
"be",
"used",
"for",
"unseen"
] | e49634903626fb9ad6cf14f2f20a232bc7ecf2f4 | https://github.com/danielb2/trakt/blob/e49634903626fb9ad6cf14f2f20a232bc7ecf2f4/lib/trakt/show.rb#L17-L30 |
3,695 | mbleigh/colorist | lib/colorist/color.rb | Colorist.Color.+ | def +(other_color)
other_color = Colorist::Color.from(other_color)
color = self.dup
color.r += other_color.r
color.g += other_color.g
color.b += other_color.b
color
end | ruby | def +(other_color)
other_color = Colorist::Color.from(other_color)
color = self.dup
color.r += other_color.r
color.g += other_color.g
color.b += other_color.b
color
end | [
"def",
"+",
"(",
"other_color",
")",
"other_color",
"=",
"Colorist",
"::",
"Color",
".",
"from",
"(",
"other_color",
")",
"color",
"=",
"self",
".",
"dup",
"color",
".",
"r",
"+=",
"other_color",
".",
"r",
"color",
".",
"g",
"+=",
"other_color",
".",
"g",
"color",
".",
"b",
"+=",
"other_color",
".",
"b",
"color",
"end"
] | Create a duplicate of this color.
Add the individual RGB values of two colors together. You
may also use an equivalent numeric or string color representation.
Examples:
gray = Colorist::Color.new(0x333333)
gray + "#300" # => <Color #663333>
gray + 0x000000 # => <Color #333333>
white = "white".to_color
gray + white # => <Color #ffffff> | [
"Create",
"a",
"duplicate",
"of",
"this",
"color",
".",
"Add",
"the",
"individual",
"RGB",
"values",
"of",
"two",
"colors",
"together",
".",
"You",
"may",
"also",
"use",
"an",
"equivalent",
"numeric",
"or",
"string",
"color",
"representation",
"."
] | c2a8dcc06d5ac9bbfc48ca86ae58ee7bef5de927 | https://github.com/mbleigh/colorist/blob/c2a8dcc06d5ac9bbfc48ca86ae58ee7bef5de927/lib/colorist/color.rb#L285-L292 |
3,696 | mbleigh/colorist | lib/colorist/color.rb | Colorist.Color.to_hsv | def to_hsv
red, green, blue = *[r, g, b].collect {|x| x / 255.0}
max = [red, green, blue].max
min = [red, green, blue].min
if min == max
hue = 0
elsif max == red
hue = 60 * ((green - blue) / (max - min))
elsif max == green
hue = 60 * ((blue - red) / (max - min)) + 120
elsif max == blue
hue = 60 * ((red - green) / (max - min)) + 240
end
saturation = (max == 0) ? 0 : (max - min) / max
[hue % 360, saturation, max]
end | ruby | def to_hsv
red, green, blue = *[r, g, b].collect {|x| x / 255.0}
max = [red, green, blue].max
min = [red, green, blue].min
if min == max
hue = 0
elsif max == red
hue = 60 * ((green - blue) / (max - min))
elsif max == green
hue = 60 * ((blue - red) / (max - min)) + 120
elsif max == blue
hue = 60 * ((red - green) / (max - min)) + 240
end
saturation = (max == 0) ? 0 : (max - min) / max
[hue % 360, saturation, max]
end | [
"def",
"to_hsv",
"red",
",",
"green",
",",
"blue",
"=",
"[",
"r",
",",
"g",
",",
"b",
"]",
".",
"collect",
"{",
"|",
"x",
"|",
"x",
"/",
"255.0",
"}",
"max",
"=",
"[",
"red",
",",
"green",
",",
"blue",
"]",
".",
"max",
"min",
"=",
"[",
"red",
",",
"green",
",",
"blue",
"]",
".",
"min",
"if",
"min",
"==",
"max",
"hue",
"=",
"0",
"elsif",
"max",
"==",
"red",
"hue",
"=",
"60",
"*",
"(",
"(",
"green",
"-",
"blue",
")",
"/",
"(",
"max",
"-",
"min",
")",
")",
"elsif",
"max",
"==",
"green",
"hue",
"=",
"60",
"*",
"(",
"(",
"blue",
"-",
"red",
")",
"/",
"(",
"max",
"-",
"min",
")",
")",
"+",
"120",
"elsif",
"max",
"==",
"blue",
"hue",
"=",
"60",
"*",
"(",
"(",
"red",
"-",
"green",
")",
"/",
"(",
"max",
"-",
"min",
")",
")",
"+",
"240",
"end",
"saturation",
"=",
"(",
"max",
"==",
"0",
")",
"?",
"0",
":",
"(",
"max",
"-",
"min",
")",
"/",
"max",
"[",
"hue",
"%",
"360",
",",
"saturation",
",",
"max",
"]",
"end"
] | Returns an array of the hue, saturation and value of the color.
Hue will range from 0-359, hue and saturation will be between 0 and 1. | [
"Returns",
"an",
"array",
"of",
"the",
"hue",
"saturation",
"and",
"value",
"of",
"the",
"color",
".",
"Hue",
"will",
"range",
"from",
"0",
"-",
"359",
"hue",
"and",
"saturation",
"will",
"be",
"between",
"0",
"and",
"1",
"."
] | c2a8dcc06d5ac9bbfc48ca86ae58ee7bef5de927 | https://github.com/mbleigh/colorist/blob/c2a8dcc06d5ac9bbfc48ca86ae58ee7bef5de927/lib/colorist/color.rb#L362-L379 |
3,697 | mbleigh/colorist | lib/colorist/color.rb | Colorist.Color.gradient_to | def gradient_to(color, steps = 10)
color_to = Colorist::Color.from(color)
red = color_to.r - r
green = color_to.g - g
blue = color_to.b - b
result = (1..(steps - 3)).to_a.collect do |step|
percentage = step.to_f / (steps - 1)
Color.from_rgb(r + (red * percentage), g + (green * percentage), b + (blue * percentage))
end
# Add first and last colors to result, avoiding uneccessary calculation and rounding errors
result.unshift(self.dup)
result.push(color.dup)
result
end | ruby | def gradient_to(color, steps = 10)
color_to = Colorist::Color.from(color)
red = color_to.r - r
green = color_to.g - g
blue = color_to.b - b
result = (1..(steps - 3)).to_a.collect do |step|
percentage = step.to_f / (steps - 1)
Color.from_rgb(r + (red * percentage), g + (green * percentage), b + (blue * percentage))
end
# Add first and last colors to result, avoiding uneccessary calculation and rounding errors
result.unshift(self.dup)
result.push(color.dup)
result
end | [
"def",
"gradient_to",
"(",
"color",
",",
"steps",
"=",
"10",
")",
"color_to",
"=",
"Colorist",
"::",
"Color",
".",
"from",
"(",
"color",
")",
"red",
"=",
"color_to",
".",
"r",
"-",
"r",
"green",
"=",
"color_to",
".",
"g",
"-",
"g",
"blue",
"=",
"color_to",
".",
"b",
"-",
"b",
"result",
"=",
"(",
"1",
"..",
"(",
"steps",
"-",
"3",
")",
")",
".",
"to_a",
".",
"collect",
"do",
"|",
"step",
"|",
"percentage",
"=",
"step",
".",
"to_f",
"/",
"(",
"steps",
"-",
"1",
")",
"Color",
".",
"from_rgb",
"(",
"r",
"+",
"(",
"red",
"*",
"percentage",
")",
",",
"g",
"+",
"(",
"green",
"*",
"percentage",
")",
",",
"b",
"+",
"(",
"blue",
"*",
"percentage",
")",
")",
"end",
"# Add first and last colors to result, avoiding uneccessary calculation and rounding errors",
"result",
".",
"unshift",
"(",
"self",
".",
"dup",
")",
"result",
".",
"push",
"(",
"color",
".",
"dup",
")",
"result",
"end"
] | Uses a naive formula to generate a gradient between this color and the given color.
Returns the array of colors that make the gradient, including this color and the
target color. By default will return 10 colors, but this can be changed by supplying
an optional steps parameter. | [
"Uses",
"a",
"naive",
"formula",
"to",
"generate",
"a",
"gradient",
"between",
"this",
"color",
"and",
"the",
"given",
"color",
".",
"Returns",
"the",
"array",
"of",
"colors",
"that",
"make",
"the",
"gradient",
"including",
"this",
"color",
"and",
"the",
"target",
"color",
".",
"By",
"default",
"will",
"return",
"10",
"colors",
"but",
"this",
"can",
"be",
"changed",
"by",
"supplying",
"an",
"optional",
"steps",
"parameter",
"."
] | c2a8dcc06d5ac9bbfc48ca86ae58ee7bef5de927 | https://github.com/mbleigh/colorist/blob/c2a8dcc06d5ac9bbfc48ca86ae58ee7bef5de927/lib/colorist/color.rb#L423-L439 |
3,698 | adamzaninovich/gematria | lib/gematria/table_manager.rb | Gematria.TableManager.add_table | def add_table(name, table)
if table.is_a? Hash
tables[name.to_sym] = table
else
raise TypeError, 'Invalid table format'
end
end | ruby | def add_table(name, table)
if table.is_a? Hash
tables[name.to_sym] = table
else
raise TypeError, 'Invalid table format'
end
end | [
"def",
"add_table",
"(",
"name",
",",
"table",
")",
"if",
"table",
".",
"is_a?",
"Hash",
"tables",
"[",
"name",
".",
"to_sym",
"]",
"=",
"table",
"else",
"raise",
"TypeError",
",",
"'Invalid table format'",
"end",
"end"
] | Adds a table to the table store. A valid table must be a Hash with single character string keys and numerical values.
A table that is not a Hash will raise a TypeError. The table name will be converted to a Symbol.
@example
Gematria::Tables.add_table :mini_english, 'a' => 1, 'b' => 2, 'c' => 3
@raise [TypeError] if table is not a valid Hash
@param name [#to_sym] table name
@param table [Hash{String => Number}] table of characters pointing to corresponding values
@return [void] | [
"Adds",
"a",
"table",
"to",
"the",
"table",
"store",
".",
"A",
"valid",
"table",
"must",
"be",
"a",
"Hash",
"with",
"single",
"character",
"string",
"keys",
"and",
"numerical",
"values",
".",
"A",
"table",
"that",
"is",
"not",
"a",
"Hash",
"will",
"raise",
"a",
"TypeError",
".",
"The",
"table",
"name",
"will",
"be",
"converted",
"to",
"a",
"Symbol",
"."
] | 962d18ee1699939c483dacb1664267b5ed8540e2 | https://github.com/adamzaninovich/gematria/blob/962d18ee1699939c483dacb1664267b5ed8540e2/lib/gematria/table_manager.rb#L38-L44 |
3,699 | astashov/debugger-xml | lib/debugger/commands/frame.rb | Debugger.FrameFunctions.get_pr_arguments_with_xml | def get_pr_arguments_with_xml(mark, *args)
res = get_pr_arguments_without_xml((!!mark).to_s, *args)
res[:file] = File.expand_path(res[:file])
res
end | ruby | def get_pr_arguments_with_xml(mark, *args)
res = get_pr_arguments_without_xml((!!mark).to_s, *args)
res[:file] = File.expand_path(res[:file])
res
end | [
"def",
"get_pr_arguments_with_xml",
"(",
"mark",
",",
"*",
"args",
")",
"res",
"=",
"get_pr_arguments_without_xml",
"(",
"(",
"!",
"!",
"mark",
")",
".",
"to_s",
",",
"args",
")",
"res",
"[",
":file",
"]",
"=",
"File",
".",
"expand_path",
"(",
"res",
"[",
":file",
"]",
")",
"res",
"end"
] | Mark should be 'true' or 'false', as a String | [
"Mark",
"should",
"be",
"true",
"or",
"false",
"as",
"a",
"String"
] | 522746dc84fdf72cc089571b6884cac792ce0267 | https://github.com/astashov/debugger-xml/blob/522746dc84fdf72cc089571b6884cac792ce0267/lib/debugger/commands/frame.rb#L5-L9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.