repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
zohararad/handlebarer | lib/handlebarer/compiler.rb | Handlebarer.Compiler.compile | def compile(template)
v8_context do |context|
template = template.read if template.respond_to?(:read)
compiled_handlebars = context.eval("Handlebars.precompile(#{template.to_json})")
"Handlebars.template(#{compiled_handlebars});"
end
end | ruby | def compile(template)
v8_context do |context|
template = template.read if template.respond_to?(:read)
compiled_handlebars = context.eval("Handlebars.precompile(#{template.to_json})")
"Handlebars.template(#{compiled_handlebars});"
end
end | [
"def",
"compile",
"(",
"template",
")",
"v8_context",
"do",
"|",
"context",
"|",
"template",
"=",
"template",
".",
"read",
"if",
"template",
".",
"respond_to?",
"(",
":read",
")",
"compiled_handlebars",
"=",
"context",
".",
"eval",
"(",
"\"Handlebars.precompile(#{template.to_json})\"",
")",
"\"Handlebars.template(#{compiled_handlebars});\"",
"end",
"end"
] | Compile a Handlerbars template for client-side use with JST
@param [String, File] template Handlerbars template file or text to compile
@return [String] Handlerbars template compiled into Javascript and wrapped inside an anonymous function for JST | [
"Compile",
"a",
"Handlerbars",
"template",
"for",
"client",
"-",
"side",
"use",
"with",
"JST"
] | f5b2db17cb72fd2874ebe8268cf6f2ae17e74002 | https://github.com/zohararad/handlebarer/blob/f5b2db17cb72fd2874ebe8268cf6f2ae17e74002/lib/handlebarer/compiler.rb#L33-L39 | train |
zohararad/handlebarer | lib/handlebarer/compiler.rb | Handlebarer.Compiler.render | def render(template, vars = {})
v8_context do |context|
unless Handlebarer.configuration.nil?
helpers = handlebars_helpers
context.eval(helpers.join("\n")) if helpers.any?
end
context.eval("var fn = Handlebars.compile(#{template.to_json})")
context.eval("fn(#{vars.to_hbs.to_json})")
end
end | ruby | def render(template, vars = {})
v8_context do |context|
unless Handlebarer.configuration.nil?
helpers = handlebars_helpers
context.eval(helpers.join("\n")) if helpers.any?
end
context.eval("var fn = Handlebars.compile(#{template.to_json})")
context.eval("fn(#{vars.to_hbs.to_json})")
end
end | [
"def",
"render",
"(",
"template",
",",
"vars",
"=",
"{",
"}",
")",
"v8_context",
"do",
"|",
"context",
"|",
"unless",
"Handlebarer",
".",
"configuration",
".",
"nil?",
"helpers",
"=",
"handlebars_helpers",
"context",
".",
"eval",
"(",
"helpers",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"if",
"helpers",
".",
"any?",
"end",
"context",
".",
"eval",
"(",
"\"var fn = Handlebars.compile(#{template.to_json})\"",
")",
"context",
".",
"eval",
"(",
"\"fn(#{vars.to_hbs.to_json})\"",
")",
"end",
"end"
] | Compile and evaluate a Handlerbars template for server-side rendering
@param [String] template Handlerbars template text to render
@param [Hash] vars controller instance variables passed to the template
@return [String] HTML output of compiled Handlerbars template | [
"Compile",
"and",
"evaluate",
"a",
"Handlerbars",
"template",
"for",
"server",
"-",
"side",
"rendering"
] | f5b2db17cb72fd2874ebe8268cf6f2ae17e74002 | https://github.com/zohararad/handlebarer/blob/f5b2db17cb72fd2874ebe8268cf6f2ae17e74002/lib/handlebarer/compiler.rb#L45-L54 | train |
sue445/sengiri_yaml | lib/sengiri_yaml/writer.rb | SengiriYaml.Writer.divide | def divide(src_file, dst_dir)
FileUtils.mkdir_p(dst_dir) unless File.exist?(dst_dir)
src_content = YAML.load_file(src_file)
filenames = []
case src_content
when Hash
src_content.each do |key, value|
filename = "#{dst_dir}/#{key}.yml"
File.open(filename, "wb") do |f|
f.write({key => value}.to_yaml)
end
filenames << filename
end
when Array
src_content.each_with_index do |element, index|
filename = "#{dst_dir}/#{index}.yml"
File.open(filename, "wb") do |f|
f.write([element].to_yaml)
end
filenames << filename
end
else
raise "Unknown type"
end
filenames
end | ruby | def divide(src_file, dst_dir)
FileUtils.mkdir_p(dst_dir) unless File.exist?(dst_dir)
src_content = YAML.load_file(src_file)
filenames = []
case src_content
when Hash
src_content.each do |key, value|
filename = "#{dst_dir}/#{key}.yml"
File.open(filename, "wb") do |f|
f.write({key => value}.to_yaml)
end
filenames << filename
end
when Array
src_content.each_with_index do |element, index|
filename = "#{dst_dir}/#{index}.yml"
File.open(filename, "wb") do |f|
f.write([element].to_yaml)
end
filenames << filename
end
else
raise "Unknown type"
end
filenames
end | [
"def",
"divide",
"(",
"src_file",
",",
"dst_dir",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"dst_dir",
")",
"unless",
"File",
".",
"exist?",
"(",
"dst_dir",
")",
"src_content",
"=",
"YAML",
".",
"load_file",
"(",
"src_file",
")",
"filenames",
"=",
"[",
"]",
"case",
"src_content",
"when",
"Hash",
"src_content",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"filename",
"=",
"\"#{dst_dir}/#{key}.yml\"",
"File",
".",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"{",
"key",
"=>",
"value",
"}",
".",
"to_yaml",
")",
"end",
"filenames",
"<<",
"filename",
"end",
"when",
"Array",
"src_content",
".",
"each_with_index",
"do",
"|",
"element",
",",
"index",
"|",
"filename",
"=",
"\"#{dst_dir}/#{index}.yml\"",
"File",
".",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"[",
"element",
"]",
".",
"to_yaml",
")",
"end",
"filenames",
"<<",
"filename",
"end",
"else",
"raise",
"\"Unknown type\"",
"end",
"filenames",
"end"
] | divide yaml file
@param src_file [String]
@param dst_dir [String]
@return [Array<String>] divided yaml filenames | [
"divide",
"yaml",
"file"
] | f9595c5c05802bbbdd5228e808e7cb2b9cc3a049 | https://github.com/sue445/sengiri_yaml/blob/f9595c5c05802bbbdd5228e808e7cb2b9cc3a049/lib/sengiri_yaml/writer.rb#L10-L40 | train |
ltello/drsi | lib/drsi/dci/context.rb | DCI.Context.players_unplay_role! | def players_unplay_role!(extending_ticker)
roles.keys.each do |rolekey|
::DCI::Multiplayer(@_players[rolekey]).each do |roleplayer|
# puts " Context: #{self} - un-assigning role #{rolekey} to #{roleplayer}"
roleplayer.__unplay_last_role! if extending_ticker["#{roleplayer.object_id}_#{rolekey}"]
end
# 'instance_variable_set(:"@#{rolekey}", nil)
end
end | ruby | def players_unplay_role!(extending_ticker)
roles.keys.each do |rolekey|
::DCI::Multiplayer(@_players[rolekey]).each do |roleplayer|
# puts " Context: #{self} - un-assigning role #{rolekey} to #{roleplayer}"
roleplayer.__unplay_last_role! if extending_ticker["#{roleplayer.object_id}_#{rolekey}"]
end
# 'instance_variable_set(:"@#{rolekey}", nil)
end
end | [
"def",
"players_unplay_role!",
"(",
"extending_ticker",
")",
"roles",
".",
"keys",
".",
"each",
"do",
"|",
"rolekey",
"|",
"::",
"DCI",
"::",
"Multiplayer",
"(",
"@_players",
"[",
"rolekey",
"]",
")",
".",
"each",
"do",
"|",
"roleplayer",
"|",
"roleplayer",
".",
"__unplay_last_role!",
"if",
"extending_ticker",
"[",
"\"#{roleplayer.object_id}_#{rolekey}\"",
"]",
"end",
"end",
"end"
] | Disassociates every role from the playing object. | [
"Disassociates",
"every",
"role",
"from",
"the",
"playing",
"object",
"."
] | f584ee2c2f6438e341474b6922b568f43b3e1f25 | https://github.com/ltello/drsi/blob/f584ee2c2f6438e341474b6922b568f43b3e1f25/lib/drsi/dci/context.rb#L183-L191 | train |
jarrett/ichiban | lib/ichiban/watcher.rb | Ichiban.Watcher.on_change | def on_change(modified, added, deleted)
# Modifications and additions are treated the same.
(modified + added).uniq.each do |path|
if file = Ichiban::ProjectFile.from_abs(path)
begin
@loader.change(file) # Tell the Loader that this file has changed
file.update
rescue Exception => exc
Ichiban.logger.exception(exc)
end
end
end
# Deletions are handled specially.
deleted.each do |path|
Ichiban::Deleter.new.delete_dest(path)
end
# Finally, propagate this change to any dependent files.
(modified + added + deleted).uniq.each do |path|
begin
Ichiban::Dependencies.propagate(path)
rescue => exc
Ichiban.logger.exception(exc)
end
end
end | ruby | def on_change(modified, added, deleted)
# Modifications and additions are treated the same.
(modified + added).uniq.each do |path|
if file = Ichiban::ProjectFile.from_abs(path)
begin
@loader.change(file) # Tell the Loader that this file has changed
file.update
rescue Exception => exc
Ichiban.logger.exception(exc)
end
end
end
# Deletions are handled specially.
deleted.each do |path|
Ichiban::Deleter.new.delete_dest(path)
end
# Finally, propagate this change to any dependent files.
(modified + added + deleted).uniq.each do |path|
begin
Ichiban::Dependencies.propagate(path)
rescue => exc
Ichiban.logger.exception(exc)
end
end
end | [
"def",
"on_change",
"(",
"modified",
",",
"added",
",",
"deleted",
")",
"(",
"modified",
"+",
"added",
")",
".",
"uniq",
".",
"each",
"do",
"|",
"path",
"|",
"if",
"file",
"=",
"Ichiban",
"::",
"ProjectFile",
".",
"from_abs",
"(",
"path",
")",
"begin",
"@loader",
".",
"change",
"(",
"file",
")",
"file",
".",
"update",
"rescue",
"Exception",
"=>",
"exc",
"Ichiban",
".",
"logger",
".",
"exception",
"(",
"exc",
")",
"end",
"end",
"end",
"deleted",
".",
"each",
"do",
"|",
"path",
"|",
"Ichiban",
"::",
"Deleter",
".",
"new",
".",
"delete_dest",
"(",
"path",
")",
"end",
"(",
"modified",
"+",
"added",
"+",
"deleted",
")",
".",
"uniq",
".",
"each",
"do",
"|",
"path",
"|",
"begin",
"Ichiban",
"::",
"Dependencies",
".",
"propagate",
"(",
"path",
")",
"rescue",
"=>",
"exc",
"Ichiban",
".",
"logger",
".",
"exception",
"(",
"exc",
")",
"end",
"end",
"end"
] | The test suite calls this method directly
to bypass the Listen gem for certain tests. | [
"The",
"test",
"suite",
"calls",
"this",
"method",
"directly",
"to",
"bypass",
"the",
"Listen",
"gem",
"for",
"certain",
"tests",
"."
] | 310f96b0981ea19bf01246995f3732c986915d5b | https://github.com/jarrett/ichiban/blob/310f96b0981ea19bf01246995f3732c986915d5b/lib/ichiban/watcher.rb#L17-L43 | train |
niyireth/brownpapertickets | lib/brownpapertickets/event.rb | BrownPaperTickets.Event.all | def all
events = Event.get("/eventlist", :query =>{"id" => @@id , "account" => @@account })
event_sales = Event.get("/eventsales", :query =>{"id" => @@id , "account" => @@account })
parsed_event = []
events.parsed_response["document"]["event"].each do |event|
parsed_event << Event.new(@id,@account, event)
end
return parsed_event
end | ruby | def all
events = Event.get("/eventlist", :query =>{"id" => @@id , "account" => @@account })
event_sales = Event.get("/eventsales", :query =>{"id" => @@id , "account" => @@account })
parsed_event = []
events.parsed_response["document"]["event"].each do |event|
parsed_event << Event.new(@id,@account, event)
end
return parsed_event
end | [
"def",
"all",
"events",
"=",
"Event",
".",
"get",
"(",
"\"/eventlist\"",
",",
":query",
"=>",
"{",
"\"id\"",
"=>",
"@@id",
",",
"\"account\"",
"=>",
"@@account",
"}",
")",
"event_sales",
"=",
"Event",
".",
"get",
"(",
"\"/eventsales\"",
",",
":query",
"=>",
"{",
"\"id\"",
"=>",
"@@id",
",",
"\"account\"",
"=>",
"@@account",
"}",
")",
"parsed_event",
"=",
"[",
"]",
"events",
".",
"parsed_response",
"[",
"\"document\"",
"]",
"[",
"\"event\"",
"]",
".",
"each",
"do",
"|",
"event",
"|",
"parsed_event",
"<<",
"Event",
".",
"new",
"(",
"@id",
",",
"@account",
",",
"event",
")",
"end",
"return",
"parsed_event",
"end"
] | Returns all the account's events from brownpapersticker | [
"Returns",
"all",
"the",
"account",
"s",
"events",
"from",
"brownpapersticker"
] | 1eae1dc6f02b183c55090b79a62023e0f572fb57 | https://github.com/niyireth/brownpapertickets/blob/1eae1dc6f02b183c55090b79a62023e0f572fb57/lib/brownpapertickets/event.rb#L26-L34 | train |
niyireth/brownpapertickets | lib/brownpapertickets/event.rb | BrownPaperTickets.Event.find | def find(event_id)
event = Event.get("/eventlist",:query =>{"id" => @@id , "account" => @@account, "event_id" => event_id })
event_sales=Event.get("/eventsales",:query =>{"id" => @@id , "account" => @@account, "event_id" => event_id })
@attributes = event.parsed_response["document"]["event"]
return self
end | ruby | def find(event_id)
event = Event.get("/eventlist",:query =>{"id" => @@id , "account" => @@account, "event_id" => event_id })
event_sales=Event.get("/eventsales",:query =>{"id" => @@id , "account" => @@account, "event_id" => event_id })
@attributes = event.parsed_response["document"]["event"]
return self
end | [
"def",
"find",
"(",
"event_id",
")",
"event",
"=",
"Event",
".",
"get",
"(",
"\"/eventlist\"",
",",
":query",
"=>",
"{",
"\"id\"",
"=>",
"@@id",
",",
"\"account\"",
"=>",
"@@account",
",",
"\"event_id\"",
"=>",
"event_id",
"}",
")",
"event_sales",
"=",
"Event",
".",
"get",
"(",
"\"/eventsales\"",
",",
":query",
"=>",
"{",
"\"id\"",
"=>",
"@@id",
",",
"\"account\"",
"=>",
"@@account",
",",
"\"event_id\"",
"=>",
"event_id",
"}",
")",
"@attributes",
"=",
"event",
".",
"parsed_response",
"[",
"\"document\"",
"]",
"[",
"\"event\"",
"]",
"return",
"self",
"end"
] | This method get an event from brownpapersticker.
The event should belong to the account.
@param [String] envent_id this is id of the event I want to find | [
"This",
"method",
"get",
"an",
"event",
"from",
"brownpapersticker",
".",
"The",
"event",
"should",
"belong",
"to",
"the",
"account",
"."
] | 1eae1dc6f02b183c55090b79a62023e0f572fb57 | https://github.com/niyireth/brownpapertickets/blob/1eae1dc6f02b183c55090b79a62023e0f572fb57/lib/brownpapertickets/event.rb#L39-L44 | train |
TheODI-UD2D/blocktrain | lib/blocktrain/lookups.rb | Blocktrain.Lookups.init! | def init!
@lookups ||= {}
@aliases ||= {}
# Get unique list of keys from ES
r = Aggregations::TermsAggregation.new(from: '2015-09-01 00:00:00Z', to: '2015-09-02 00:00:00Z', term: "memoryAddress").results
addresses = r.map {|x| x["key"]}
# Get a memory location for each key
addresses.each do |address|
r = Query.new(from: '2015-09-01 10:00:00Z', to: '2015-09-30 11:00:00Z', memory_addresses: address, limit: 1).results
signal_name = remove_cruft(r.first["_source"]["signalName"].to_s)
@lookups[signal_name] = address
end
# Read aliases from file
aliases = OpenStruct.new fetch_yaml 'signal_aliases'
aliases.each_pair do |key, value|
@aliases[key.to_s] = @lookups[value]
@lookups[key.to_s] = @lookups[value]
end
end | ruby | def init!
@lookups ||= {}
@aliases ||= {}
# Get unique list of keys from ES
r = Aggregations::TermsAggregation.new(from: '2015-09-01 00:00:00Z', to: '2015-09-02 00:00:00Z', term: "memoryAddress").results
addresses = r.map {|x| x["key"]}
# Get a memory location for each key
addresses.each do |address|
r = Query.new(from: '2015-09-01 10:00:00Z', to: '2015-09-30 11:00:00Z', memory_addresses: address, limit: 1).results
signal_name = remove_cruft(r.first["_source"]["signalName"].to_s)
@lookups[signal_name] = address
end
# Read aliases from file
aliases = OpenStruct.new fetch_yaml 'signal_aliases'
aliases.each_pair do |key, value|
@aliases[key.to_s] = @lookups[value]
@lookups[key.to_s] = @lookups[value]
end
end | [
"def",
"init!",
"@lookups",
"||=",
"{",
"}",
"@aliases",
"||=",
"{",
"}",
"r",
"=",
"Aggregations",
"::",
"TermsAggregation",
".",
"new",
"(",
"from",
":",
"'2015-09-01 00:00:00Z'",
",",
"to",
":",
"'2015-09-02 00:00:00Z'",
",",
"term",
":",
"\"memoryAddress\"",
")",
".",
"results",
"addresses",
"=",
"r",
".",
"map",
"{",
"|",
"x",
"|",
"x",
"[",
"\"key\"",
"]",
"}",
"addresses",
".",
"each",
"do",
"|",
"address",
"|",
"r",
"=",
"Query",
".",
"new",
"(",
"from",
":",
"'2015-09-01 10:00:00Z'",
",",
"to",
":",
"'2015-09-30 11:00:00Z'",
",",
"memory_addresses",
":",
"address",
",",
"limit",
":",
"1",
")",
".",
"results",
"signal_name",
"=",
"remove_cruft",
"(",
"r",
".",
"first",
"[",
"\"_source\"",
"]",
"[",
"\"signalName\"",
"]",
".",
"to_s",
")",
"@lookups",
"[",
"signal_name",
"]",
"=",
"address",
"end",
"aliases",
"=",
"OpenStruct",
".",
"new",
"fetch_yaml",
"'signal_aliases'",
"aliases",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"@aliases",
"[",
"key",
".",
"to_s",
"]",
"=",
"@lookups",
"[",
"value",
"]",
"@lookups",
"[",
"key",
".",
"to_s",
"]",
"=",
"@lookups",
"[",
"value",
"]",
"end",
"end"
] | Separate out initialization for testing purposes | [
"Separate",
"out",
"initialization",
"for",
"testing",
"purposes"
] | ec415f48ebc1a1dd4e4107e21bddb2d0fe238efb | https://github.com/TheODI-UD2D/blocktrain/blob/ec415f48ebc1a1dd4e4107e21bddb2d0fe238efb/lib/blocktrain/lookups.rb#L20-L38 | train |
TheODI-UD2D/blocktrain | lib/blocktrain/lookups.rb | Blocktrain.Lookups.remove_cruft | def remove_cruft(signal)
parts = signal.split(".")
[
parts[0..-3].join('.'),
parts.pop
].join('.')
end | ruby | def remove_cruft(signal)
parts = signal.split(".")
[
parts[0..-3].join('.'),
parts.pop
].join('.')
end | [
"def",
"remove_cruft",
"(",
"signal",
")",
"parts",
"=",
"signal",
".",
"split",
"(",
"\".\"",
")",
"[",
"parts",
"[",
"0",
"..",
"-",
"3",
"]",
".",
"join",
"(",
"'.'",
")",
",",
"parts",
".",
"pop",
"]",
".",
"join",
"(",
"'.'",
")",
"end"
] | This will go away once we get the correct signals in the DB | [
"This",
"will",
"go",
"away",
"once",
"we",
"get",
"the",
"correct",
"signals",
"in",
"the",
"DB"
] | ec415f48ebc1a1dd4e4107e21bddb2d0fe238efb | https://github.com/TheODI-UD2D/blocktrain/blob/ec415f48ebc1a1dd4e4107e21bddb2d0fe238efb/lib/blocktrain/lookups.rb#L47-L53 | train |
tubbo/active_copy | lib/active_copy/view_helper.rb | ActiveCopy.ViewHelper.render_copy | def render_copy from_source_path
source_path = "#{ActiveCopy.content_path}/#{from_source_path}.md"
if File.exists? source_path
raw_source = IO.read source_path
source = raw_source.split("---\n")[2]
template = ActiveCopy::Markdown.new
template.render(source).html_safe
else
raise ArgumentError.new "#{source_path} does not exist."
end
end | ruby | def render_copy from_source_path
source_path = "#{ActiveCopy.content_path}/#{from_source_path}.md"
if File.exists? source_path
raw_source = IO.read source_path
source = raw_source.split("---\n")[2]
template = ActiveCopy::Markdown.new
template.render(source).html_safe
else
raise ArgumentError.new "#{source_path} does not exist."
end
end | [
"def",
"render_copy",
"from_source_path",
"source_path",
"=",
"\"#{ActiveCopy.content_path}/#{from_source_path}.md\"",
"if",
"File",
".",
"exists?",
"source_path",
"raw_source",
"=",
"IO",
".",
"read",
"source_path",
"source",
"=",
"raw_source",
".",
"split",
"(",
"\"---\\n\"",
")",
"[",
"2",
"]",
"template",
"=",
"ActiveCopy",
"::",
"Markdown",
".",
"new",
"template",
".",
"render",
"(",
"source",
")",
".",
"html_safe",
"else",
"raise",
"ArgumentError",
".",
"new",
"\"#{source_path} does not exist.\"",
"end",
"end"
] | Render a given relative content path to Markdown. | [
"Render",
"a",
"given",
"relative",
"content",
"path",
"to",
"Markdown",
"."
] | 63716fdd9283231e9ed0d8ac6af97633d3e97210 | https://github.com/tubbo/active_copy/blob/63716fdd9283231e9ed0d8ac6af97633d3e97210/lib/active_copy/view_helper.rb#L4-L15 | train |
analogeryuta/capistrano-sudo | lib/capistrano/sudo/dsl.rb | Capistrano.DSL.sudo! | def sudo!(*args)
on roles(:all) do |host|
key = "#{host.user}@#{host.hostname}"
SSHKit::Sudo.password_cache[key] = "#{fetch(:password)}\n" # \n is enter
end
sudo(*args)
end | ruby | def sudo!(*args)
on roles(:all) do |host|
key = "#{host.user}@#{host.hostname}"
SSHKit::Sudo.password_cache[key] = "#{fetch(:password)}\n" # \n is enter
end
sudo(*args)
end | [
"def",
"sudo!",
"(",
"*",
"args",
")",
"on",
"roles",
"(",
":all",
")",
"do",
"|",
"host",
"|",
"key",
"=",
"\"#{host.user}@#{host.hostname}\"",
"SSHKit",
"::",
"Sudo",
".",
"password_cache",
"[",
"key",
"]",
"=",
"\"#{fetch(:password)}\\n\"",
"end",
"sudo",
"(",
"*",
"args",
")",
"end"
] | `sudo!` executes sudo command and provides password input. | [
"sudo!",
"executes",
"sudo",
"command",
"and",
"provides",
"password",
"input",
"."
] | 20311986f3e3d2892dfcf5036d13d76bca7a3de0 | https://github.com/analogeryuta/capistrano-sudo/blob/20311986f3e3d2892dfcf5036d13d76bca7a3de0/lib/capistrano/sudo/dsl.rb#L4-L10 | train |
antonversal/fake_service | lib/fake_service/middleware.rb | FakeService.Middleware.define_actions | def define_actions
unless @action_defined
hash = YAML.load(File.read(@file_path))
hash.each do |k, v|
v.each do |key, value|
@app.class.define_action!(value["request"], value["response"])
end
end
@action_defined = true
end
end | ruby | def define_actions
unless @action_defined
hash = YAML.load(File.read(@file_path))
hash.each do |k, v|
v.each do |key, value|
@app.class.define_action!(value["request"], value["response"])
end
end
@action_defined = true
end
end | [
"def",
"define_actions",
"unless",
"@action_defined",
"hash",
"=",
"YAML",
".",
"load",
"(",
"File",
".",
"read",
"(",
"@file_path",
")",
")",
"hash",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"v",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"@app",
".",
"class",
".",
"define_action!",
"(",
"value",
"[",
"\"request\"",
"]",
",",
"value",
"[",
"\"response\"",
"]",
")",
"end",
"end",
"@action_defined",
"=",
"true",
"end",
"end"
] | defines actions for each request in yaml file. | [
"defines",
"actions",
"for",
"each",
"request",
"in",
"yaml",
"file",
"."
] | 93a59f859447004bdea27b3b4226c4d73d197008 | https://github.com/antonversal/fake_service/blob/93a59f859447004bdea27b3b4226c4d73d197008/lib/fake_service/middleware.rb#L9-L19 | train |
pikesley/insulin | lib/insulin/event.rb | Insulin.Event.save | def save mongo_handle
# See above
date_collection = self["date"]
if self["time"] < @@cut_off_time
date_collection = (Time.parse(self["date"]) - 86400).strftime "%F"
end
# Save to each of these collections
clxns = [
"events",
self["type"],
self["subtype"],
date_collection
]
clxns.each do |c|
if c
mongo_handle.db.collection(c).update(
{
"serial" => self["serial"]
},
self,
{
# Upsert: update if exists, otherwise insert
:upsert => true
}
)
end
end
end | ruby | def save mongo_handle
# See above
date_collection = self["date"]
if self["time"] < @@cut_off_time
date_collection = (Time.parse(self["date"]) - 86400).strftime "%F"
end
# Save to each of these collections
clxns = [
"events",
self["type"],
self["subtype"],
date_collection
]
clxns.each do |c|
if c
mongo_handle.db.collection(c).update(
{
"serial" => self["serial"]
},
self,
{
# Upsert: update if exists, otherwise insert
:upsert => true
}
)
end
end
end | [
"def",
"save",
"mongo_handle",
"date_collection",
"=",
"self",
"[",
"\"date\"",
"]",
"if",
"self",
"[",
"\"time\"",
"]",
"<",
"@@cut_off_time",
"date_collection",
"=",
"(",
"Time",
".",
"parse",
"(",
"self",
"[",
"\"date\"",
"]",
")",
"-",
"86400",
")",
".",
"strftime",
"\"%F\"",
"end",
"clxns",
"=",
"[",
"\"events\"",
",",
"self",
"[",
"\"type\"",
"]",
",",
"self",
"[",
"\"subtype\"",
"]",
",",
"date_collection",
"]",
"clxns",
".",
"each",
"do",
"|",
"c",
"|",
"if",
"c",
"mongo_handle",
".",
"db",
".",
"collection",
"(",
"c",
")",
".",
"update",
"(",
"{",
"\"serial\"",
"=>",
"self",
"[",
"\"serial\"",
"]",
"}",
",",
"self",
",",
"{",
":upsert",
"=>",
"true",
"}",
")",
"end",
"end",
"end"
] | Save the event to Mongo via mongo_handle | [
"Save",
"the",
"event",
"to",
"Mongo",
"via",
"mongo_handle"
] | 0ef2fe0ec10afe030fb556e223cb994797456969 | https://github.com/pikesley/insulin/blob/0ef2fe0ec10afe030fb556e223cb994797456969/lib/insulin/event.rb#L49-L79 | train |
zpatten/ztk | lib/ztk/logger.rb | ZTK.Logger.shift | def shift(severity, shift=0, &block)
severity = ZTK::Logger.const_get(severity.to_s.upcase)
add(severity, nil, nil, shift, &block)
end | ruby | def shift(severity, shift=0, &block)
severity = ZTK::Logger.const_get(severity.to_s.upcase)
add(severity, nil, nil, shift, &block)
end | [
"def",
"shift",
"(",
"severity",
",",
"shift",
"=",
"0",
",",
"&",
"block",
")",
"severity",
"=",
"ZTK",
"::",
"Logger",
".",
"const_get",
"(",
"severity",
".",
"to_s",
".",
"upcase",
")",
"add",
"(",
"severity",
",",
"nil",
",",
"nil",
",",
"shift",
",",
"&",
"block",
")",
"end"
] | Specialized logging. Logs messages in the same format, except has the
option to shift the caller_at position to exposed the proper calling
method.
Very useful in situations of class inheritence, for example, where you
might have logging statements in a base class, which are inherited by
another class. When calling the base class method via the inherited class
the log messages will indicate the base class as the caller. While this
is technically true it is not always what we want to see in the logs
because it is ambigious and does not show us where the call truly
originated from. | [
"Specialized",
"logging",
".",
"Logs",
"messages",
"in",
"the",
"same",
"format",
"except",
"has",
"the",
"option",
"to",
"shift",
"the",
"caller_at",
"position",
"to",
"exposed",
"the",
"proper",
"calling",
"method",
"."
] | 9b0f35bef36f38428e1a57b36f25a806c240b3fb | https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/logger.rb#L112-L115 | train |
zpatten/ztk | lib/ztk/logger.rb | ZTK.Logger.add | def add(severity, message=nil, progname=nil, shift=0, &block)
return if (@level > severity)
message = block.call if message.nil? && block_given?
return if message.nil?
called_by = parse_caller(caller[1+shift])
message = [message.chomp, progname].flatten.compact.join(": ")
message = "%19s.%06d|%05d|%5s|%s%s\n" % [Time.now.utc.strftime("%Y-%m-%d|%H:%M:%S"), Time.now.utc.usec, Process.pid, SEVERITIES[severity], called_by, message]
@logdev.write(ZTK::ANSI.uncolor(message))
@logdev.respond_to?(:flush) and @logdev.flush
true
end | ruby | def add(severity, message=nil, progname=nil, shift=0, &block)
return if (@level > severity)
message = block.call if message.nil? && block_given?
return if message.nil?
called_by = parse_caller(caller[1+shift])
message = [message.chomp, progname].flatten.compact.join(": ")
message = "%19s.%06d|%05d|%5s|%s%s\n" % [Time.now.utc.strftime("%Y-%m-%d|%H:%M:%S"), Time.now.utc.usec, Process.pid, SEVERITIES[severity], called_by, message]
@logdev.write(ZTK::ANSI.uncolor(message))
@logdev.respond_to?(:flush) and @logdev.flush
true
end | [
"def",
"add",
"(",
"severity",
",",
"message",
"=",
"nil",
",",
"progname",
"=",
"nil",
",",
"shift",
"=",
"0",
",",
"&",
"block",
")",
"return",
"if",
"(",
"@level",
">",
"severity",
")",
"message",
"=",
"block",
".",
"call",
"if",
"message",
".",
"nil?",
"&&",
"block_given?",
"return",
"if",
"message",
".",
"nil?",
"called_by",
"=",
"parse_caller",
"(",
"caller",
"[",
"1",
"+",
"shift",
"]",
")",
"message",
"=",
"[",
"message",
".",
"chomp",
",",
"progname",
"]",
".",
"flatten",
".",
"compact",
".",
"join",
"(",
"\": \"",
")",
"message",
"=",
"\"%19s.%06d|%05d|%5s|%s%s\\n\"",
"%",
"[",
"Time",
".",
"now",
".",
"utc",
".",
"strftime",
"(",
"\"%Y-%m-%d|%H:%M:%S\"",
")",
",",
"Time",
".",
"now",
".",
"utc",
".",
"usec",
",",
"Process",
".",
"pid",
",",
"SEVERITIES",
"[",
"severity",
"]",
",",
"called_by",
",",
"message",
"]",
"@logdev",
".",
"write",
"(",
"ZTK",
"::",
"ANSI",
".",
"uncolor",
"(",
"message",
")",
")",
"@logdev",
".",
"respond_to?",
"(",
":flush",
")",
"and",
"@logdev",
".",
"flush",
"true",
"end"
] | Writes a log message if the current log level is at or below the supplied
severity.
@param [Constant] severity Log level severity.
@param [String] message Optional message to prefix the log entry with.
@param [String] progname Optional name of the program to prefix the log
entry with.
@yieldreturn [String] The block should return the desired log message. | [
"Writes",
"a",
"log",
"message",
"if",
"the",
"current",
"log",
"level",
"is",
"at",
"or",
"below",
"the",
"supplied",
"severity",
"."
] | 9b0f35bef36f38428e1a57b36f25a806c240b3fb | https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/logger.rb#L150-L165 | train |
zpatten/ztk | lib/ztk/logger.rb | ZTK.Logger.set_log_level | def set_log_level(level=nil)
defined?(Rails) and (default = (Rails.env.production? ? "INFO" : "DEBUG")) or (default = "INFO")
log_level = (ENV['LOG_LEVEL'] || level || default)
self.level = ZTK::Logger.const_get(log_level.to_s.upcase)
end | ruby | def set_log_level(level=nil)
defined?(Rails) and (default = (Rails.env.production? ? "INFO" : "DEBUG")) or (default = "INFO")
log_level = (ENV['LOG_LEVEL'] || level || default)
self.level = ZTK::Logger.const_get(log_level.to_s.upcase)
end | [
"def",
"set_log_level",
"(",
"level",
"=",
"nil",
")",
"defined?",
"(",
"Rails",
")",
"and",
"(",
"default",
"=",
"(",
"Rails",
".",
"env",
".",
"production?",
"?",
"\"INFO\"",
":",
"\"DEBUG\"",
")",
")",
"or",
"(",
"default",
"=",
"\"INFO\"",
")",
"log_level",
"=",
"(",
"ENV",
"[",
"'LOG_LEVEL'",
"]",
"||",
"level",
"||",
"default",
")",
"self",
".",
"level",
"=",
"ZTK",
"::",
"Logger",
".",
"const_get",
"(",
"log_level",
".",
"to_s",
".",
"upcase",
")",
"end"
] | Sets the log level.
@param [String] level Log level to use. | [
"Sets",
"the",
"log",
"level",
"."
] | 9b0f35bef36f38428e1a57b36f25a806c240b3fb | https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/logger.rb#L170-L174 | train |
npepinpe/redstruct | lib/redstruct/list.rb | Redstruct.List.pop | def pop(size = 1, timeout: nil)
raise ArgumentError, 'size must be positive' unless size.positive?
if timeout.nil?
return self.connection.rpop(@key) if size == 1
return shift_pop_script(keys: @key, argv: [-size, -1, 1])
else
raise ArgumentError, 'timeout is only supported if size == 1' unless size == 1
return self.connection.brpop(@key, timeout: timeout)&.last
end
end | ruby | def pop(size = 1, timeout: nil)
raise ArgumentError, 'size must be positive' unless size.positive?
if timeout.nil?
return self.connection.rpop(@key) if size == 1
return shift_pop_script(keys: @key, argv: [-size, -1, 1])
else
raise ArgumentError, 'timeout is only supported if size == 1' unless size == 1
return self.connection.brpop(@key, timeout: timeout)&.last
end
end | [
"def",
"pop",
"(",
"size",
"=",
"1",
",",
"timeout",
":",
"nil",
")",
"raise",
"ArgumentError",
",",
"'size must be positive'",
"unless",
"size",
".",
"positive?",
"if",
"timeout",
".",
"nil?",
"return",
"self",
".",
"connection",
".",
"rpop",
"(",
"@key",
")",
"if",
"size",
"==",
"1",
"return",
"shift_pop_script",
"(",
"keys",
":",
"@key",
",",
"argv",
":",
"[",
"-",
"size",
",",
"-",
"1",
",",
"1",
"]",
")",
"else",
"raise",
"ArgumentError",
",",
"'timeout is only supported if size == 1'",
"unless",
"size",
"==",
"1",
"return",
"self",
".",
"connection",
".",
"brpop",
"(",
"@key",
",",
"timeout",
":",
"timeout",
")",
"&.",
"last",
"end",
"end"
] | Pops an item from the list, optionally blocking to wait until the list is non-empty
@param [Integer] timeout the amount of time to wait in seconds; if 0, waits indefinitely
@return [nil, String] nil if the list was empty, otherwise the item | [
"Pops",
"an",
"item",
"from",
"the",
"list",
"optionally",
"blocking",
"to",
"wait",
"until",
"the",
"list",
"is",
"non",
"-",
"empty"
] | c97b45e7227f8ed9029f0effff352fc4d82dc3cb | https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/list.rb#L115-L125 | train |
npepinpe/redstruct | lib/redstruct/list.rb | Redstruct.List.shift | def shift(size = 1, timeout: nil)
raise ArgumentError, 'size must be positive' unless size.positive?
if timeout.nil?
return self.connection.lpop(@key) if size == 1
return shift_pop_script(keys: @key, argv: [0, size - 1, 0])
else
raise ArgumentError, 'timeout is only supported if size == 1' unless size == 1
return self.connection.blpop(@key, timeout: timeout)&.last
end
end | ruby | def shift(size = 1, timeout: nil)
raise ArgumentError, 'size must be positive' unless size.positive?
if timeout.nil?
return self.connection.lpop(@key) if size == 1
return shift_pop_script(keys: @key, argv: [0, size - 1, 0])
else
raise ArgumentError, 'timeout is only supported if size == 1' unless size == 1
return self.connection.blpop(@key, timeout: timeout)&.last
end
end | [
"def",
"shift",
"(",
"size",
"=",
"1",
",",
"timeout",
":",
"nil",
")",
"raise",
"ArgumentError",
",",
"'size must be positive'",
"unless",
"size",
".",
"positive?",
"if",
"timeout",
".",
"nil?",
"return",
"self",
".",
"connection",
".",
"lpop",
"(",
"@key",
")",
"if",
"size",
"==",
"1",
"return",
"shift_pop_script",
"(",
"keys",
":",
"@key",
",",
"argv",
":",
"[",
"0",
",",
"size",
"-",
"1",
",",
"0",
"]",
")",
"else",
"raise",
"ArgumentError",
",",
"'timeout is only supported if size == 1'",
"unless",
"size",
"==",
"1",
"return",
"self",
".",
"connection",
".",
"blpop",
"(",
"@key",
",",
"timeout",
":",
"timeout",
")",
"&.",
"last",
"end",
"end"
] | Shifts an item from the list, optionally blocking to wait until the list is non-empty
@param [Integer] timeout the amount of time to wait in seconds; if 0, waits indefinitely
@return [nil, String] nil if the list was empty, otherwise the item | [
"Shifts",
"an",
"item",
"from",
"the",
"list",
"optionally",
"blocking",
"to",
"wait",
"until",
"the",
"list",
"is",
"non",
"-",
"empty"
] | c97b45e7227f8ed9029f0effff352fc4d82dc3cb | https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/list.rb#L130-L140 | train |
npepinpe/redstruct | lib/redstruct/list.rb | Redstruct.List.popshift | def popshift(list, timeout: nil)
raise ArgumentError, 'list must respond to #key' unless list.respond_to?(:key)
if timeout.nil?
return self.connection.rpoplpush(@key, list.key)
else
return self.connection.brpoplpush(@key, list.key, timeout: timeout)
end
end | ruby | def popshift(list, timeout: nil)
raise ArgumentError, 'list must respond to #key' unless list.respond_to?(:key)
if timeout.nil?
return self.connection.rpoplpush(@key, list.key)
else
return self.connection.brpoplpush(@key, list.key, timeout: timeout)
end
end | [
"def",
"popshift",
"(",
"list",
",",
"timeout",
":",
"nil",
")",
"raise",
"ArgumentError",
",",
"'list must respond to #key'",
"unless",
"list",
".",
"respond_to?",
"(",
":key",
")",
"if",
"timeout",
".",
"nil?",
"return",
"self",
".",
"connection",
".",
"rpoplpush",
"(",
"@key",
",",
"list",
".",
"key",
")",
"else",
"return",
"self",
".",
"connection",
".",
"brpoplpush",
"(",
"@key",
",",
"list",
".",
"key",
",",
"timeout",
":",
"timeout",
")",
"end",
"end"
] | Pops an element from this list and shifts it onto the given list.
@param [Redstruct::List] list the list to shift the element onto
@param [#to_i] timeout optional timeout to wait for in seconds
@return [String] the element that was popped from the list and pushed onto the other | [
"Pops",
"an",
"element",
"from",
"this",
"list",
"and",
"shifts",
"it",
"onto",
"the",
"given",
"list",
"."
] | c97b45e7227f8ed9029f0effff352fc4d82dc3cb | https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/list.rb#L146-L154 | train |
colstrom/ezmq | lib/ezmq/socket.rb | EZMQ.Socket.connect | def connect(transport: :tcp, address: '127.0.0.1', port: 5555)
endpoint = "#{ transport }://#{ address }"
endpoint << ":#{ port }" if %i(tcp pgm epgm).include? transport
@socket.method(__callee__).call(endpoint) == 0
end | ruby | def connect(transport: :tcp, address: '127.0.0.1', port: 5555)
endpoint = "#{ transport }://#{ address }"
endpoint << ":#{ port }" if %i(tcp pgm epgm).include? transport
@socket.method(__callee__).call(endpoint) == 0
end | [
"def",
"connect",
"(",
"transport",
":",
":tcp",
",",
"address",
":",
"'127.0.0.1'",
",",
"port",
":",
"5555",
")",
"endpoint",
"=",
"\"#{ transport }://#{ address }\"",
"endpoint",
"<<",
"\":#{ port }\"",
"if",
"%i(",
"tcp",
"pgm",
"epgm",
")",
".",
"include?",
"transport",
"@socket",
".",
"method",
"(",
"__callee__",
")",
".",
"call",
"(",
"endpoint",
")",
"==",
"0",
"end"
] | Connects the socket to the given address.
@note This method can be called as #bind, in which case it binds to the
specified address instead.
@param [Symbol] transport (:tcp) transport for transport.
@param [String] address ('127.0.0.1') address for endpoint.
@note Binding to 'localhost' is not consistent on all platforms.
Prefer '127.0.0.1' instead.
@param [Fixnum] port (5555) port for endpoint.
@note port is ignored unless transport is one of :tcp, :pgm or :epgm
@return [Boolean] was connection successful? | [
"Connects",
"the",
"socket",
"to",
"the",
"given",
"address",
"."
] | cd7f9f256d6c3f7a844871a3a77a89d7122d5836 | https://github.com/colstrom/ezmq/blob/cd7f9f256d6c3f7a844871a3a77a89d7122d5836/lib/ezmq/socket.rb#L88-L92 | train |
abrandoned/multi_op_queue | lib/multi_op_queue.rb | MultiOpQueue.Queue.pop | def pop(non_block=false)
handle_interrupt do
@mutex.synchronize do
while true
if @que.empty?
if non_block
raise ThreadError, "queue empty"
else
begin
@num_waiting += 1
@cond.wait @mutex
ensure
@num_waiting -= 1
end
end
else
return @que.shift
end
end
end
end
end | ruby | def pop(non_block=false)
handle_interrupt do
@mutex.synchronize do
while true
if @que.empty?
if non_block
raise ThreadError, "queue empty"
else
begin
@num_waiting += 1
@cond.wait @mutex
ensure
@num_waiting -= 1
end
end
else
return @que.shift
end
end
end
end
end | [
"def",
"pop",
"(",
"non_block",
"=",
"false",
")",
"handle_interrupt",
"do",
"@mutex",
".",
"synchronize",
"do",
"while",
"true",
"if",
"@que",
".",
"empty?",
"if",
"non_block",
"raise",
"ThreadError",
",",
"\"queue empty\"",
"else",
"begin",
"@num_waiting",
"+=",
"1",
"@cond",
".",
"wait",
"@mutex",
"ensure",
"@num_waiting",
"-=",
"1",
"end",
"end",
"else",
"return",
"@que",
".",
"shift",
"end",
"end",
"end",
"end",
"end"
] | Retrieves data from the queue. If the queue is empty, the calling thread is
suspended until data is pushed onto the queue. If +non_block+ is true, the
thread isn't suspended, and an exception is raised. | [
"Retrieves",
"data",
"from",
"the",
"queue",
".",
"If",
"the",
"queue",
"is",
"empty",
"the",
"calling",
"thread",
"is",
"suspended",
"until",
"data",
"is",
"pushed",
"onto",
"the",
"queue",
".",
"If",
"+",
"non_block",
"+",
"is",
"true",
"the",
"thread",
"isn",
"t",
"suspended",
"and",
"an",
"exception",
"is",
"raised",
"."
] | 51cc58bd2fc20af2991e3c766d2bbd83c409ea0a | https://github.com/abrandoned/multi_op_queue/blob/51cc58bd2fc20af2991e3c766d2bbd83c409ea0a/lib/multi_op_queue.rb#L85-L106 | train |
abrandoned/multi_op_queue | lib/multi_op_queue.rb | MultiOpQueue.Queue.pop_up_to | def pop_up_to(num_to_pop = 1, opts = {})
case opts
when TrueClass, FalseClass
non_bock = opts
when Hash
timeout = opts.fetch(:timeout, nil)
non_block = opts.fetch(:non_block, false)
end
handle_interrupt do
@mutex.synchronize do
while true
if @que.empty?
if non_block
raise ThreadError, "queue empty"
else
begin
@num_waiting += 1
@cond.wait(@mutex, timeout)
return nil if @que.empty?
ensure
@num_waiting -= 1
end
end
else
return @que.shift(num_to_pop)
end
end
end
end
end | ruby | def pop_up_to(num_to_pop = 1, opts = {})
case opts
when TrueClass, FalseClass
non_bock = opts
when Hash
timeout = opts.fetch(:timeout, nil)
non_block = opts.fetch(:non_block, false)
end
handle_interrupt do
@mutex.synchronize do
while true
if @que.empty?
if non_block
raise ThreadError, "queue empty"
else
begin
@num_waiting += 1
@cond.wait(@mutex, timeout)
return nil if @que.empty?
ensure
@num_waiting -= 1
end
end
else
return @que.shift(num_to_pop)
end
end
end
end
end | [
"def",
"pop_up_to",
"(",
"num_to_pop",
"=",
"1",
",",
"opts",
"=",
"{",
"}",
")",
"case",
"opts",
"when",
"TrueClass",
",",
"FalseClass",
"non_bock",
"=",
"opts",
"when",
"Hash",
"timeout",
"=",
"opts",
".",
"fetch",
"(",
":timeout",
",",
"nil",
")",
"non_block",
"=",
"opts",
".",
"fetch",
"(",
":non_block",
",",
"false",
")",
"end",
"handle_interrupt",
"do",
"@mutex",
".",
"synchronize",
"do",
"while",
"true",
"if",
"@que",
".",
"empty?",
"if",
"non_block",
"raise",
"ThreadError",
",",
"\"queue empty\"",
"else",
"begin",
"@num_waiting",
"+=",
"1",
"@cond",
".",
"wait",
"(",
"@mutex",
",",
"timeout",
")",
"return",
"nil",
"if",
"@que",
".",
"empty?",
"ensure",
"@num_waiting",
"-=",
"1",
"end",
"end",
"else",
"return",
"@que",
".",
"shift",
"(",
"num_to_pop",
")",
"end",
"end",
"end",
"end",
"end"
] | Retrieves data from the queue and returns array of contents.
If +num_to_pop+ are available in the queue then multiple elements are returned in array response
If the queue is empty, the calling thread is
suspended until data is pushed onto the queue. If +non_block+ is true, the
thread isn't suspended, and an exception is raised. | [
"Retrieves",
"data",
"from",
"the",
"queue",
"and",
"returns",
"array",
"of",
"contents",
".",
"If",
"+",
"num_to_pop",
"+",
"are",
"available",
"in",
"the",
"queue",
"then",
"multiple",
"elements",
"are",
"returned",
"in",
"array",
"response",
"If",
"the",
"queue",
"is",
"empty",
"the",
"calling",
"thread",
"is",
"suspended",
"until",
"data",
"is",
"pushed",
"onto",
"the",
"queue",
".",
"If",
"+",
"non_block",
"+",
"is",
"true",
"the",
"thread",
"isn",
"t",
"suspended",
"and",
"an",
"exception",
"is",
"raised",
"."
] | 51cc58bd2fc20af2991e3c766d2bbd83c409ea0a | https://github.com/abrandoned/multi_op_queue/blob/51cc58bd2fc20af2991e3c766d2bbd83c409ea0a/lib/multi_op_queue.rb#L125-L155 | train |
yivo/confo-config | lib/confo/concerns/options_manager.rb | Confo.OptionsManager.raw_get | def raw_get(option)
value = options_storage[option]
Confo.callable_without_arguments?(value) ? value.call : value
end | ruby | def raw_get(option)
value = options_storage[option]
Confo.callable_without_arguments?(value) ? value.call : value
end | [
"def",
"raw_get",
"(",
"option",
")",
"value",
"=",
"options_storage",
"[",
"option",
"]",
"Confo",
".",
"callable_without_arguments?",
"(",
"value",
")",
"?",
"value",
".",
"call",
":",
"value",
"end"
] | Internal method to get an option.
If value is callable without arguments
it will be called and result will be returned. | [
"Internal",
"method",
"to",
"get",
"an",
"option",
".",
"If",
"value",
"is",
"callable",
"without",
"arguments",
"it",
"will",
"be",
"called",
"and",
"result",
"will",
"be",
"returned",
"."
] | 4d5be81947b450c6daa329bcc111096ae629cf46 | https://github.com/yivo/confo-config/blob/4d5be81947b450c6daa329bcc111096ae629cf46/lib/confo/concerns/options_manager.rb#L72-L75 | train |
yivo/confo-config | lib/confo/concerns/options_manager.rb | Confo.OptionsManager.public_set | def public_set(option, value)
# TODO Prevent subconfigs here
method = "#{option}="
respond_to?(method) ? send(method, value) : raw_set(option, value)
end | ruby | def public_set(option, value)
# TODO Prevent subconfigs here
method = "#{option}="
respond_to?(method) ? send(method, value) : raw_set(option, value)
end | [
"def",
"public_set",
"(",
"option",
",",
"value",
")",
"method",
"=",
"\"#{option}=\"",
"respond_to?",
"(",
"method",
")",
"?",
"send",
"(",
"method",
",",
"value",
")",
":",
"raw_set",
"(",
"option",
",",
"value",
")",
"end"
] | Method to set an option.
If there is an option accessor defined then it will be used.
In other cases +raw_set+ will be used. | [
"Method",
"to",
"set",
"an",
"option",
".",
"If",
"there",
"is",
"an",
"option",
"accessor",
"defined",
"then",
"it",
"will",
"be",
"used",
".",
"In",
"other",
"cases",
"+",
"raw_set",
"+",
"will",
"be",
"used",
"."
] | 4d5be81947b450c6daa329bcc111096ae629cf46 | https://github.com/yivo/confo-config/blob/4d5be81947b450c6daa329bcc111096ae629cf46/lib/confo/concerns/options_manager.rb#L100-L104 | train |
yivo/confo-config | lib/confo/concerns/options_manager.rb | Confo.OptionsManager.set? | def set?(arg, *rest_args)
if arg.kind_of?(Hash)
arg.each { |k, v| set(k, v) unless set?(k) }
nil
elsif rest_args.size > 0
set(arg, rest_args.first) unless set?(arg)
true
else
options_storage.has_key?(arg)
end
end | ruby | def set?(arg, *rest_args)
if arg.kind_of?(Hash)
arg.each { |k, v| set(k, v) unless set?(k) }
nil
elsif rest_args.size > 0
set(arg, rest_args.first) unless set?(arg)
true
else
options_storage.has_key?(arg)
end
end | [
"def",
"set?",
"(",
"arg",
",",
"*",
"rest_args",
")",
"if",
"arg",
".",
"kind_of?",
"(",
"Hash",
")",
"arg",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"set",
"(",
"k",
",",
"v",
")",
"unless",
"set?",
"(",
"k",
")",
"}",
"nil",
"elsif",
"rest_args",
".",
"size",
">",
"0",
"set",
"(",
"arg",
",",
"rest_args",
".",
"first",
")",
"unless",
"set?",
"(",
"arg",
")",
"true",
"else",
"options_storage",
".",
"has_key?",
"(",
"arg",
")",
"end",
"end"
] | Checks if option is set.
Works similar to set if value passed but sets only uninitialized options. | [
"Checks",
"if",
"option",
"is",
"set",
".",
"Works",
"similar",
"to",
"set",
"if",
"value",
"passed",
"but",
"sets",
"only",
"uninitialized",
"options",
"."
] | 4d5be81947b450c6daa329bcc111096ae629cf46 | https://github.com/yivo/confo-config/blob/4d5be81947b450c6daa329bcc111096ae629cf46/lib/confo/concerns/options_manager.rb#L135-L145 | train |
galetahub/page_parts | lib/page_parts/extension.rb | PageParts.Extension.find_or_build_page_part | def find_or_build_page_part(attr_name)
key = normalize_page_part_key(attr_name)
page_parts.detect { |record| record.key.to_s == key } || page_parts.build(key: key)
end | ruby | def find_or_build_page_part(attr_name)
key = normalize_page_part_key(attr_name)
page_parts.detect { |record| record.key.to_s == key } || page_parts.build(key: key)
end | [
"def",
"find_or_build_page_part",
"(",
"attr_name",
")",
"key",
"=",
"normalize_page_part_key",
"(",
"attr_name",
")",
"page_parts",
".",
"detect",
"{",
"|",
"record",
"|",
"record",
".",
"key",
".",
"to_s",
"==",
"key",
"}",
"||",
"page_parts",
".",
"build",
"(",
"key",
":",
"key",
")",
"end"
] | Find page part by key or build new record | [
"Find",
"page",
"part",
"by",
"key",
"or",
"build",
"new",
"record"
] | 97650adc9574a15ebdec3086d9f737b46f1ae101 | https://github.com/galetahub/page_parts/blob/97650adc9574a15ebdec3086d9f737b46f1ae101/lib/page_parts/extension.rb#L44-L47 | train |
oniram88/imdb-scan | lib/imdb/movie.rb | IMDB.Movie.poster | def poster
src = doc.at("#img_primary img")["src"] rescue nil
unless src.nil?
if src.match(/\._V1/)
return src.match(/(.*)\._V1.*(.jpg)/)[1, 2].join
else
return src
end
end
src
end | ruby | def poster
src = doc.at("#img_primary img")["src"] rescue nil
unless src.nil?
if src.match(/\._V1/)
return src.match(/(.*)\._V1.*(.jpg)/)[1, 2].join
else
return src
end
end
src
end | [
"def",
"poster",
"src",
"=",
"doc",
".",
"at",
"(",
"\"#img_primary img\"",
")",
"[",
"\"src\"",
"]",
"rescue",
"nil",
"unless",
"src",
".",
"nil?",
"if",
"src",
".",
"match",
"(",
"/",
"\\.",
"/",
")",
"return",
"src",
".",
"match",
"(",
"/",
"\\.",
"/",
")",
"[",
"1",
",",
"2",
"]",
".",
"join",
"else",
"return",
"src",
"end",
"end",
"src",
"end"
] | Get movie poster address
@return [String] | [
"Get",
"movie",
"poster",
"address"
] | e358adaba3db178df42c711c79c894f14d83c742 | https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/movie.rb#L32-L42 | train |
oniram88/imdb-scan | lib/imdb/movie.rb | IMDB.Movie.title | def title
doc.at("//head/meta[@name='title']")["content"].split(/\(.*\)/)[0].strip! ||
doc.at("h1.header").children.first.text.strip
end | ruby | def title
doc.at("//head/meta[@name='title']")["content"].split(/\(.*\)/)[0].strip! ||
doc.at("h1.header").children.first.text.strip
end | [
"def",
"title",
"doc",
".",
"at",
"(",
"\"//head/meta[@name='title']\"",
")",
"[",
"\"content\"",
"]",
".",
"split",
"(",
"/",
"\\(",
"\\)",
"/",
")",
"[",
"0",
"]",
".",
"strip!",
"||",
"doc",
".",
"at",
"(",
"\"h1.header\"",
")",
".",
"children",
".",
"first",
".",
"text",
".",
"strip",
"end"
] | Get movie title
@return [String] | [
"Get",
"movie",
"title"
] | e358adaba3db178df42c711c79c894f14d83c742 | https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/movie.rb#L46-L50 | train |
oniram88/imdb-scan | lib/imdb/movie.rb | IMDB.Movie.director_person | def director_person
begin
link=doc.xpath("//h4[contains(., 'Director')]/..").at('a[@href^="/name/nm"]')
profile = link['href'].match(/\/name\/nm([0-9]+)/)[1] rescue nil
IMDB::Person.new(profile) unless profile.nil?
rescue
nil
end
end | ruby | def director_person
begin
link=doc.xpath("//h4[contains(., 'Director')]/..").at('a[@href^="/name/nm"]')
profile = link['href'].match(/\/name\/nm([0-9]+)/)[1] rescue nil
IMDB::Person.new(profile) unless profile.nil?
rescue
nil
end
end | [
"def",
"director_person",
"begin",
"link",
"=",
"doc",
".",
"xpath",
"(",
"\"//h4[contains(., 'Director')]/..\"",
")",
".",
"at",
"(",
"'a[@href^=\"/name/nm\"]'",
")",
"profile",
"=",
"link",
"[",
"'href'",
"]",
".",
"match",
"(",
"/",
"\\/",
"\\/",
"/",
")",
"[",
"1",
"]",
"rescue",
"nil",
"IMDB",
"::",
"Person",
".",
"new",
"(",
"profile",
")",
"unless",
"profile",
".",
"nil?",
"rescue",
"nil",
"end",
"end"
] | Get Director Person class
@return [Person] | [
"Get",
"Director",
"Person",
"class"
] | e358adaba3db178df42c711c79c894f14d83c742 | https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/movie.rb#L103-L111 | train |
mLewisLogic/cisco-mse-client | lib/cisco-mse-client/stub.rb | CiscoMSE.Stub.stub! | def stub!
CiscoMSE::Endpoints::Location.any_instance.stub(:clients).and_return( Stub::Data::Location::CLIENTS )
end | ruby | def stub!
CiscoMSE::Endpoints::Location.any_instance.stub(:clients).and_return( Stub::Data::Location::CLIENTS )
end | [
"def",
"stub!",
"CiscoMSE",
"::",
"Endpoints",
"::",
"Location",
".",
"any_instance",
".",
"stub",
"(",
":clients",
")",
".",
"and_return",
"(",
"Stub",
"::",
"Data",
"::",
"Location",
"::",
"CLIENTS",
")",
"end"
] | Setup stubbing for all endpoints | [
"Setup",
"stubbing",
"for",
"all",
"endpoints"
] | 8d5a659349f7a42e5f130707780367c38061dfc6 | https://github.com/mLewisLogic/cisco-mse-client/blob/8d5a659349f7a42e5f130707780367c38061dfc6/lib/cisco-mse-client/stub.rb#L11-L13 | train |
ideonetwork/lato-blog | lib/lato_blog/interfaces/posts.rb | LatoBlog.Interface::Posts.blog__clean_post_parents | def blog__clean_post_parents
post_parents = LatoBlog::PostParent.all
post_parents.map { |pp| pp.destroy if pp.posts.empty? }
end | ruby | def blog__clean_post_parents
post_parents = LatoBlog::PostParent.all
post_parents.map { |pp| pp.destroy if pp.posts.empty? }
end | [
"def",
"blog__clean_post_parents",
"post_parents",
"=",
"LatoBlog",
"::",
"PostParent",
".",
"all",
"post_parents",
".",
"map",
"{",
"|",
"pp",
"|",
"pp",
".",
"destroy",
"if",
"pp",
".",
"posts",
".",
"empty?",
"}",
"end"
] | This function cleans all old post parents without any child. | [
"This",
"function",
"cleans",
"all",
"old",
"post",
"parents",
"without",
"any",
"child",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/posts.rb#L7-L10 | train |
ideonetwork/lato-blog | lib/lato_blog/interfaces/posts.rb | LatoBlog.Interface::Posts.blog__get_posts | def blog__get_posts(
order: nil,
language: nil,
category_permalink: nil,
category_permalink_AND: false,
category_id: nil,
category_id_AND: false,
tag_permalink: nil,
tag_permalink_AND: false,
tag_id: nil,
tag_id_AND: false,
search: nil,
page: nil,
per_page: nil
)
posts = LatoBlog::Post.published.joins(:post_parent).where('lato_blog_post_parents.publication_datetime <= ?', DateTime.now)
# apply filters
order = order && order == 'ASC' ? 'ASC' : 'DESC'
posts = _posts_filter_by_order(posts, order)
posts = _posts_filter_by_language(posts, language)
if category_permalink || category_id
posts = posts.joins(:categories)
posts = _posts_filter_by_category_permalink(posts, category_permalink, category_permalink_AND)
posts = _posts_filter_category_id(posts, category_id, category_id_AND)
end
if tag_permalink || tag_id
posts = posts.joins(:tags)
posts = _posts_filter_by_tag_permalink(posts, tag_permalink, tag_permalink_AND)
posts = _posts_filter_tag_id(posts, tag_id, tag_id_AND)
end
posts = _posts_filter_search(posts, search)
# take posts uniqueness
posts = posts.uniq(&:id)
# save total posts
total = posts.length
# manage pagination
page = page&.to_i || 1
per_page = per_page&.to_i || 20
posts = core__paginate_array(posts, per_page, page)
# return result
{
posts: posts && !posts.empty? ? posts.map(&:serialize) : [],
page: page,
per_page: per_page,
order: order,
total: total
}
end | ruby | def blog__get_posts(
order: nil,
language: nil,
category_permalink: nil,
category_permalink_AND: false,
category_id: nil,
category_id_AND: false,
tag_permalink: nil,
tag_permalink_AND: false,
tag_id: nil,
tag_id_AND: false,
search: nil,
page: nil,
per_page: nil
)
posts = LatoBlog::Post.published.joins(:post_parent).where('lato_blog_post_parents.publication_datetime <= ?', DateTime.now)
# apply filters
order = order && order == 'ASC' ? 'ASC' : 'DESC'
posts = _posts_filter_by_order(posts, order)
posts = _posts_filter_by_language(posts, language)
if category_permalink || category_id
posts = posts.joins(:categories)
posts = _posts_filter_by_category_permalink(posts, category_permalink, category_permalink_AND)
posts = _posts_filter_category_id(posts, category_id, category_id_AND)
end
if tag_permalink || tag_id
posts = posts.joins(:tags)
posts = _posts_filter_by_tag_permalink(posts, tag_permalink, tag_permalink_AND)
posts = _posts_filter_tag_id(posts, tag_id, tag_id_AND)
end
posts = _posts_filter_search(posts, search)
# take posts uniqueness
posts = posts.uniq(&:id)
# save total posts
total = posts.length
# manage pagination
page = page&.to_i || 1
per_page = per_page&.to_i || 20
posts = core__paginate_array(posts, per_page, page)
# return result
{
posts: posts && !posts.empty? ? posts.map(&:serialize) : [],
page: page,
per_page: per_page,
order: order,
total: total
}
end | [
"def",
"blog__get_posts",
"(",
"order",
":",
"nil",
",",
"language",
":",
"nil",
",",
"category_permalink",
":",
"nil",
",",
"category_permalink_AND",
":",
"false",
",",
"category_id",
":",
"nil",
",",
"category_id_AND",
":",
"false",
",",
"tag_permalink",
":",
"nil",
",",
"tag_permalink_AND",
":",
"false",
",",
"tag_id",
":",
"nil",
",",
"tag_id_AND",
":",
"false",
",",
"search",
":",
"nil",
",",
"page",
":",
"nil",
",",
"per_page",
":",
"nil",
")",
"posts",
"=",
"LatoBlog",
"::",
"Post",
".",
"published",
".",
"joins",
"(",
":post_parent",
")",
".",
"where",
"(",
"'lato_blog_post_parents.publication_datetime <= ?'",
",",
"DateTime",
".",
"now",
")",
"order",
"=",
"order",
"&&",
"order",
"==",
"'ASC'",
"?",
"'ASC'",
":",
"'DESC'",
"posts",
"=",
"_posts_filter_by_order",
"(",
"posts",
",",
"order",
")",
"posts",
"=",
"_posts_filter_by_language",
"(",
"posts",
",",
"language",
")",
"if",
"category_permalink",
"||",
"category_id",
"posts",
"=",
"posts",
".",
"joins",
"(",
":categories",
")",
"posts",
"=",
"_posts_filter_by_category_permalink",
"(",
"posts",
",",
"category_permalink",
",",
"category_permalink_AND",
")",
"posts",
"=",
"_posts_filter_category_id",
"(",
"posts",
",",
"category_id",
",",
"category_id_AND",
")",
"end",
"if",
"tag_permalink",
"||",
"tag_id",
"posts",
"=",
"posts",
".",
"joins",
"(",
":tags",
")",
"posts",
"=",
"_posts_filter_by_tag_permalink",
"(",
"posts",
",",
"tag_permalink",
",",
"tag_permalink_AND",
")",
"posts",
"=",
"_posts_filter_tag_id",
"(",
"posts",
",",
"tag_id",
",",
"tag_id_AND",
")",
"end",
"posts",
"=",
"_posts_filter_search",
"(",
"posts",
",",
"search",
")",
"posts",
"=",
"posts",
".",
"uniq",
"(",
"&",
":id",
")",
"total",
"=",
"posts",
".",
"length",
"page",
"=",
"page",
"&.",
"to_i",
"||",
"1",
"per_page",
"=",
"per_page",
"&.",
"to_i",
"||",
"20",
"posts",
"=",
"core__paginate_array",
"(",
"posts",
",",
"per_page",
",",
"page",
")",
"{",
"posts",
":",
"posts",
"&&",
"!",
"posts",
".",
"empty?",
"?",
"posts",
".",
"map",
"(",
"&",
":serialize",
")",
":",
"[",
"]",
",",
"page",
":",
"page",
",",
"per_page",
":",
"per_page",
",",
"order",
":",
"order",
",",
"total",
":",
"total",
"}",
"end"
] | This function returns an object with the list of posts with some filters. | [
"This",
"function",
"returns",
"an",
"object",
"with",
"the",
"list",
"of",
"posts",
"with",
"some",
"filters",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/posts.rb#L13-L65 | train |
ideonetwork/lato-blog | lib/lato_blog/interfaces/posts.rb | LatoBlog.Interface::Posts.blog__get_post | def blog__get_post(id: nil, permalink: nil)
return {} unless id || permalink
if id
post = LatoBlog::Post.find_by(id: id.to_i, meta_status: 'published')
else
post = LatoBlog::Post.find_by(meta_permalink: permalink, meta_status: 'published')
end
post.serialize
end | ruby | def blog__get_post(id: nil, permalink: nil)
return {} unless id || permalink
if id
post = LatoBlog::Post.find_by(id: id.to_i, meta_status: 'published')
else
post = LatoBlog::Post.find_by(meta_permalink: permalink, meta_status: 'published')
end
post.serialize
end | [
"def",
"blog__get_post",
"(",
"id",
":",
"nil",
",",
"permalink",
":",
"nil",
")",
"return",
"{",
"}",
"unless",
"id",
"||",
"permalink",
"if",
"id",
"post",
"=",
"LatoBlog",
"::",
"Post",
".",
"find_by",
"(",
"id",
":",
"id",
".",
"to_i",
",",
"meta_status",
":",
"'published'",
")",
"else",
"post",
"=",
"LatoBlog",
"::",
"Post",
".",
"find_by",
"(",
"meta_permalink",
":",
"permalink",
",",
"meta_status",
":",
"'published'",
")",
"end",
"post",
".",
"serialize",
"end"
] | This function returns a single post searched by id or permalink. | [
"This",
"function",
"returns",
"a",
"single",
"post",
"searched",
"by",
"id",
"or",
"permalink",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/posts.rb#L68-L78 | train |
3100/trahald | lib/trahald/redis-client.rb | Trahald.RedisClient.commit! | def commit!(message)
date = Time.now
@status_add.each{|name, body|
json = Article.new(name, body, date).to_json
zcard = @redis.zcard name
@redis.zadd name, zcard+1, json
@redis.sadd KEY_SET, name
@summary_redis.update MarkdownBody.new(name, body, date).summary
}
@remove_add.each{|name, latest_rank|
@redis.zremrange(name, 0, latest_rank)
}
@redis.set MODIFIED_DATE, date.to_s
end | ruby | def commit!(message)
date = Time.now
@status_add.each{|name, body|
json = Article.new(name, body, date).to_json
zcard = @redis.zcard name
@redis.zadd name, zcard+1, json
@redis.sadd KEY_SET, name
@summary_redis.update MarkdownBody.new(name, body, date).summary
}
@remove_add.each{|name, latest_rank|
@redis.zremrange(name, 0, latest_rank)
}
@redis.set MODIFIED_DATE, date.to_s
end | [
"def",
"commit!",
"(",
"message",
")",
"date",
"=",
"Time",
".",
"now",
"@status_add",
".",
"each",
"{",
"|",
"name",
",",
"body",
"|",
"json",
"=",
"Article",
".",
"new",
"(",
"name",
",",
"body",
",",
"date",
")",
".",
"to_json",
"zcard",
"=",
"@redis",
".",
"zcard",
"name",
"@redis",
".",
"zadd",
"name",
",",
"zcard",
"+",
"1",
",",
"json",
"@redis",
".",
"sadd",
"KEY_SET",
",",
"name",
"@summary_redis",
".",
"update",
"MarkdownBody",
".",
"new",
"(",
"name",
",",
"body",
",",
"date",
")",
".",
"summary",
"}",
"@remove_add",
".",
"each",
"{",
"|",
"name",
",",
"latest_rank",
"|",
"@redis",
".",
"zremrange",
"(",
"name",
",",
"0",
",",
"latest_rank",
")",
"}",
"@redis",
".",
"set",
"MODIFIED_DATE",
",",
"date",
".",
"to_s",
"end"
] | message is not used. | [
"message",
"is",
"not",
"used",
"."
] | a32bdd61ee3db1579c194eee2e898ae364f99870 | https://github.com/3100/trahald/blob/a32bdd61ee3db1579c194eee2e898ae364f99870/lib/trahald/redis-client.rb#L43-L56 | train |
gssbzn/slack-api-wrapper | lib/slack/request.rb | Slack.Request.make_query_string | def make_query_string(params)
clean_params(params).collect do |k, v|
CGI.escape(k) + '=' + CGI.escape(v)
end.join('&')
end | ruby | def make_query_string(params)
clean_params(params).collect do |k, v|
CGI.escape(k) + '=' + CGI.escape(v)
end.join('&')
end | [
"def",
"make_query_string",
"(",
"params",
")",
"clean_params",
"(",
"params",
")",
".",
"collect",
"do",
"|",
"k",
",",
"v",
"|",
"CGI",
".",
"escape",
"(",
"k",
")",
"+",
"'='",
"+",
"CGI",
".",
"escape",
"(",
"v",
")",
"end",
".",
"join",
"(",
"'&'",
")",
"end"
] | Convert params to query string
@param [Hash] params
API call arguments
@return [String] | [
"Convert",
"params",
"to",
"query",
"string"
] | cba33ad720295d7afa193662ff69574308552def | https://github.com/gssbzn/slack-api-wrapper/blob/cba33ad720295d7afa193662ff69574308552def/lib/slack/request.rb#L9-L13 | train |
gssbzn/slack-api-wrapper | lib/slack/request.rb | Slack.Request.do_http | def do_http(uri, request)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
# Let then know about us
request['User-Agent'] = 'SlackRubyAPIWrapper'
begin
http.request(request)
rescue OpenSSL::SSL::SSLError => e
raise Slack::Error, 'SSL error connecting to Slack.'
end
end | ruby | def do_http(uri, request)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
# Let then know about us
request['User-Agent'] = 'SlackRubyAPIWrapper'
begin
http.request(request)
rescue OpenSSL::SSL::SSLError => e
raise Slack::Error, 'SSL error connecting to Slack.'
end
end | [
"def",
"do_http",
"(",
"uri",
",",
"request",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"http",
".",
"use_ssl",
"=",
"true",
"request",
"[",
"'User-Agent'",
"]",
"=",
"'SlackRubyAPIWrapper'",
"begin",
"http",
".",
"request",
"(",
"request",
")",
"rescue",
"OpenSSL",
"::",
"SSL",
"::",
"SSLError",
"=>",
"e",
"raise",
"Slack",
"::",
"Error",
",",
"'SSL error connecting to Slack.'",
"end",
"end"
] | Handle http requests
@param [URI::HTTPS] uri
API uri
@param [Object] request
request object
@return [Net::HTTPResponse] | [
"Handle",
"http",
"requests"
] | cba33ad720295d7afa193662ff69574308552def | https://github.com/gssbzn/slack-api-wrapper/blob/cba33ad720295d7afa193662ff69574308552def/lib/slack/request.rb#L21-L31 | train |
essfeed/ruby-ess | lib/ess/ess.rb | ESS.ESS.find_coming | def find_coming n=10, start_time=nil
start_time = Time.now if start_time.nil?
feeds = []
channel.feed_list.each do |feed|
feed.dates.item_list.each do |item|
if item.type_attr == "standalone"
feeds << { :time => Time.parse(item.start.text!), :feed => feed }
elsif item.type_attr == "recurrent"
moments = parse_recurrent_date_item(item, n, start_time)
moments.each do |moment|
feeds << { :time => moment, :feed => feed }
end
elsif item.type_attr == "permanent"
start = Time.parse(item.start.text!)
if start > start_time
feeds << { :time => start, :feed => feed }
else
feeds << { :time => start_time, :feed => feed }
end
else
raise DTD::InvalidValueError, "the \"#{item.type_attr}\" is not valid for a date item type attribute"
end
end
end
feeds = feeds.delete_if { |x| x[:time] < start_time }
feeds.sort! { |x, y| x[:time] <=> y[:time] }
return feeds[0..n-1]
end | ruby | def find_coming n=10, start_time=nil
start_time = Time.now if start_time.nil?
feeds = []
channel.feed_list.each do |feed|
feed.dates.item_list.each do |item|
if item.type_attr == "standalone"
feeds << { :time => Time.parse(item.start.text!), :feed => feed }
elsif item.type_attr == "recurrent"
moments = parse_recurrent_date_item(item, n, start_time)
moments.each do |moment|
feeds << { :time => moment, :feed => feed }
end
elsif item.type_attr == "permanent"
start = Time.parse(item.start.text!)
if start > start_time
feeds << { :time => start, :feed => feed }
else
feeds << { :time => start_time, :feed => feed }
end
else
raise DTD::InvalidValueError, "the \"#{item.type_attr}\" is not valid for a date item type attribute"
end
end
end
feeds = feeds.delete_if { |x| x[:time] < start_time }
feeds.sort! { |x, y| x[:time] <=> y[:time] }
return feeds[0..n-1]
end | [
"def",
"find_coming",
"n",
"=",
"10",
",",
"start_time",
"=",
"nil",
"start_time",
"=",
"Time",
".",
"now",
"if",
"start_time",
".",
"nil?",
"feeds",
"=",
"[",
"]",
"channel",
".",
"feed_list",
".",
"each",
"do",
"|",
"feed",
"|",
"feed",
".",
"dates",
".",
"item_list",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"type_attr",
"==",
"\"standalone\"",
"feeds",
"<<",
"{",
":time",
"=>",
"Time",
".",
"parse",
"(",
"item",
".",
"start",
".",
"text!",
")",
",",
":feed",
"=>",
"feed",
"}",
"elsif",
"item",
".",
"type_attr",
"==",
"\"recurrent\"",
"moments",
"=",
"parse_recurrent_date_item",
"(",
"item",
",",
"n",
",",
"start_time",
")",
"moments",
".",
"each",
"do",
"|",
"moment",
"|",
"feeds",
"<<",
"{",
":time",
"=>",
"moment",
",",
":feed",
"=>",
"feed",
"}",
"end",
"elsif",
"item",
".",
"type_attr",
"==",
"\"permanent\"",
"start",
"=",
"Time",
".",
"parse",
"(",
"item",
".",
"start",
".",
"text!",
")",
"if",
"start",
">",
"start_time",
"feeds",
"<<",
"{",
":time",
"=>",
"start",
",",
":feed",
"=>",
"feed",
"}",
"else",
"feeds",
"<<",
"{",
":time",
"=>",
"start_time",
",",
":feed",
"=>",
"feed",
"}",
"end",
"else",
"raise",
"DTD",
"::",
"InvalidValueError",
",",
"\"the \\\"#{item.type_attr}\\\" is not valid for a date item type attribute\"",
"end",
"end",
"end",
"feeds",
"=",
"feeds",
".",
"delete_if",
"{",
"|",
"x",
"|",
"x",
"[",
":time",
"]",
"<",
"start_time",
"}",
"feeds",
".",
"sort!",
"{",
"|",
"x",
",",
"y",
"|",
"x",
"[",
":time",
"]",
"<=>",
"y",
"[",
":time",
"]",
"}",
"return",
"feeds",
"[",
"0",
"..",
"n",
"-",
"1",
"]",
"end"
] | Returns the next n events from the moment specified in the second
optional argument.
=== Parameters
[n = 10] how many coming events should be returned
[start_time] only events hapenning after this time will be considered
=== Returns
A list of hashes, sorted by event start time, each hash having
two keys:
[:time] start time of the event
[:feed] feed describing the event | [
"Returns",
"the",
"next",
"n",
"events",
"from",
"the",
"moment",
"specified",
"in",
"the",
"second",
"optional",
"argument",
"."
] | 25708228acd64e4abd0557e323f6e6adabf6e930 | https://github.com/essfeed/ruby-ess/blob/25708228acd64e4abd0557e323f6e6adabf6e930/lib/ess/ess.rb#L26-L53 | train |
essfeed/ruby-ess | lib/ess/ess.rb | ESS.ESS.find_between | def find_between start_time, end_time
feeds = []
channel.feed_list.each do |feed|
feed.dates.item_list.each do |item|
if item.type_attr == "standalone"
feed_start_time = Time.parse(item.start.text!)
if feed_start_time.between?(start_time, end_time)
feeds << { :time => feed_start_time, :feed => feed }
end
elsif item.type_attr == "recurrent"
moments = parse_recurrent_date_item(item, end_time, start_time)
moments.each do |moment|
if moment.between?(start_time, end_time)
feeds << { :time => moment, :feed => feed }
end
end
elsif item.type_attr == "permanent"
start = Time.parse(item.start.text!)
unless start > end_time
if start > start_time
feeds << { :time => start, :feed => feed }
else
feeds << { :time => start_time, :feed => feed }
end
end
else
raise DTD::InvalidValueError, "the \"#{item.type_attr}\" is not valid for a date item type attribute"
end
end
end
feeds.sort! { |x, y| x[:time] <=> y[:time] }
end | ruby | def find_between start_time, end_time
feeds = []
channel.feed_list.each do |feed|
feed.dates.item_list.each do |item|
if item.type_attr == "standalone"
feed_start_time = Time.parse(item.start.text!)
if feed_start_time.between?(start_time, end_time)
feeds << { :time => feed_start_time, :feed => feed }
end
elsif item.type_attr == "recurrent"
moments = parse_recurrent_date_item(item, end_time, start_time)
moments.each do |moment|
if moment.between?(start_time, end_time)
feeds << { :time => moment, :feed => feed }
end
end
elsif item.type_attr == "permanent"
start = Time.parse(item.start.text!)
unless start > end_time
if start > start_time
feeds << { :time => start, :feed => feed }
else
feeds << { :time => start_time, :feed => feed }
end
end
else
raise DTD::InvalidValueError, "the \"#{item.type_attr}\" is not valid for a date item type attribute"
end
end
end
feeds.sort! { |x, y| x[:time] <=> y[:time] }
end | [
"def",
"find_between",
"start_time",
",",
"end_time",
"feeds",
"=",
"[",
"]",
"channel",
".",
"feed_list",
".",
"each",
"do",
"|",
"feed",
"|",
"feed",
".",
"dates",
".",
"item_list",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"type_attr",
"==",
"\"standalone\"",
"feed_start_time",
"=",
"Time",
".",
"parse",
"(",
"item",
".",
"start",
".",
"text!",
")",
"if",
"feed_start_time",
".",
"between?",
"(",
"start_time",
",",
"end_time",
")",
"feeds",
"<<",
"{",
":time",
"=>",
"feed_start_time",
",",
":feed",
"=>",
"feed",
"}",
"end",
"elsif",
"item",
".",
"type_attr",
"==",
"\"recurrent\"",
"moments",
"=",
"parse_recurrent_date_item",
"(",
"item",
",",
"end_time",
",",
"start_time",
")",
"moments",
".",
"each",
"do",
"|",
"moment",
"|",
"if",
"moment",
".",
"between?",
"(",
"start_time",
",",
"end_time",
")",
"feeds",
"<<",
"{",
":time",
"=>",
"moment",
",",
":feed",
"=>",
"feed",
"}",
"end",
"end",
"elsif",
"item",
".",
"type_attr",
"==",
"\"permanent\"",
"start",
"=",
"Time",
".",
"parse",
"(",
"item",
".",
"start",
".",
"text!",
")",
"unless",
"start",
">",
"end_time",
"if",
"start",
">",
"start_time",
"feeds",
"<<",
"{",
":time",
"=>",
"start",
",",
":feed",
"=>",
"feed",
"}",
"else",
"feeds",
"<<",
"{",
":time",
"=>",
"start_time",
",",
":feed",
"=>",
"feed",
"}",
"end",
"end",
"else",
"raise",
"DTD",
"::",
"InvalidValueError",
",",
"\"the \\\"#{item.type_attr}\\\" is not valid for a date item type attribute\"",
"end",
"end",
"end",
"feeds",
".",
"sort!",
"{",
"|",
"x",
",",
"y",
"|",
"x",
"[",
":time",
"]",
"<=>",
"y",
"[",
":time",
"]",
"}",
"end"
] | Returns all events starting after the time specified by the first
parameter and before the time specified by the second parameter,
which accept regular Time objects.
=== Parameters
[start_time] will return only events starting after this moment
[end_time] will return only events starting before this moment
=== Returns
A list of hashes, sorted by event start time, each hash having
two keys:
[:time] start time of the event
[:feed] feed describing the event | [
"Returns",
"all",
"events",
"starting",
"after",
"the",
"time",
"specified",
"by",
"the",
"first",
"parameter",
"and",
"before",
"the",
"time",
"specified",
"by",
"the",
"second",
"parameter",
"which",
"accept",
"regular",
"Time",
"objects",
"."
] | 25708228acd64e4abd0557e323f6e6adabf6e930 | https://github.com/essfeed/ruby-ess/blob/25708228acd64e4abd0557e323f6e6adabf6e930/lib/ess/ess.rb#L73-L104 | train |
mochnatiy/flexible_accessibility | lib/flexible_accessibility/filters.rb | FlexibleAccessibility.Filters.check_permission_to_route | def check_permission_to_route
route_provider = RouteProvider.new(self.class)
if route_provider.verifiable_routes_list.include?(current_action)
if logged_user.nil?
raise UserNotLoggedInException.new(current_route, nil)
end
is_permitted = AccessProvider.action_permitted_for_user?(
current_route, logged_user
)
is_permitted ? allow_route : deny_route
elsif route_provider.non_verifiable_routes_list.include?(current_action)
allow_route
else
deny_route
end
end | ruby | def check_permission_to_route
route_provider = RouteProvider.new(self.class)
if route_provider.verifiable_routes_list.include?(current_action)
if logged_user.nil?
raise UserNotLoggedInException.new(current_route, nil)
end
is_permitted = AccessProvider.action_permitted_for_user?(
current_route, logged_user
)
is_permitted ? allow_route : deny_route
elsif route_provider.non_verifiable_routes_list.include?(current_action)
allow_route
else
deny_route
end
end | [
"def",
"check_permission_to_route",
"route_provider",
"=",
"RouteProvider",
".",
"new",
"(",
"self",
".",
"class",
")",
"if",
"route_provider",
".",
"verifiable_routes_list",
".",
"include?",
"(",
"current_action",
")",
"if",
"logged_user",
".",
"nil?",
"raise",
"UserNotLoggedInException",
".",
"new",
"(",
"current_route",
",",
"nil",
")",
"end",
"is_permitted",
"=",
"AccessProvider",
".",
"action_permitted_for_user?",
"(",
"current_route",
",",
"logged_user",
")",
"is_permitted",
"?",
"allow_route",
":",
"deny_route",
"elsif",
"route_provider",
".",
"non_verifiable_routes_list",
".",
"include?",
"(",
"current_action",
")",
"allow_route",
"else",
"deny_route",
"end",
"end"
] | Check access to route and we expected the existing of current_user helper | [
"Check",
"access",
"to",
"route",
"and",
"we",
"expected",
"the",
"existing",
"of",
"current_user",
"helper"
] | ffd7f76e0765aa28909625b3bfa282264b8a5195 | https://github.com/mochnatiy/flexible_accessibility/blob/ffd7f76e0765aa28909625b3bfa282264b8a5195/lib/flexible_accessibility/filters.rb#L41-L59 | train |
bogrobotten/fetch | lib/fetch/base.rb | Fetch.Base.fetch | def fetch
requests = instantiate_modules.select(&:fetch?).map(&:requests).flatten
total, done = requests.size, 0
update_progress(total, done)
before_fetch
backend.new(requests).run do
update_progress(total, done += 1)
end
after_fetch
true
rescue => e
error(e)
raise e
end | ruby | def fetch
requests = instantiate_modules.select(&:fetch?).map(&:requests).flatten
total, done = requests.size, 0
update_progress(total, done)
before_fetch
backend.new(requests).run do
update_progress(total, done += 1)
end
after_fetch
true
rescue => e
error(e)
raise e
end | [
"def",
"fetch",
"requests",
"=",
"instantiate_modules",
".",
"select",
"(",
"&",
":fetch?",
")",
".",
"map",
"(",
"&",
":requests",
")",
".",
"flatten",
"total",
",",
"done",
"=",
"requests",
".",
"size",
",",
"0",
"update_progress",
"(",
"total",
",",
"done",
")",
"before_fetch",
"backend",
".",
"new",
"(",
"requests",
")",
".",
"run",
"do",
"update_progress",
"(",
"total",
",",
"done",
"+=",
"1",
")",
"end",
"after_fetch",
"true",
"rescue",
"=>",
"e",
"error",
"(",
"e",
")",
"raise",
"e",
"end"
] | Begin fetching.
Will run synchronous fetches first and async fetches afterwards.
Updates progress when each module finishes its fetch. | [
"Begin",
"fetching",
".",
"Will",
"run",
"synchronous",
"fetches",
"first",
"and",
"async",
"fetches",
"afterwards",
".",
"Updates",
"progress",
"when",
"each",
"module",
"finishes",
"its",
"fetch",
"."
] | 8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f | https://github.com/bogrobotten/fetch/blob/8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f/lib/fetch/base.rb#L35-L53 | train |
bogrobotten/fetch | lib/fetch/base.rb | Fetch.Base.instantiate_modules | def instantiate_modules
mods = Array(modules)
mods = load!(mods) if callback?(:load)
Array(mods).map do |klass|
init!(klass) || klass.new(fetchable)
end
end | ruby | def instantiate_modules
mods = Array(modules)
mods = load!(mods) if callback?(:load)
Array(mods).map do |klass|
init!(klass) || klass.new(fetchable)
end
end | [
"def",
"instantiate_modules",
"mods",
"=",
"Array",
"(",
"modules",
")",
"mods",
"=",
"load!",
"(",
"mods",
")",
"if",
"callback?",
"(",
":load",
")",
"Array",
"(",
"mods",
")",
".",
"map",
"do",
"|",
"klass",
"|",
"init!",
"(",
"klass",
")",
"||",
"klass",
".",
"new",
"(",
"fetchable",
")",
"end",
"end"
] | Array of instantiated fetch modules. | [
"Array",
"of",
"instantiated",
"fetch",
"modules",
"."
] | 8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f | https://github.com/bogrobotten/fetch/blob/8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f/lib/fetch/base.rb#L61-L67 | train |
bogrobotten/fetch | lib/fetch/base.rb | Fetch.Base.update_progress | def update_progress(total, done)
percentage = total.zero? ? 100 : ((done.to_f / total) * 100).to_i
progress(percentage)
end | ruby | def update_progress(total, done)
percentage = total.zero? ? 100 : ((done.to_f / total) * 100).to_i
progress(percentage)
end | [
"def",
"update_progress",
"(",
"total",
",",
"done",
")",
"percentage",
"=",
"total",
".",
"zero?",
"?",
"100",
":",
"(",
"(",
"done",
".",
"to_f",
"/",
"total",
")",
"*",
"100",
")",
".",
"to_i",
"progress",
"(",
"percentage",
")",
"end"
] | Updates progress with a percentage calculated from +total+ and +done+. | [
"Updates",
"progress",
"with",
"a",
"percentage",
"calculated",
"from",
"+",
"total",
"+",
"and",
"+",
"done",
"+",
"."
] | 8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f | https://github.com/bogrobotten/fetch/blob/8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f/lib/fetch/base.rb#L70-L73 | train |
Velir/kaltura_fu | lib/kaltura_fu/session.rb | KalturaFu.Session.generate_session_key | def generate_session_key
self.check_for_client_session
raise "Missing Administrator Secret" unless KalturaFu.config.administrator_secret
@@session_key = @@client.session_service.start(KalturaFu.config.administrator_secret,'',Kaltura::Constants::SessionType::ADMIN)
@@client.ks = @@session_key
rescue Kaltura::APIError => e
puts e.message
end | ruby | def generate_session_key
self.check_for_client_session
raise "Missing Administrator Secret" unless KalturaFu.config.administrator_secret
@@session_key = @@client.session_service.start(KalturaFu.config.administrator_secret,'',Kaltura::Constants::SessionType::ADMIN)
@@client.ks = @@session_key
rescue Kaltura::APIError => e
puts e.message
end | [
"def",
"generate_session_key",
"self",
".",
"check_for_client_session",
"raise",
"\"Missing Administrator Secret\"",
"unless",
"KalturaFu",
".",
"config",
".",
"administrator_secret",
"@@session_key",
"=",
"@@client",
".",
"session_service",
".",
"start",
"(",
"KalturaFu",
".",
"config",
".",
"administrator_secret",
",",
"''",
",",
"Kaltura",
"::",
"Constants",
"::",
"SessionType",
"::",
"ADMIN",
")",
"@@client",
".",
"ks",
"=",
"@@session_key",
"rescue",
"Kaltura",
"::",
"APIError",
"=>",
"e",
"puts",
"e",
".",
"message",
"end"
] | Generates a Kaltura ks and adds it to the KalturaFu client object.
@return [String] a Kaltura KS. | [
"Generates",
"a",
"Kaltura",
"ks",
"and",
"adds",
"it",
"to",
"the",
"KalturaFu",
"client",
"object",
"."
] | 539e476786d1fd2257b90dfb1e50c2c75ae75bdd | https://github.com/Velir/kaltura_fu/blob/539e476786d1fd2257b90dfb1e50c2c75ae75bdd/lib/kaltura_fu/session.rb#L54-L62 | train |
hexorx/oxmlk | lib/oxmlk/attr.rb | OxMlk.Attr.from_xml | def from_xml(data)
procs.inject(XML::Node.from(data)[tag]) {|d,p| p.call(d) rescue d}
end | ruby | def from_xml(data)
procs.inject(XML::Node.from(data)[tag]) {|d,p| p.call(d) rescue d}
end | [
"def",
"from_xml",
"(",
"data",
")",
"procs",
".",
"inject",
"(",
"XML",
"::",
"Node",
".",
"from",
"(",
"data",
")",
"[",
"tag",
"]",
")",
"{",
"|",
"d",
",",
"p",
"|",
"p",
".",
"call",
"(",
"d",
")",
"rescue",
"d",
"}",
"end"
] | Creates a new instance of Attr to be used as a template for converting
XML to objects and from objects to XML
@param [Symbol,String] name Sets the accessor methods for this attr.
It is also used to guess defaults for :from and :as.
For example if it ends with '?' and :as isn't set
it will treat it as a boolean.
@param [Hash] o the options for the new attr definition
@option o [Symbol,String] :from (tag_proc.call(name))
Tells OxMlk what the name of the XML attribute is.
It defaults to name processed by the tag_proc.
@option o [Symbol,String,Proc,Array<Symbol,String,Proc>] :as
Tells OxMlk how to translate the XML.
The argument is coerced into a Proc and applied to the string found in the XML attribute.
If an Array is passed each Proc is applied in order with the results
of the first being passed to the second and so on. If it isn't set
and name ends in '?' it processes it as if :bool was passed otherwise
it treats it as a string with no processing.
Includes the following named Procs: Integer, Float, String, Symbol and :bool.
@option o [Proc] :tag_proc (proc {|x| x}) Proc used to guess :from.
The Proc is applied to name and the results used to find the XML attribute
if :from isn't set.
@yield [String] Adds anothe Proc that is applied to the value.
Finds @tag in data and applies procs. | [
"Creates",
"a",
"new",
"instance",
"of",
"Attr",
"to",
"be",
"used",
"as",
"a",
"template",
"for",
"converting",
"XML",
"to",
"objects",
"and",
"from",
"objects",
"to",
"XML"
] | bf4be00ece9b13a3357d8eb324e2a571d2715f79 | https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk/attr.rb#L48-L50 | train |
erniebrodeur/bini | lib/bini/optparser.rb | Bini.OptionParser.mash | def mash(h)
h.merge! @options
@options.clear
h.each {|k,v| self[k] = v}
end | ruby | def mash(h)
h.merge! @options
@options.clear
h.each {|k,v| self[k] = v}
end | [
"def",
"mash",
"(",
"h",
")",
"h",
".",
"merge!",
"@options",
"@options",
".",
"clear",
"h",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"self",
"[",
"k",
"]",
"=",
"v",
"}",
"end"
] | merge takes in a set of values and overwrites the previous values.
mash does this in reverse. | [
"merge",
"takes",
"in",
"a",
"set",
"of",
"values",
"and",
"overwrites",
"the",
"previous",
"values",
".",
"mash",
"does",
"this",
"in",
"reverse",
"."
] | 4bcc1a90e877c7e77fcf97d4bf91b894d6824a2b | https://github.com/erniebrodeur/bini/blob/4bcc1a90e877c7e77fcf97d4bf91b894d6824a2b/lib/bini/optparser.rb#L47-L51 | train |
nicholas-johnson/content_driven | lib/content_driven/routes.rb | ContentDriven.Routes.content_for | def content_for route
parts = route.split("/").delete_if &:empty?
content = parts.inject(self) do |page, part|
page.children[part.to_sym] if page
end
content
end | ruby | def content_for route
parts = route.split("/").delete_if &:empty?
content = parts.inject(self) do |page, part|
page.children[part.to_sym] if page
end
content
end | [
"def",
"content_for",
"route",
"parts",
"=",
"route",
".",
"split",
"(",
"\"/\"",
")",
".",
"delete_if",
"&",
":empty?",
"content",
"=",
"parts",
".",
"inject",
"(",
"self",
")",
"do",
"|",
"page",
",",
"part",
"|",
"page",
".",
"children",
"[",
"part",
".",
"to_sym",
"]",
"if",
"page",
"end",
"content",
"end"
] | Walks the tree based on a url and returns the requested page
Will return nil if the page does not exist | [
"Walks",
"the",
"tree",
"based",
"on",
"a",
"url",
"and",
"returns",
"the",
"requested",
"page",
"Will",
"return",
"nil",
"if",
"the",
"page",
"does",
"not",
"exist"
] | ac362677810e45d95ce21975fed841d3d65f11d7 | https://github.com/nicholas-johnson/content_driven/blob/ac362677810e45d95ce21975fed841d3d65f11d7/lib/content_driven/routes.rb#L5-L11 | train |
checkdin/checkdin-ruby | lib/checkdin/won_rewards.rb | Checkdin.WonRewards.won_rewards | def won_rewards(options={})
response = connection.get do |req|
req.url "won_rewards", options
end
return_error_or_body(response)
end | ruby | def won_rewards(options={})
response = connection.get do |req|
req.url "won_rewards", options
end
return_error_or_body(response)
end | [
"def",
"won_rewards",
"(",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"connection",
".",
"get",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"\"won_rewards\"",
",",
"options",
"end",
"return_error_or_body",
"(",
"response",
")",
"end"
] | Get a list of all won rewards for the authenticating client.
@param [Hash] options
@option options Integer :campaign_id - Only return won rewards for this campaign.
@option options Integer :user_id - Only return won rewards for this user.
@option options Integer :promotion_id - Only return won rewards for this promotion.
@option options Integer :limit - The maximum number of records to return. | [
"Get",
"a",
"list",
"of",
"all",
"won",
"rewards",
"for",
"the",
"authenticating",
"client",
"."
] | c3c4b38b0f8c710e1f805100dcf3a70649215b48 | https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/won_rewards.rb#L21-L26 | train |
octoai/gem-octocore-cassandra | lib/octocore-cassandra/models/enterprise/authorization.rb | Octo.Authorization.generate_password | def generate_password
if(self.password.nil?)
self.password = Digest::SHA1.hexdigest(self.username + self.enterprise_id)
else
self.password = Digest::SHA1.hexdigest(self.password + self.enterprise_id)
end
end | ruby | def generate_password
if(self.password.nil?)
self.password = Digest::SHA1.hexdigest(self.username + self.enterprise_id)
else
self.password = Digest::SHA1.hexdigest(self.password + self.enterprise_id)
end
end | [
"def",
"generate_password",
"if",
"(",
"self",
".",
"password",
".",
"nil?",
")",
"self",
".",
"password",
"=",
"Digest",
"::",
"SHA1",
".",
"hexdigest",
"(",
"self",
".",
"username",
"+",
"self",
".",
"enterprise_id",
")",
"else",
"self",
".",
"password",
"=",
"Digest",
"::",
"SHA1",
".",
"hexdigest",
"(",
"self",
".",
"password",
"+",
"self",
".",
"enterprise_id",
")",
"end",
"end"
] | Check or Generate client password | [
"Check",
"or",
"Generate",
"client",
"password"
] | c0977dce5ba0eb174ff810f161aba151069935df | https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/models/enterprise/authorization.rb#L35-L41 | train |
octoai/gem-octocore-cassandra | lib/octocore-cassandra/models/enterprise/authorization.rb | Octo.Authorization.kong_requests | def kong_requests
kong_config = Octo.get_config :kong
if kong_config[:enabled]
url = '/consumers/'
payload = {
username: self.username,
custom_id: self.enterprise_id
}
process_kong_request(url, :PUT, payload)
create_keyauth( self.username, self.apikey)
end
end | ruby | def kong_requests
kong_config = Octo.get_config :kong
if kong_config[:enabled]
url = '/consumers/'
payload = {
username: self.username,
custom_id: self.enterprise_id
}
process_kong_request(url, :PUT, payload)
create_keyauth( self.username, self.apikey)
end
end | [
"def",
"kong_requests",
"kong_config",
"=",
"Octo",
".",
"get_config",
":kong",
"if",
"kong_config",
"[",
":enabled",
"]",
"url",
"=",
"'/consumers/'",
"payload",
"=",
"{",
"username",
":",
"self",
".",
"username",
",",
"custom_id",
":",
"self",
".",
"enterprise_id",
"}",
"process_kong_request",
"(",
"url",
",",
":PUT",
",",
"payload",
")",
"create_keyauth",
"(",
"self",
".",
"username",
",",
"self",
".",
"apikey",
")",
"end",
"end"
] | Perform Kong Operations after creating client | [
"Perform",
"Kong",
"Operations",
"after",
"creating",
"client"
] | c0977dce5ba0eb174ff810f161aba151069935df | https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/models/enterprise/authorization.rb#L44-L56 | train |
redding/ns-options | lib/ns-options/proxy.rb | NsOptions::Proxy.ProxyMethods.option | def option(name, *args, &block)
__proxy_options__.option(name, *args, &block)
NsOptions::ProxyMethod.new(self, name, 'an option').define($stdout, caller)
end | ruby | def option(name, *args, &block)
__proxy_options__.option(name, *args, &block)
NsOptions::ProxyMethod.new(self, name, 'an option').define($stdout, caller)
end | [
"def",
"option",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"__proxy_options__",
".",
"option",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"NsOptions",
"::",
"ProxyMethod",
".",
"new",
"(",
"self",
",",
"name",
",",
"'an option'",
")",
".",
"define",
"(",
"$stdout",
",",
"caller",
")",
"end"
] | pass thru namespace methods to the proxied NAMESPACE handler | [
"pass",
"thru",
"namespace",
"methods",
"to",
"the",
"proxied",
"NAMESPACE",
"handler"
] | 63618a18e7a1d270dffc5a3cfea70ef45569e061 | https://github.com/redding/ns-options/blob/63618a18e7a1d270dffc5a3cfea70ef45569e061/lib/ns-options/proxy.rb#L78-L81 | train |
redding/ns-options | lib/ns-options/proxy.rb | NsOptions::Proxy.ProxyMethods.method_missing | def method_missing(meth, *args, &block)
if (po = __proxy_options__) && po.respond_to?(meth.to_s)
po.send(meth.to_s, *args, &block)
else
super
end
end | ruby | def method_missing(meth, *args, &block)
if (po = __proxy_options__) && po.respond_to?(meth.to_s)
po.send(meth.to_s, *args, &block)
else
super
end
end | [
"def",
"method_missing",
"(",
"meth",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"(",
"po",
"=",
"__proxy_options__",
")",
"&&",
"po",
".",
"respond_to?",
"(",
"meth",
".",
"to_s",
")",
"po",
".",
"send",
"(",
"meth",
".",
"to_s",
",",
"*",
"args",
",",
"&",
"block",
")",
"else",
"super",
"end",
"end"
] | for everything else, send to the proxied NAMESPACE handler
at this point it really just enables dynamic options writers | [
"for",
"everything",
"else",
"send",
"to",
"the",
"proxied",
"NAMESPACE",
"handler",
"at",
"this",
"point",
"it",
"really",
"just",
"enables",
"dynamic",
"options",
"writers"
] | 63618a18e7a1d270dffc5a3cfea70ef45569e061 | https://github.com/redding/ns-options/blob/63618a18e7a1d270dffc5a3cfea70ef45569e061/lib/ns-options/proxy.rb#L110-L116 | train |
Ptico/sequoia | lib/sequoia/configurable.rb | Sequoia.Configurable.configure | def configure(env=:default, &block)
environment = config_attributes[env.to_sym]
Builder.new(environment, &block)
end | ruby | def configure(env=:default, &block)
environment = config_attributes[env.to_sym]
Builder.new(environment, &block)
end | [
"def",
"configure",
"(",
"env",
"=",
":default",
",",
"&",
"block",
")",
"environment",
"=",
"config_attributes",
"[",
"env",
".",
"to_sym",
"]",
"Builder",
".",
"new",
"(",
"environment",
",",
"&",
"block",
")",
"end"
] | Add or merge environment configuration
Params:
- env {Symbol} Environment to set (optional, default: :default)
Yields: block with key-value definitions
Returns: {Sequoia::Builder} builder instance | [
"Add",
"or",
"merge",
"environment",
"configuration"
] | d3645d8bedd27eb0149928c09678d12c4082c787 | https://github.com/Ptico/sequoia/blob/d3645d8bedd27eb0149928c09678d12c4082c787/lib/sequoia/configurable.rb#L19-L23 | train |
Ptico/sequoia | lib/sequoia/configurable.rb | Sequoia.Configurable.build_configuration | def build_configuration(env=nil)
result = config_attributes[:default]
result.deep_merge!(config_attributes[env.to_sym]) if env
Entity.create(result)
end | ruby | def build_configuration(env=nil)
result = config_attributes[:default]
result.deep_merge!(config_attributes[env.to_sym]) if env
Entity.create(result)
end | [
"def",
"build_configuration",
"(",
"env",
"=",
"nil",
")",
"result",
"=",
"config_attributes",
"[",
":default",
"]",
"result",
".",
"deep_merge!",
"(",
"config_attributes",
"[",
"env",
".",
"to_sym",
"]",
")",
"if",
"env",
"Entity",
".",
"create",
"(",
"result",
")",
"end"
] | Build configuration object
Params:
- env {Symbol} Environment to build
Returns: {Sequoia::Entity} builded configuration object | [
"Build",
"configuration",
"object"
] | d3645d8bedd27eb0149928c09678d12c4082c787 | https://github.com/Ptico/sequoia/blob/d3645d8bedd27eb0149928c09678d12c4082c787/lib/sequoia/configurable.rb#L33-L37 | train |
pdorrell/regenerate | lib/regenerate/web-page.rb | Regenerate.WebPage.initializePageObject | def initializePageObject(pageObject)
@pageObject = pageObject
pathDepth = @pathComponents.length-1
rootLinkPath = "../" * pathDepth
setPageObjectInstanceVar("@fileName", @fileName)
setPageObjectInstanceVar("@baseDir", File.dirname(@fileName))
setPageObjectInstanceVar("@baseFileName", File.basename(@fileName))
setPageObjectInstanceVar("@pathDepth", pathDepth)
setPageObjectInstanceVar("@pathComponents", @pathComponents)
setPageObjectInstanceVar("@rootLinkPath", rootLinkPath)
setPageObjectInstanceVar("@baseUrl", rootLinkPath)
setPageObjectInstanceVar("@site", @site)
@initialInstanceVariables = Set.new(@pageObject.instance_variables)
pageObject.postInitialize
end | ruby | def initializePageObject(pageObject)
@pageObject = pageObject
pathDepth = @pathComponents.length-1
rootLinkPath = "../" * pathDepth
setPageObjectInstanceVar("@fileName", @fileName)
setPageObjectInstanceVar("@baseDir", File.dirname(@fileName))
setPageObjectInstanceVar("@baseFileName", File.basename(@fileName))
setPageObjectInstanceVar("@pathDepth", pathDepth)
setPageObjectInstanceVar("@pathComponents", @pathComponents)
setPageObjectInstanceVar("@rootLinkPath", rootLinkPath)
setPageObjectInstanceVar("@baseUrl", rootLinkPath)
setPageObjectInstanceVar("@site", @site)
@initialInstanceVariables = Set.new(@pageObject.instance_variables)
pageObject.postInitialize
end | [
"def",
"initializePageObject",
"(",
"pageObject",
")",
"@pageObject",
"=",
"pageObject",
"pathDepth",
"=",
"@pathComponents",
".",
"length",
"-",
"1",
"rootLinkPath",
"=",
"\"../\"",
"*",
"pathDepth",
"setPageObjectInstanceVar",
"(",
"\"@fileName\"",
",",
"@fileName",
")",
"setPageObjectInstanceVar",
"(",
"\"@baseDir\"",
",",
"File",
".",
"dirname",
"(",
"@fileName",
")",
")",
"setPageObjectInstanceVar",
"(",
"\"@baseFileName\"",
",",
"File",
".",
"basename",
"(",
"@fileName",
")",
")",
"setPageObjectInstanceVar",
"(",
"\"@pathDepth\"",
",",
"pathDepth",
")",
"setPageObjectInstanceVar",
"(",
"\"@pathComponents\"",
",",
"@pathComponents",
")",
"setPageObjectInstanceVar",
"(",
"\"@rootLinkPath\"",
",",
"rootLinkPath",
")",
"setPageObjectInstanceVar",
"(",
"\"@baseUrl\"",
",",
"rootLinkPath",
")",
"setPageObjectInstanceVar",
"(",
"\"@site\"",
",",
"@site",
")",
"@initialInstanceVariables",
"=",
"Set",
".",
"new",
"(",
"@pageObject",
".",
"instance_variables",
")",
"pageObject",
".",
"postInitialize",
"end"
] | The absolute name of the source file
initialise the "page object", which is the object that "owns" the defined instance variables,
and the object in whose context the Ruby components are evaluated
Three special instance variable values are set - @fileName, @baseDir, @baseFileName,
so that they can be accessed, if necessary, by Ruby code in the Ruby code components.
(if this is called a second time, it overrides whatever was set the first time)
Notes on special instance variables -
@fileName and @baseDir are the absolute paths of the source file and it's containing directory.
They would be used in Ruby code that looked for other files with names or locations relative to these two.
They would generally not be expected to appear in the output content.
@baseFileName is the name of the file without any directory path components. In some cases it might be
used within output content. | [
"The",
"absolute",
"name",
"of",
"the",
"source",
"file",
"initialise",
"the",
"page",
"object",
"which",
"is",
"the",
"object",
"that",
"owns",
"the",
"defined",
"instance",
"variables",
"and",
"the",
"object",
"in",
"whose",
"context",
"the",
"Ruby",
"components",
"are",
"evaluated",
"Three",
"special",
"instance",
"variable",
"values",
"are",
"set",
"-"
] | 31f3beb3ff9b45384a90f20fed61be20f39da0d4 | https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L358-L372 | train |
pdorrell/regenerate | lib/regenerate/web-page.rb | Regenerate.WebPage.startNewComponent | def startNewComponent(component, startComment = nil)
component.parentPage = self
@currentComponent = component
#puts "startNewComponent, @currentComponent = #{@currentComponent.inspect}"
@components << component
if startComment
component.processStartComment(startComment)
end
end | ruby | def startNewComponent(component, startComment = nil)
component.parentPage = self
@currentComponent = component
#puts "startNewComponent, @currentComponent = #{@currentComponent.inspect}"
@components << component
if startComment
component.processStartComment(startComment)
end
end | [
"def",
"startNewComponent",
"(",
"component",
",",
"startComment",
"=",
"nil",
")",
"component",
".",
"parentPage",
"=",
"self",
"@currentComponent",
"=",
"component",
"@components",
"<<",
"component",
"if",
"startComment",
"component",
".",
"processStartComment",
"(",
"startComment",
")",
"end",
"end"
] | Add a newly started page component to this page
Also process the start comment, unless it was a static HTML component, in which case there is
not start comment. | [
"Add",
"a",
"newly",
"started",
"page",
"component",
"to",
"this",
"page",
"Also",
"process",
"the",
"start",
"comment",
"unless",
"it",
"was",
"a",
"static",
"HTML",
"component",
"in",
"which",
"case",
"there",
"is",
"not",
"start",
"comment",
"."
] | 31f3beb3ff9b45384a90f20fed61be20f39da0d4 | https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L393-L401 | train |
pdorrell/regenerate | lib/regenerate/web-page.rb | Regenerate.WebPage.writeRegeneratedFile | def writeRegeneratedFile(outFile, makeBackup, checkNoChanges)
puts "writeRegeneratedFile, #{outFile}, makeBackup = #{makeBackup}, checkNoChanges = #{checkNoChanges}"
if makeBackup
backupFileName = makeBackupFile(outFile)
end
File.open(outFile, "w") do |f|
for component in @components do
f.write(component.output)
end
end
puts " wrote regenerated page to #{outFile}"
if checkNoChanges
if !makeBackup
raise Exception.new("writeRegeneratedFile #{outFile}: checkNoChanges specified, but no backup was made")
end
checkAndEnsureOutputFileUnchanged(outFile, backupFileName)
end
end | ruby | def writeRegeneratedFile(outFile, makeBackup, checkNoChanges)
puts "writeRegeneratedFile, #{outFile}, makeBackup = #{makeBackup}, checkNoChanges = #{checkNoChanges}"
if makeBackup
backupFileName = makeBackupFile(outFile)
end
File.open(outFile, "w") do |f|
for component in @components do
f.write(component.output)
end
end
puts " wrote regenerated page to #{outFile}"
if checkNoChanges
if !makeBackup
raise Exception.new("writeRegeneratedFile #{outFile}: checkNoChanges specified, but no backup was made")
end
checkAndEnsureOutputFileUnchanged(outFile, backupFileName)
end
end | [
"def",
"writeRegeneratedFile",
"(",
"outFile",
",",
"makeBackup",
",",
"checkNoChanges",
")",
"puts",
"\"writeRegeneratedFile, #{outFile}, makeBackup = #{makeBackup}, checkNoChanges = #{checkNoChanges}\"",
"if",
"makeBackup",
"backupFileName",
"=",
"makeBackupFile",
"(",
"outFile",
")",
"end",
"File",
".",
"open",
"(",
"outFile",
",",
"\"w\"",
")",
"do",
"|",
"f",
"|",
"for",
"component",
"in",
"@components",
"do",
"f",
".",
"write",
"(",
"component",
".",
"output",
")",
"end",
"end",
"puts",
"\" wrote regenerated page to #{outFile}\"",
"if",
"checkNoChanges",
"if",
"!",
"makeBackup",
"raise",
"Exception",
".",
"new",
"(",
"\"writeRegeneratedFile #{outFile}: checkNoChanges specified, but no backup was made\"",
")",
"end",
"checkAndEnsureOutputFileUnchanged",
"(",
"outFile",
",",
"backupFileName",
")",
"end",
"end"
] | Write the output of the page components to the output file (optionally checking that
there are no differences between the new output and the existing output. | [
"Write",
"the",
"output",
"of",
"the",
"page",
"components",
"to",
"the",
"output",
"file",
"(",
"optionally",
"checking",
"that",
"there",
"are",
"no",
"differences",
"between",
"the",
"new",
"output",
"and",
"the",
"existing",
"output",
"."
] | 31f3beb3ff9b45384a90f20fed61be20f39da0d4 | https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L519-L536 | train |
pdorrell/regenerate | lib/regenerate/web-page.rb | Regenerate.WebPage.readFileLines | def readFileLines
puts "Reading source file #{@fileName} ..."
lineNumber = 0
File.open(@fileName).each_line do |line|
line.chomp!
lineNumber += 1 # track line numbers for when Ruby code needs to be executed (i.e. to populate stack traces)
#puts "line #{lineNumber}: #{line}"
commentLineMatch = COMMENT_LINE_REGEX.match(line)
if commentLineMatch # it matches the Regenerate command line regex (but might not actually be a command ...)
parsedCommandLine = ParsedRegenerateCommentLine.new(line, commentLineMatch)
#puts "parsedCommandLine = #{parsedCommandLine}"
if parsedCommandLine.isRegenerateCommentLine # if it is a Regenerate command line
parsedCommandLine.checkIsValid # check it is valid, and then,
processCommandLine(parsedCommandLine, lineNumber) # process the command line
else
processTextLine(line, lineNumber) # process a text line which is not a Regenerate command line
end
else
processTextLine(line, lineNumber) # process a text line which is not a Regenerate command line
end
end
# After processing all source lines, the only unfinished page component permitted is a static HTML component.
finishAtEndOfSourceFile
#puts "Finished reading #{@fileName}."
end | ruby | def readFileLines
puts "Reading source file #{@fileName} ..."
lineNumber = 0
File.open(@fileName).each_line do |line|
line.chomp!
lineNumber += 1 # track line numbers for when Ruby code needs to be executed (i.e. to populate stack traces)
#puts "line #{lineNumber}: #{line}"
commentLineMatch = COMMENT_LINE_REGEX.match(line)
if commentLineMatch # it matches the Regenerate command line regex (but might not actually be a command ...)
parsedCommandLine = ParsedRegenerateCommentLine.new(line, commentLineMatch)
#puts "parsedCommandLine = #{parsedCommandLine}"
if parsedCommandLine.isRegenerateCommentLine # if it is a Regenerate command line
parsedCommandLine.checkIsValid # check it is valid, and then,
processCommandLine(parsedCommandLine, lineNumber) # process the command line
else
processTextLine(line, lineNumber) # process a text line which is not a Regenerate command line
end
else
processTextLine(line, lineNumber) # process a text line which is not a Regenerate command line
end
end
# After processing all source lines, the only unfinished page component permitted is a static HTML component.
finishAtEndOfSourceFile
#puts "Finished reading #{@fileName}."
end | [
"def",
"readFileLines",
"puts",
"\"Reading source file #{@fileName} ...\"",
"lineNumber",
"=",
"0",
"File",
".",
"open",
"(",
"@fileName",
")",
".",
"each_line",
"do",
"|",
"line",
"|",
"line",
".",
"chomp!",
"lineNumber",
"+=",
"1",
"commentLineMatch",
"=",
"COMMENT_LINE_REGEX",
".",
"match",
"(",
"line",
")",
"if",
"commentLineMatch",
"parsedCommandLine",
"=",
"ParsedRegenerateCommentLine",
".",
"new",
"(",
"line",
",",
"commentLineMatch",
")",
"if",
"parsedCommandLine",
".",
"isRegenerateCommentLine",
"parsedCommandLine",
".",
"checkIsValid",
"processCommandLine",
"(",
"parsedCommandLine",
",",
"lineNumber",
")",
"else",
"processTextLine",
"(",
"line",
",",
"lineNumber",
")",
"end",
"else",
"processTextLine",
"(",
"line",
",",
"lineNumber",
")",
"end",
"end",
"finishAtEndOfSourceFile",
"end"
] | Read in and parse lines from source file | [
"Read",
"in",
"and",
"parse",
"lines",
"from",
"source",
"file"
] | 31f3beb3ff9b45384a90f20fed61be20f39da0d4 | https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L539-L563 | train |
pdorrell/regenerate | lib/regenerate/web-page.rb | Regenerate.WebPage.regenerateToOutputFile | def regenerateToOutputFile(outFile, checkNoChanges = false)
executeRubyComponents
@pageObject.process
writeRegeneratedFile(outFile, checkNoChanges, checkNoChanges)
end | ruby | def regenerateToOutputFile(outFile, checkNoChanges = false)
executeRubyComponents
@pageObject.process
writeRegeneratedFile(outFile, checkNoChanges, checkNoChanges)
end | [
"def",
"regenerateToOutputFile",
"(",
"outFile",
",",
"checkNoChanges",
"=",
"false",
")",
"executeRubyComponents",
"@pageObject",
".",
"process",
"writeRegeneratedFile",
"(",
"outFile",
",",
"checkNoChanges",
",",
"checkNoChanges",
")",
"end"
] | Regenerate from the source file into the output file | [
"Regenerate",
"from",
"the",
"source",
"file",
"into",
"the",
"output",
"file"
] | 31f3beb3ff9b45384a90f20fed61be20f39da0d4 | https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L574-L578 | train |
pdorrell/regenerate | lib/regenerate/web-page.rb | Regenerate.WebPage.executeRubyComponents | def executeRubyComponents
fileDir = File.dirname(@fileName)
#puts "Executing ruby components in directory #{fileDir} ..."
Dir.chdir(fileDir) do
for rubyComponent in @rubyComponents
rubyCode = rubyComponent.text
#puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
#puts "Executing ruby (line #{rubyComponent.lineNumber}) #{rubyCode.inspect} ..."
@pageObject.instance_eval(rubyCode, @fileName, rubyComponent.lineNumber)
#puts "Finished executing ruby at line #{rubyComponent.lineNumber}"
end
end
#puts "Finished executing ruby components."
end | ruby | def executeRubyComponents
fileDir = File.dirname(@fileName)
#puts "Executing ruby components in directory #{fileDir} ..."
Dir.chdir(fileDir) do
for rubyComponent in @rubyComponents
rubyCode = rubyComponent.text
#puts ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
#puts "Executing ruby (line #{rubyComponent.lineNumber}) #{rubyCode.inspect} ..."
@pageObject.instance_eval(rubyCode, @fileName, rubyComponent.lineNumber)
#puts "Finished executing ruby at line #{rubyComponent.lineNumber}"
end
end
#puts "Finished executing ruby components."
end | [
"def",
"executeRubyComponents",
"fileDir",
"=",
"File",
".",
"dirname",
"(",
"@fileName",
")",
"Dir",
".",
"chdir",
"(",
"fileDir",
")",
"do",
"for",
"rubyComponent",
"in",
"@rubyComponents",
"rubyCode",
"=",
"rubyComponent",
".",
"text",
"@pageObject",
".",
"instance_eval",
"(",
"rubyCode",
",",
"@fileName",
",",
"rubyComponent",
".",
"lineNumber",
")",
"end",
"end",
"end"
] | Execute the Ruby components which consist of Ruby code to be evaluated in the context of the page object | [
"Execute",
"the",
"Ruby",
"components",
"which",
"consist",
"of",
"Ruby",
"code",
"to",
"be",
"evaluated",
"in",
"the",
"context",
"of",
"the",
"page",
"object"
] | 31f3beb3ff9b45384a90f20fed61be20f39da0d4 | https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L581-L594 | train |
pdorrell/regenerate | lib/regenerate/web-page.rb | Regenerate.PageObject.erb | def erb(templateFileName)
@binding = binding
fullTemplateFilePath = relative_path(@rootLinkPath + templateFileName)
File.open(fullTemplateFilePath, "r") do |input|
templateText = input.read
template = ERB.new(templateText, nil, nil)
template.filename = templateFileName
result = template.result(@binding)
end
end | ruby | def erb(templateFileName)
@binding = binding
fullTemplateFilePath = relative_path(@rootLinkPath + templateFileName)
File.open(fullTemplateFilePath, "r") do |input|
templateText = input.read
template = ERB.new(templateText, nil, nil)
template.filename = templateFileName
result = template.result(@binding)
end
end | [
"def",
"erb",
"(",
"templateFileName",
")",
"@binding",
"=",
"binding",
"fullTemplateFilePath",
"=",
"relative_path",
"(",
"@rootLinkPath",
"+",
"templateFileName",
")",
"File",
".",
"open",
"(",
"fullTemplateFilePath",
",",
"\"r\"",
")",
"do",
"|",
"input",
"|",
"templateText",
"=",
"input",
".",
"read",
"template",
"=",
"ERB",
".",
"new",
"(",
"templateText",
",",
"nil",
",",
"nil",
")",
"template",
".",
"filename",
"=",
"templateFileName",
"result",
"=",
"template",
".",
"result",
"(",
"@binding",
")",
"end",
"end"
] | Method to render an ERB template file in the context of this object | [
"Method",
"to",
"render",
"an",
"ERB",
"template",
"file",
"in",
"the",
"context",
"of",
"this",
"object"
] | 31f3beb3ff9b45384a90f20fed61be20f39da0d4 | https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/web-page.rb#L618-L627 | train |
alexdean/where_was_i | lib/where_was_i/gpx.rb | WhereWasI.Gpx.add_tracks | def add_tracks
@tracks = []
doc = Nokogiri::XML(@gpx_data)
doc.css('xmlns|trk').each do |trk|
track = Track.new
trk.css('xmlns|trkpt').each do |trkpt|
# https://en.wikipedia.org/wiki/GPS_Exchange_Format#Units
# decimal degrees, wgs84.
# elevation in meters.
track.add_point(
lat: trkpt.attributes['lat'].text.to_f,
lon: trkpt.attributes['lon'].text.to_f,
elevation: trkpt.at_css('xmlns|ele').text.to_f,
time: Time.parse(trkpt.at_css('xmlns|time').text)
)
end
@tracks << track
end
@intersegments = []
@tracks.each_with_index do |track,i|
next if i == 0
this_track = track
prev_track = @tracks[i-1]
inter_track = Track.new
inter_track.add_point(
lat: prev_track.end_location[0],
lon: prev_track.end_location[1],
elevation: prev_track.end_location[2],
time: prev_track.end_time
)
inter_track.add_point(
lat: this_track.start_location[0],
lon: this_track.start_location[1],
elevation: this_track.start_location[2],
time: this_track.start_time
)
@intersegments << inter_track
end
@tracks_added = true
end | ruby | def add_tracks
@tracks = []
doc = Nokogiri::XML(@gpx_data)
doc.css('xmlns|trk').each do |trk|
track = Track.new
trk.css('xmlns|trkpt').each do |trkpt|
# https://en.wikipedia.org/wiki/GPS_Exchange_Format#Units
# decimal degrees, wgs84.
# elevation in meters.
track.add_point(
lat: trkpt.attributes['lat'].text.to_f,
lon: trkpt.attributes['lon'].text.to_f,
elevation: trkpt.at_css('xmlns|ele').text.to_f,
time: Time.parse(trkpt.at_css('xmlns|time').text)
)
end
@tracks << track
end
@intersegments = []
@tracks.each_with_index do |track,i|
next if i == 0
this_track = track
prev_track = @tracks[i-1]
inter_track = Track.new
inter_track.add_point(
lat: prev_track.end_location[0],
lon: prev_track.end_location[1],
elevation: prev_track.end_location[2],
time: prev_track.end_time
)
inter_track.add_point(
lat: this_track.start_location[0],
lon: this_track.start_location[1],
elevation: this_track.start_location[2],
time: this_track.start_time
)
@intersegments << inter_track
end
@tracks_added = true
end | [
"def",
"add_tracks",
"@tracks",
"=",
"[",
"]",
"doc",
"=",
"Nokogiri",
"::",
"XML",
"(",
"@gpx_data",
")",
"doc",
".",
"css",
"(",
"'xmlns|trk'",
")",
".",
"each",
"do",
"|",
"trk",
"|",
"track",
"=",
"Track",
".",
"new",
"trk",
".",
"css",
"(",
"'xmlns|trkpt'",
")",
".",
"each",
"do",
"|",
"trkpt",
"|",
"track",
".",
"add_point",
"(",
"lat",
":",
"trkpt",
".",
"attributes",
"[",
"'lat'",
"]",
".",
"text",
".",
"to_f",
",",
"lon",
":",
"trkpt",
".",
"attributes",
"[",
"'lon'",
"]",
".",
"text",
".",
"to_f",
",",
"elevation",
":",
"trkpt",
".",
"at_css",
"(",
"'xmlns|ele'",
")",
".",
"text",
".",
"to_f",
",",
"time",
":",
"Time",
".",
"parse",
"(",
"trkpt",
".",
"at_css",
"(",
"'xmlns|time'",
")",
".",
"text",
")",
")",
"end",
"@tracks",
"<<",
"track",
"end",
"@intersegments",
"=",
"[",
"]",
"@tracks",
".",
"each_with_index",
"do",
"|",
"track",
",",
"i",
"|",
"next",
"if",
"i",
"==",
"0",
"this_track",
"=",
"track",
"prev_track",
"=",
"@tracks",
"[",
"i",
"-",
"1",
"]",
"inter_track",
"=",
"Track",
".",
"new",
"inter_track",
".",
"add_point",
"(",
"lat",
":",
"prev_track",
".",
"end_location",
"[",
"0",
"]",
",",
"lon",
":",
"prev_track",
".",
"end_location",
"[",
"1",
"]",
",",
"elevation",
":",
"prev_track",
".",
"end_location",
"[",
"2",
"]",
",",
"time",
":",
"prev_track",
".",
"end_time",
")",
"inter_track",
".",
"add_point",
"(",
"lat",
":",
"this_track",
".",
"start_location",
"[",
"0",
"]",
",",
"lon",
":",
"this_track",
".",
"start_location",
"[",
"1",
"]",
",",
"elevation",
":",
"this_track",
".",
"start_location",
"[",
"2",
"]",
",",
"time",
":",
"this_track",
".",
"start_time",
")",
"@intersegments",
"<<",
"inter_track",
"end",
"@tracks_added",
"=",
"true",
"end"
] | extract track data from gpx data
it's not necessary to call this directly | [
"extract",
"track",
"data",
"from",
"gpx",
"data"
] | 10d1381d6e0b1a85de65678a540d4dbc6041321d | https://github.com/alexdean/where_was_i/blob/10d1381d6e0b1a85de65678a540d4dbc6041321d/lib/where_was_i/gpx.rb#L47-L91 | train |
alexdean/where_was_i | lib/where_was_i/gpx.rb | WhereWasI.Gpx.at | def at(time)
add_tracks if ! @tracks_added
if time.is_a?(String)
time = Time.parse(time)
end
time = time.to_i
location = nil
@tracks.each do |track|
location = track.at(time)
break if location
end
if ! location
case @intersegment_behavior
when :interpolate then
@intersegments.each do |track|
location = track.at(time)
break if location
end
when :nearest then
# hash is sorted in ascending time order.
# all start/end points for all segments
points = {}
@tracks.each do |t|
points[t.start_time.to_i] = t.start_location
points[t.end_time.to_i] = t.end_location
end
last_diff = Infinity
last_time = -1
points.each do |p_time,p_location|
this_diff = (p_time.to_i - time).abs
# as long as the differences keep getting smaller, we keep going
# as soon as we see a larger one, we step back one and use that value.
if this_diff > last_diff
l = points[last_time]
location = Track.array_to_hash(points[last_time])
break
else
last_diff = this_diff
last_time = p_time
end
end
# if we got here, time is > the end of the last segment
location = Track.array_to_hash(points[last_time])
end
end
# each segment has a begin and end time.
# which one is this time closest to?
# array of times in order. compute abs diff between time and each point.
# put times in order. abs diff to each, until we get a larger value or we run out of points. then back up one and use that.
# {time => [lat, lon, elev], time => [lat, lon, elev]}
location
end | ruby | def at(time)
add_tracks if ! @tracks_added
if time.is_a?(String)
time = Time.parse(time)
end
time = time.to_i
location = nil
@tracks.each do |track|
location = track.at(time)
break if location
end
if ! location
case @intersegment_behavior
when :interpolate then
@intersegments.each do |track|
location = track.at(time)
break if location
end
when :nearest then
# hash is sorted in ascending time order.
# all start/end points for all segments
points = {}
@tracks.each do |t|
points[t.start_time.to_i] = t.start_location
points[t.end_time.to_i] = t.end_location
end
last_diff = Infinity
last_time = -1
points.each do |p_time,p_location|
this_diff = (p_time.to_i - time).abs
# as long as the differences keep getting smaller, we keep going
# as soon as we see a larger one, we step back one and use that value.
if this_diff > last_diff
l = points[last_time]
location = Track.array_to_hash(points[last_time])
break
else
last_diff = this_diff
last_time = p_time
end
end
# if we got here, time is > the end of the last segment
location = Track.array_to_hash(points[last_time])
end
end
# each segment has a begin and end time.
# which one is this time closest to?
# array of times in order. compute abs diff between time and each point.
# put times in order. abs diff to each, until we get a larger value or we run out of points. then back up one and use that.
# {time => [lat, lon, elev], time => [lat, lon, elev]}
location
end | [
"def",
"at",
"(",
"time",
")",
"add_tracks",
"if",
"!",
"@tracks_added",
"if",
"time",
".",
"is_a?",
"(",
"String",
")",
"time",
"=",
"Time",
".",
"parse",
"(",
"time",
")",
"end",
"time",
"=",
"time",
".",
"to_i",
"location",
"=",
"nil",
"@tracks",
".",
"each",
"do",
"|",
"track",
"|",
"location",
"=",
"track",
".",
"at",
"(",
"time",
")",
"break",
"if",
"location",
"end",
"if",
"!",
"location",
"case",
"@intersegment_behavior",
"when",
":interpolate",
"then",
"@intersegments",
".",
"each",
"do",
"|",
"track",
"|",
"location",
"=",
"track",
".",
"at",
"(",
"time",
")",
"break",
"if",
"location",
"end",
"when",
":nearest",
"then",
"points",
"=",
"{",
"}",
"@tracks",
".",
"each",
"do",
"|",
"t",
"|",
"points",
"[",
"t",
".",
"start_time",
".",
"to_i",
"]",
"=",
"t",
".",
"start_location",
"points",
"[",
"t",
".",
"end_time",
".",
"to_i",
"]",
"=",
"t",
".",
"end_location",
"end",
"last_diff",
"=",
"Infinity",
"last_time",
"=",
"-",
"1",
"points",
".",
"each",
"do",
"|",
"p_time",
",",
"p_location",
"|",
"this_diff",
"=",
"(",
"p_time",
".",
"to_i",
"-",
"time",
")",
".",
"abs",
"if",
"this_diff",
">",
"last_diff",
"l",
"=",
"points",
"[",
"last_time",
"]",
"location",
"=",
"Track",
".",
"array_to_hash",
"(",
"points",
"[",
"last_time",
"]",
")",
"break",
"else",
"last_diff",
"=",
"this_diff",
"last_time",
"=",
"p_time",
"end",
"end",
"location",
"=",
"Track",
".",
"array_to_hash",
"(",
"points",
"[",
"last_time",
"]",
")",
"end",
"end",
"location",
"end"
] | infer a location from track data and a time
@param [Time,String,Fixnum] time
@return [Hash]
@see Track#at | [
"infer",
"a",
"location",
"from",
"track",
"data",
"and",
"a",
"time"
] | 10d1381d6e0b1a85de65678a540d4dbc6041321d | https://github.com/alexdean/where_was_i/blob/10d1381d6e0b1a85de65678a540d4dbc6041321d/lib/where_was_i/gpx.rb#L98-L158 | train |
rgeyer/rs_user_policy | lib/rs_user_policy/user.rb | RsUserPolicy.User.clear_permissions | def clear_permissions(account_href, client, options={})
options = {:dry_run => false}.merge(options)
current_permissions = get_api_permissions(account_href)
if options[:dry_run]
Hash[current_permissions.map{|p| [p.href, p.role_title]}]
else
retval = RsUserPolicy::RightApi::PermissionUtilities.destroy_permissions(
current_permissions,
client
)
@permissions.delete(account_href)
retval
end
end | ruby | def clear_permissions(account_href, client, options={})
options = {:dry_run => false}.merge(options)
current_permissions = get_api_permissions(account_href)
if options[:dry_run]
Hash[current_permissions.map{|p| [p.href, p.role_title]}]
else
retval = RsUserPolicy::RightApi::PermissionUtilities.destroy_permissions(
current_permissions,
client
)
@permissions.delete(account_href)
retval
end
end | [
"def",
"clear_permissions",
"(",
"account_href",
",",
"client",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":dry_run",
"=>",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"current_permissions",
"=",
"get_api_permissions",
"(",
"account_href",
")",
"if",
"options",
"[",
":dry_run",
"]",
"Hash",
"[",
"current_permissions",
".",
"map",
"{",
"|",
"p",
"|",
"[",
"p",
".",
"href",
",",
"p",
".",
"role_title",
"]",
"}",
"]",
"else",
"retval",
"=",
"RsUserPolicy",
"::",
"RightApi",
"::",
"PermissionUtilities",
".",
"destroy_permissions",
"(",
"current_permissions",
",",
"client",
")",
"@permissions",
".",
"delete",
"(",
"account_href",
")",
"retval",
"end",
"end"
] | Removes all permissions for the user in the specified rightscale account using the supplied client
@param [String] account_href The RightScale API href of the account
@param [RightApi::Client] client An active RightApi::Client instance for the account referenced in account_href
@param [Hash] options Optional parameters
@option options [Bool] :dry_run If true, no API calls will be made, but the return value will contain the actions which would have been taken
@raise [RightApi::ApiError] If an unrecoverable API error has occurred.
@return [Hash] A hash where the keys are the permission hrefs destroyed, and the keys are the role_title of those permissions | [
"Removes",
"all",
"permissions",
"for",
"the",
"user",
"in",
"the",
"specified",
"rightscale",
"account",
"using",
"the",
"supplied",
"client"
] | bae3355f1471cc7d28de7992c5d5f4ac39fff68b | https://github.com/rgeyer/rs_user_policy/blob/bae3355f1471cc7d28de7992c5d5f4ac39fff68b/lib/rs_user_policy/user.rb#L75-L88 | train |
rgeyer/rs_user_policy | lib/rs_user_policy/user.rb | RsUserPolicy.User.set_api_permissions | def set_api_permissions(permissions, account_href, client, options={})
options = {:dry_run => false}.merge(options)
existing_api_permissions_response = get_api_permissions(account_href)
existing_api_permissions = Hash[existing_api_permissions_response.map{|p| [p.role_title, p] }]
if permissions.length == 0
removed = clear_permissions(account_href, client, options)
@permissions.delete(account_href)
return removed, {}
else
permissions_to_remove = (existing_api_permissions.keys - permissions).map{|p| existing_api_permissions[p]}
remove_response = Hash[permissions_to_remove.map{|p| [p.href, p.role_title]}]
unless options[:dry_run]
remove_response = RsUserPolicy::RightApi::PermissionUtilities.destroy_permissions(permissions_to_remove, client)
end
permissions_to_add = {
@href => Hash[(permissions - existing_api_permissions.keys).map{|p| [p,nil]}]
}
add_response = {}
if options[:dry_run]
href_idx = 0
add_response = {
@href => Hash[(permissions - existing_api_permissions.keys).map{|p| [p,(href_idx += 1)]}]
}
else
add_response = RsUserPolicy::RightApi::PermissionUtilities.create_permissions(permissions_to_add, client)
end
@permissions[account_href] = client.permissions.index(:filter => ["user_href==#{@href}"]) unless options[:dry_run]
return remove_response, Hash[add_response[@href].keys.map{|p| [add_response[@href][p],p]}]
end
end | ruby | def set_api_permissions(permissions, account_href, client, options={})
options = {:dry_run => false}.merge(options)
existing_api_permissions_response = get_api_permissions(account_href)
existing_api_permissions = Hash[existing_api_permissions_response.map{|p| [p.role_title, p] }]
if permissions.length == 0
removed = clear_permissions(account_href, client, options)
@permissions.delete(account_href)
return removed, {}
else
permissions_to_remove = (existing_api_permissions.keys - permissions).map{|p| existing_api_permissions[p]}
remove_response = Hash[permissions_to_remove.map{|p| [p.href, p.role_title]}]
unless options[:dry_run]
remove_response = RsUserPolicy::RightApi::PermissionUtilities.destroy_permissions(permissions_to_remove, client)
end
permissions_to_add = {
@href => Hash[(permissions - existing_api_permissions.keys).map{|p| [p,nil]}]
}
add_response = {}
if options[:dry_run]
href_idx = 0
add_response = {
@href => Hash[(permissions - existing_api_permissions.keys).map{|p| [p,(href_idx += 1)]}]
}
else
add_response = RsUserPolicy::RightApi::PermissionUtilities.create_permissions(permissions_to_add, client)
end
@permissions[account_href] = client.permissions.index(:filter => ["user_href==#{@href}"]) unless options[:dry_run]
return remove_response, Hash[add_response[@href].keys.map{|p| [add_response[@href][p],p]}]
end
end | [
"def",
"set_api_permissions",
"(",
"permissions",
",",
"account_href",
",",
"client",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":dry_run",
"=>",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"existing_api_permissions_response",
"=",
"get_api_permissions",
"(",
"account_href",
")",
"existing_api_permissions",
"=",
"Hash",
"[",
"existing_api_permissions_response",
".",
"map",
"{",
"|",
"p",
"|",
"[",
"p",
".",
"role_title",
",",
"p",
"]",
"}",
"]",
"if",
"permissions",
".",
"length",
"==",
"0",
"removed",
"=",
"clear_permissions",
"(",
"account_href",
",",
"client",
",",
"options",
")",
"@permissions",
".",
"delete",
"(",
"account_href",
")",
"return",
"removed",
",",
"{",
"}",
"else",
"permissions_to_remove",
"=",
"(",
"existing_api_permissions",
".",
"keys",
"-",
"permissions",
")",
".",
"map",
"{",
"|",
"p",
"|",
"existing_api_permissions",
"[",
"p",
"]",
"}",
"remove_response",
"=",
"Hash",
"[",
"permissions_to_remove",
".",
"map",
"{",
"|",
"p",
"|",
"[",
"p",
".",
"href",
",",
"p",
".",
"role_title",
"]",
"}",
"]",
"unless",
"options",
"[",
":dry_run",
"]",
"remove_response",
"=",
"RsUserPolicy",
"::",
"RightApi",
"::",
"PermissionUtilities",
".",
"destroy_permissions",
"(",
"permissions_to_remove",
",",
"client",
")",
"end",
"permissions_to_add",
"=",
"{",
"@href",
"=>",
"Hash",
"[",
"(",
"permissions",
"-",
"existing_api_permissions",
".",
"keys",
")",
".",
"map",
"{",
"|",
"p",
"|",
"[",
"p",
",",
"nil",
"]",
"}",
"]",
"}",
"add_response",
"=",
"{",
"}",
"if",
"options",
"[",
":dry_run",
"]",
"href_idx",
"=",
"0",
"add_response",
"=",
"{",
"@href",
"=>",
"Hash",
"[",
"(",
"permissions",
"-",
"existing_api_permissions",
".",
"keys",
")",
".",
"map",
"{",
"|",
"p",
"|",
"[",
"p",
",",
"(",
"href_idx",
"+=",
"1",
")",
"]",
"}",
"]",
"}",
"else",
"add_response",
"=",
"RsUserPolicy",
"::",
"RightApi",
"::",
"PermissionUtilities",
".",
"create_permissions",
"(",
"permissions_to_add",
",",
"client",
")",
"end",
"@permissions",
"[",
"account_href",
"]",
"=",
"client",
".",
"permissions",
".",
"index",
"(",
":filter",
"=>",
"[",
"\"user_href==#{@href}\"",
"]",
")",
"unless",
"options",
"[",
":dry_run",
"]",
"return",
"remove_response",
",",
"Hash",
"[",
"add_response",
"[",
"@href",
"]",
".",
"keys",
".",
"map",
"{",
"|",
"p",
"|",
"[",
"add_response",
"[",
"@href",
"]",
"[",
"p",
"]",
",",
"p",
"]",
"}",
"]",
"end",
"end"
] | Removes and adds permissions as appropriate so that the users current permissions reflect
the desired set passed in as "permissions"
@param [Array<String>] permissions The list of desired permissions for the user in the specified account
@param [String] account_href The RightScale API href of the account
@param [RightApi::Client] client An active RightApi::Client instance for the account referenced in account_href
@param [Hash] options Optional parameters
@option options [Bool] :dry_run If true, no API calls will be made, but the return value will contain the actions which would have been taken
@raise [RightApi::ApiError] If an unrecoverable API error has occurred.
@return [Hash,Hash] A tuple where two hashes are returned. The keys of the hashes are the href of the permission, and the values are the role_title of the permission. The first hash is the permissions removed, and the second hash is the permissions added | [
"Removes",
"and",
"adds",
"permissions",
"as",
"appropriate",
"so",
"that",
"the",
"users",
"current",
"permissions",
"reflect",
"the",
"desired",
"set",
"passed",
"in",
"as",
"permissions"
] | bae3355f1471cc7d28de7992c5d5f4ac39fff68b | https://github.com/rgeyer/rs_user_policy/blob/bae3355f1471cc7d28de7992c5d5f4ac39fff68b/lib/rs_user_policy/user.rb#L102-L134 | train |
influenza/hosties | lib/hosties/reification.rb | Hosties.UsesAttributes.finish | def finish
retval = {}
# Ensure all required attributes have been set
@attributes.each do |attr|
val = instance_variable_get "@#{attr}"
raise ArgumentError, "Missing attribute #{attr}" if val.nil?
retval[attr] = val
end
retval
end | ruby | def finish
retval = {}
# Ensure all required attributes have been set
@attributes.each do |attr|
val = instance_variable_get "@#{attr}"
raise ArgumentError, "Missing attribute #{attr}" if val.nil?
retval[attr] = val
end
retval
end | [
"def",
"finish",
"retval",
"=",
"{",
"}",
"@attributes",
".",
"each",
"do",
"|",
"attr",
"|",
"val",
"=",
"instance_variable_get",
"\"@#{attr}\"",
"raise",
"ArgumentError",
",",
"\"Missing attribute #{attr}\"",
"if",
"val",
".",
"nil?",
"retval",
"[",
"attr",
"]",
"=",
"val",
"end",
"retval",
"end"
] | Return a hash after verifying everything was set correctly | [
"Return",
"a",
"hash",
"after",
"verifying",
"everything",
"was",
"set",
"correctly"
] | a3030cd4a23a23a0fcc2664c01a497b31e6e49fe | https://github.com/influenza/hosties/blob/a3030cd4a23a23a0fcc2664c01a497b31e6e49fe/lib/hosties/reification.rb#L29-L38 | train |
crapooze/em-xmpp | lib/em-xmpp/handler.rb | EM::Xmpp.Handler.run_xpath_handlers | def run_xpath_handlers(ctx, handlers, remover)
handlers.each do |h|
if (not ctx.done?) and (h.match?(ctx.stanza))
ctx['xpath.handler'] = h
ctx = h.call(ctx)
raise RuntimeError, "xpath handlers should return a Context" unless ctx.is_a?(Context)
send remover, h unless ctx.reuse_handler?
end
end
end | ruby | def run_xpath_handlers(ctx, handlers, remover)
handlers.each do |h|
if (not ctx.done?) and (h.match?(ctx.stanza))
ctx['xpath.handler'] = h
ctx = h.call(ctx)
raise RuntimeError, "xpath handlers should return a Context" unless ctx.is_a?(Context)
send remover, h unless ctx.reuse_handler?
end
end
end | [
"def",
"run_xpath_handlers",
"(",
"ctx",
",",
"handlers",
",",
"remover",
")",
"handlers",
".",
"each",
"do",
"|",
"h",
"|",
"if",
"(",
"not",
"ctx",
".",
"done?",
")",
"and",
"(",
"h",
".",
"match?",
"(",
"ctx",
".",
"stanza",
")",
")",
"ctx",
"[",
"'xpath.handler'",
"]",
"=",
"h",
"ctx",
"=",
"h",
".",
"call",
"(",
"ctx",
")",
"raise",
"RuntimeError",
",",
"\"xpath handlers should return a Context\"",
"unless",
"ctx",
".",
"is_a?",
"(",
"Context",
")",
"send",
"remover",
",",
"h",
"unless",
"ctx",
".",
"reuse_handler?",
"end",
"end",
"end"
] | runs all handlers, calls the remover method if a handler should be removed | [
"runs",
"all",
"handlers",
"calls",
"the",
"remover",
"method",
"if",
"a",
"handler",
"should",
"be",
"removed"
] | 804e139944c88bc317b359754d5ad69b75f42319 | https://github.com/crapooze/em-xmpp/blob/804e139944c88bc317b359754d5ad69b75f42319/lib/em-xmpp/handler.rb#L210-L219 | train |
mabako/mta_json | lib/mta_json/wrapper.rb | MtaJson.Wrapper.update_params | def update_params env, json
env[FORM_HASH] = json
env[BODY] = env[FORM_INPUT] = StringIO.new(Rack::Utils.build_query(json))
end | ruby | def update_params env, json
env[FORM_HASH] = json
env[BODY] = env[FORM_INPUT] = StringIO.new(Rack::Utils.build_query(json))
end | [
"def",
"update_params",
"env",
",",
"json",
"env",
"[",
"FORM_HASH",
"]",
"=",
"json",
"env",
"[",
"BODY",
"]",
"=",
"env",
"[",
"FORM_INPUT",
"]",
"=",
"StringIO",
".",
"new",
"(",
"Rack",
"::",
"Utils",
".",
"build_query",
"(",
"json",
")",
")",
"end"
] | update all of the parameter-related values in the current request's environment | [
"update",
"all",
"of",
"the",
"parameter",
"-",
"related",
"values",
"in",
"the",
"current",
"request",
"s",
"environment"
] | a9462c229ccc0e49c95bbb32b377afe082093fd7 | https://github.com/mabako/mta_json/blob/a9462c229ccc0e49c95bbb32b377afe082093fd7/lib/mta_json/wrapper.rb#L105-L108 | train |
mabako/mta_json | lib/mta_json/wrapper.rb | MtaJson.Wrapper.verify_request_method | def verify_request_method env
allowed = ALLOWED_METHODS
allowed |= ALLOWED_METHODS_PRIVATE if whitelisted?(env)
if !allowed.include?(env[METHOD])
raise "Request method #{env[METHOD]} not allowed"
end
end | ruby | def verify_request_method env
allowed = ALLOWED_METHODS
allowed |= ALLOWED_METHODS_PRIVATE if whitelisted?(env)
if !allowed.include?(env[METHOD])
raise "Request method #{env[METHOD]} not allowed"
end
end | [
"def",
"verify_request_method",
"env",
"allowed",
"=",
"ALLOWED_METHODS",
"allowed",
"|=",
"ALLOWED_METHODS_PRIVATE",
"if",
"whitelisted?",
"(",
"env",
")",
"if",
"!",
"allowed",
".",
"include?",
"(",
"env",
"[",
"METHOD",
"]",
")",
"raise",
"\"Request method #{env[METHOD]} not allowed\"",
"end",
"end"
] | make sure the request came from a whitelisted ip, or uses a publically accessible request method | [
"make",
"sure",
"the",
"request",
"came",
"from",
"a",
"whitelisted",
"ip",
"or",
"uses",
"a",
"publically",
"accessible",
"request",
"method"
] | a9462c229ccc0e49c95bbb32b377afe082093fd7 | https://github.com/mabako/mta_json/blob/a9462c229ccc0e49c95bbb32b377afe082093fd7/lib/mta_json/wrapper.rb#L111-L117 | train |
mabako/mta_json | lib/mta_json/wrapper.rb | MtaJson.Wrapper.update_options | def update_options env, options
if options[:method] and (ALLOWED_METHODS | ALLOWED_METHODS_PRIVATE).include?(options[:method])
# (possibly) TODO - pass parameters for GET instead of POST in update_params then?
# see https://github.com/rack/rack/blob/master/lib/rack/request.rb -> def GET
env[METHOD] = options[:method]
end
end | ruby | def update_options env, options
if options[:method] and (ALLOWED_METHODS | ALLOWED_METHODS_PRIVATE).include?(options[:method])
# (possibly) TODO - pass parameters for GET instead of POST in update_params then?
# see https://github.com/rack/rack/blob/master/lib/rack/request.rb -> def GET
env[METHOD] = options[:method]
end
end | [
"def",
"update_options",
"env",
",",
"options",
"if",
"options",
"[",
":method",
"]",
"and",
"(",
"ALLOWED_METHODS",
"|",
"ALLOWED_METHODS_PRIVATE",
")",
".",
"include?",
"(",
"options",
"[",
":method",
"]",
")",
"env",
"[",
"METHOD",
"]",
"=",
"options",
"[",
":method",
"]",
"end",
"end"
] | updates the options | [
"updates",
"the",
"options"
] | a9462c229ccc0e49c95bbb32b377afe082093fd7 | https://github.com/mabako/mta_json/blob/a9462c229ccc0e49c95bbb32b377afe082093fd7/lib/mta_json/wrapper.rb#L120-L126 | train |
mabako/mta_json | lib/mta_json/wrapper.rb | MtaJson.Wrapper.add_csrf_info | def add_csrf_info env
env[CSRF_TOKEN] = env[SESSION][:_csrf_token] = SecureRandom.base64(32).to_s if env[METHOD] != 'GET' and whitelisted?(env)
end | ruby | def add_csrf_info env
env[CSRF_TOKEN] = env[SESSION][:_csrf_token] = SecureRandom.base64(32).to_s if env[METHOD] != 'GET' and whitelisted?(env)
end | [
"def",
"add_csrf_info",
"env",
"env",
"[",
"CSRF_TOKEN",
"]",
"=",
"env",
"[",
"SESSION",
"]",
"[",
":_csrf_token",
"]",
"=",
"SecureRandom",
".",
"base64",
"(",
"32",
")",
".",
"to_s",
"if",
"env",
"[",
"METHOD",
"]",
"!=",
"'GET'",
"and",
"whitelisted?",
"(",
"env",
")",
"end"
] | adds csrf info to non-GET requests of whitelisted IPs | [
"adds",
"csrf",
"info",
"to",
"non",
"-",
"GET",
"requests",
"of",
"whitelisted",
"IPs"
] | a9462c229ccc0e49c95bbb32b377afe082093fd7 | https://github.com/mabako/mta_json/blob/a9462c229ccc0e49c95bbb32b377afe082093fd7/lib/mta_json/wrapper.rb#L129-L131 | train |
polleverywhere/cerealizer | lib/cerealizer.rb | Cerealizer.Base.read_keys | def read_keys
self.class.keys.inject Hash.new do |hash, key|
hash[key.name] = proxy_reader(key.name) if readable?(key.name)
hash
end
end | ruby | def read_keys
self.class.keys.inject Hash.new do |hash, key|
hash[key.name] = proxy_reader(key.name) if readable?(key.name)
hash
end
end | [
"def",
"read_keys",
"self",
".",
"class",
".",
"keys",
".",
"inject",
"Hash",
".",
"new",
"do",
"|",
"hash",
",",
"key",
"|",
"hash",
"[",
"key",
".",
"name",
"]",
"=",
"proxy_reader",
"(",
"key",
".",
"name",
")",
"if",
"readable?",
"(",
"key",
".",
"name",
")",
"hash",
"end",
"end"
] | Call methods on the object that's being presented and create a flat
hash for these mofos. | [
"Call",
"methods",
"on",
"the",
"object",
"that",
"s",
"being",
"presented",
"and",
"create",
"a",
"flat",
"hash",
"for",
"these",
"mofos",
"."
] | f7a5ef6a543427e5fe7439da6fb9da08b7bc5caf | https://github.com/polleverywhere/cerealizer/blob/f7a5ef6a543427e5fe7439da6fb9da08b7bc5caf/lib/cerealizer.rb#L24-L29 | train |
polleverywhere/cerealizer | lib/cerealizer.rb | Cerealizer.Base.write_keys | def write_keys(attrs)
attrs.each { |key, value| proxy_writer(key, value) if writeable?(key) }
self
end | ruby | def write_keys(attrs)
attrs.each { |key, value| proxy_writer(key, value) if writeable?(key) }
self
end | [
"def",
"write_keys",
"(",
"attrs",
")",
"attrs",
".",
"each",
"{",
"|",
"key",
",",
"value",
"|",
"proxy_writer",
"(",
"key",
",",
"value",
")",
"if",
"writeable?",
"(",
"key",
")",
"}",
"self",
"end"
] | Update the attrs on zie model. | [
"Update",
"the",
"attrs",
"on",
"zie",
"model",
"."
] | f7a5ef6a543427e5fe7439da6fb9da08b7bc5caf | https://github.com/polleverywhere/cerealizer/blob/f7a5ef6a543427e5fe7439da6fb9da08b7bc5caf/lib/cerealizer.rb#L32-L35 | train |
polleverywhere/cerealizer | lib/cerealizer.rb | Cerealizer.Base.proxy_writer | def proxy_writer(key, *args)
meth = "#{key}="
if self.respond_to? meth
self.send(meth, *args)
else
object.send(meth, *args)
end
end | ruby | def proxy_writer(key, *args)
meth = "#{key}="
if self.respond_to? meth
self.send(meth, *args)
else
object.send(meth, *args)
end
end | [
"def",
"proxy_writer",
"(",
"key",
",",
"*",
"args",
")",
"meth",
"=",
"\"#{key}=\"",
"if",
"self",
".",
"respond_to?",
"meth",
"self",
".",
"send",
"(",
"meth",
",",
"*",
"args",
")",
"else",
"object",
".",
"send",
"(",
"meth",
",",
"*",
"args",
")",
"end",
"end"
] | Proxy the writer to zie object. | [
"Proxy",
"the",
"writer",
"to",
"zie",
"object",
"."
] | f7a5ef6a543427e5fe7439da6fb9da08b7bc5caf | https://github.com/polleverywhere/cerealizer/blob/f7a5ef6a543427e5fe7439da6fb9da08b7bc5caf/lib/cerealizer.rb#L76-L83 | train |
ktonon/code_node | spec/fixtures/activerecord/src/active_record/fixtures.rb | ActiveRecord.Fixtures.table_rows | def table_rows
now = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now
now = now.to_s(:db)
# allow a standard key to be used for doing defaults in YAML
fixtures.delete('DEFAULTS')
# track any join tables we need to insert later
rows = Hash.new { |h,table| h[table] = [] }
rows[table_name] = fixtures.map do |label, fixture|
row = fixture.to_hash
if model_class && model_class < ActiveRecord::Base
# fill in timestamp columns if they aren't specified and the model is set to record_timestamps
if model_class.record_timestamps
timestamp_column_names.each do |name|
row[name] = now unless row.key?(name)
end
end
# interpolate the fixture label
row.each do |key, value|
row[key] = label if value == "$LABEL"
end
# generate a primary key if necessary
if has_primary_key_column? && !row.include?(primary_key_name)
row[primary_key_name] = ActiveRecord::Fixtures.identify(label)
end
# If STI is used, find the correct subclass for association reflection
reflection_class =
if row.include?(inheritance_column_name)
row[inheritance_column_name].constantize rescue model_class
else
model_class
end
reflection_class.reflect_on_all_associations.each do |association|
case association.macro
when :belongs_to
# Do not replace association name with association foreign key if they are named the same
fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s
if association.name.to_s != fk_name && value = row.delete(association.name.to_s)
if association.options[:polymorphic] && value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
# support polymorphic belongs_to as "label (Type)"
row[association.foreign_type] = $1
end
row[fk_name] = ActiveRecord::Fixtures.identify(value)
end
when :has_and_belongs_to_many
if (targets = row.delete(association.name.to_s))
targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
table_name = association.options[:join_table]
rows[table_name].concat targets.map { |target|
{ association.foreign_key => row[primary_key_name],
association.association_foreign_key => ActiveRecord::Fixtures.identify(target) }
}
end
end
end
end
row
end
rows
end | ruby | def table_rows
now = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now
now = now.to_s(:db)
# allow a standard key to be used for doing defaults in YAML
fixtures.delete('DEFAULTS')
# track any join tables we need to insert later
rows = Hash.new { |h,table| h[table] = [] }
rows[table_name] = fixtures.map do |label, fixture|
row = fixture.to_hash
if model_class && model_class < ActiveRecord::Base
# fill in timestamp columns if they aren't specified and the model is set to record_timestamps
if model_class.record_timestamps
timestamp_column_names.each do |name|
row[name] = now unless row.key?(name)
end
end
# interpolate the fixture label
row.each do |key, value|
row[key] = label if value == "$LABEL"
end
# generate a primary key if necessary
if has_primary_key_column? && !row.include?(primary_key_name)
row[primary_key_name] = ActiveRecord::Fixtures.identify(label)
end
# If STI is used, find the correct subclass for association reflection
reflection_class =
if row.include?(inheritance_column_name)
row[inheritance_column_name].constantize rescue model_class
else
model_class
end
reflection_class.reflect_on_all_associations.each do |association|
case association.macro
when :belongs_to
# Do not replace association name with association foreign key if they are named the same
fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s
if association.name.to_s != fk_name && value = row.delete(association.name.to_s)
if association.options[:polymorphic] && value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
# support polymorphic belongs_to as "label (Type)"
row[association.foreign_type] = $1
end
row[fk_name] = ActiveRecord::Fixtures.identify(value)
end
when :has_and_belongs_to_many
if (targets = row.delete(association.name.to_s))
targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
table_name = association.options[:join_table]
rows[table_name].concat targets.map { |target|
{ association.foreign_key => row[primary_key_name],
association.association_foreign_key => ActiveRecord::Fixtures.identify(target) }
}
end
end
end
end
row
end
rows
end | [
"def",
"table_rows",
"now",
"=",
"ActiveRecord",
"::",
"Base",
".",
"default_timezone",
"==",
":utc",
"?",
"Time",
".",
"now",
".",
"utc",
":",
"Time",
".",
"now",
"now",
"=",
"now",
".",
"to_s",
"(",
":db",
")",
"fixtures",
".",
"delete",
"(",
"'DEFAULTS'",
")",
"rows",
"=",
"Hash",
".",
"new",
"{",
"|",
"h",
",",
"table",
"|",
"h",
"[",
"table",
"]",
"=",
"[",
"]",
"}",
"rows",
"[",
"table_name",
"]",
"=",
"fixtures",
".",
"map",
"do",
"|",
"label",
",",
"fixture",
"|",
"row",
"=",
"fixture",
".",
"to_hash",
"if",
"model_class",
"&&",
"model_class",
"<",
"ActiveRecord",
"::",
"Base",
"if",
"model_class",
".",
"record_timestamps",
"timestamp_column_names",
".",
"each",
"do",
"|",
"name",
"|",
"row",
"[",
"name",
"]",
"=",
"now",
"unless",
"row",
".",
"key?",
"(",
"name",
")",
"end",
"end",
"row",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"row",
"[",
"key",
"]",
"=",
"label",
"if",
"value",
"==",
"\"$LABEL\"",
"end",
"if",
"has_primary_key_column?",
"&&",
"!",
"row",
".",
"include?",
"(",
"primary_key_name",
")",
"row",
"[",
"primary_key_name",
"]",
"=",
"ActiveRecord",
"::",
"Fixtures",
".",
"identify",
"(",
"label",
")",
"end",
"reflection_class",
"=",
"if",
"row",
".",
"include?",
"(",
"inheritance_column_name",
")",
"row",
"[",
"inheritance_column_name",
"]",
".",
"constantize",
"rescue",
"model_class",
"else",
"model_class",
"end",
"reflection_class",
".",
"reflect_on_all_associations",
".",
"each",
"do",
"|",
"association",
"|",
"case",
"association",
".",
"macro",
"when",
":belongs_to",
"fk_name",
"=",
"(",
"association",
".",
"options",
"[",
":foreign_key",
"]",
"||",
"\"#{association.name}_id\"",
")",
".",
"to_s",
"if",
"association",
".",
"name",
".",
"to_s",
"!=",
"fk_name",
"&&",
"value",
"=",
"row",
".",
"delete",
"(",
"association",
".",
"name",
".",
"to_s",
")",
"if",
"association",
".",
"options",
"[",
":polymorphic",
"]",
"&&",
"value",
".",
"sub!",
"(",
"/",
"\\s",
"\\(",
"\\)",
"\\)",
"\\s",
"/",
",",
"\"\"",
")",
"row",
"[",
"association",
".",
"foreign_type",
"]",
"=",
"$1",
"end",
"row",
"[",
"fk_name",
"]",
"=",
"ActiveRecord",
"::",
"Fixtures",
".",
"identify",
"(",
"value",
")",
"end",
"when",
":has_and_belongs_to_many",
"if",
"(",
"targets",
"=",
"row",
".",
"delete",
"(",
"association",
".",
"name",
".",
"to_s",
")",
")",
"targets",
"=",
"targets",
".",
"is_a?",
"(",
"Array",
")",
"?",
"targets",
":",
"targets",
".",
"split",
"(",
"/",
"\\s",
"\\s",
"/",
")",
"table_name",
"=",
"association",
".",
"options",
"[",
":join_table",
"]",
"rows",
"[",
"table_name",
"]",
".",
"concat",
"targets",
".",
"map",
"{",
"|",
"target",
"|",
"{",
"association",
".",
"foreign_key",
"=>",
"row",
"[",
"primary_key_name",
"]",
",",
"association",
".",
"association_foreign_key",
"=>",
"ActiveRecord",
"::",
"Fixtures",
".",
"identify",
"(",
"target",
")",
"}",
"}",
"end",
"end",
"end",
"end",
"row",
"end",
"rows",
"end"
] | Return a hash of rows to be inserted. The key is the table, the value is
a list of rows to insert to that table. | [
"Return",
"a",
"hash",
"of",
"rows",
"to",
"be",
"inserted",
".",
"The",
"key",
"is",
"the",
"table",
"the",
"value",
"is",
"a",
"list",
"of",
"rows",
"to",
"insert",
"to",
"that",
"table",
"."
] | 48d5d1a7442d9cade602be4fb782a1b56c7677f5 | https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/fixtures.rb#L569-L638 | train |
kukushkin/mimi-core | lib/mimi/core.rb | Mimi.Core.use | def use(mod, opts = {})
raise ArgumentError, "#{mod} is not a Mimi module" unless mod < Mimi::Core::Module
mod.configure(opts)
used_modules << mod unless used_modules.include?(mod)
true
end | ruby | def use(mod, opts = {})
raise ArgumentError, "#{mod} is not a Mimi module" unless mod < Mimi::Core::Module
mod.configure(opts)
used_modules << mod unless used_modules.include?(mod)
true
end | [
"def",
"use",
"(",
"mod",
",",
"opts",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"#{mod} is not a Mimi module\"",
"unless",
"mod",
"<",
"Mimi",
"::",
"Core",
"::",
"Module",
"mod",
".",
"configure",
"(",
"opts",
")",
"used_modules",
"<<",
"mod",
"unless",
"used_modules",
".",
"include?",
"(",
"mod",
")",
"true",
"end"
] | Use the given module | [
"Use",
"the",
"given",
"module"
] | c483360a23a373d56511c3d23e0551e690dfaf17 | https://github.com/kukushkin/mimi-core/blob/c483360a23a373d56511c3d23e0551e690dfaf17/lib/mimi/core.rb#L33-L38 | train |
kukushkin/mimi-core | lib/mimi/core.rb | Mimi.Core.require_files | def require_files(glob, root_path = app_root_path)
Pathname.glob(root_path.join(glob)).each do |filename|
require filename.expand_path
end
end | ruby | def require_files(glob, root_path = app_root_path)
Pathname.glob(root_path.join(glob)).each do |filename|
require filename.expand_path
end
end | [
"def",
"require_files",
"(",
"glob",
",",
"root_path",
"=",
"app_root_path",
")",
"Pathname",
".",
"glob",
"(",
"root_path",
".",
"join",
"(",
"glob",
")",
")",
".",
"each",
"do",
"|",
"filename",
"|",
"require",
"filename",
".",
"expand_path",
"end",
"end"
] | Requires all files that match the glob. | [
"Requires",
"all",
"files",
"that",
"match",
"the",
"glob",
"."
] | c483360a23a373d56511c3d23e0551e690dfaf17 | https://github.com/kukushkin/mimi-core/blob/c483360a23a373d56511c3d23e0551e690dfaf17/lib/mimi/core.rb#L60-L64 | train |
davidan1981/rails-identity | app/models/rails_identity/user.rb | RailsIdentity.User.valid_user | def valid_user
if (self.username.blank? || self.password_digest.blank?) &&
(self.oauth_provider.blank? || self.oauth_uid.blank?)
errors.add(:username, " and password OR oauth must be specified")
end
end | ruby | def valid_user
if (self.username.blank? || self.password_digest.blank?) &&
(self.oauth_provider.blank? || self.oauth_uid.blank?)
errors.add(:username, " and password OR oauth must be specified")
end
end | [
"def",
"valid_user",
"if",
"(",
"self",
".",
"username",
".",
"blank?",
"||",
"self",
".",
"password_digest",
".",
"blank?",
")",
"&&",
"(",
"self",
".",
"oauth_provider",
".",
"blank?",
"||",
"self",
".",
"oauth_uid",
".",
"blank?",
")",
"errors",
".",
"add",
"(",
":username",
",",
"\" and password OR oauth must be specified\"",
")",
"end",
"end"
] | This method validates if the user object is valid. A user is valid if
username and password exist OR oauth integration exists. | [
"This",
"method",
"validates",
"if",
"the",
"user",
"object",
"is",
"valid",
".",
"A",
"user",
"is",
"valid",
"if",
"username",
"and",
"password",
"exist",
"OR",
"oauth",
"integration",
"exists",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/models/rails_identity/user.rb#L20-L25 | train |
davidan1981/rails-identity | app/models/rails_identity/user.rb | RailsIdentity.User.issue_token | def issue_token(kind)
session = Session.new(user: self, seconds: 3600)
session.save
if kind == :reset_token
self.reset_token = session.token
elsif kind == :verification_token
self.verification_token = session.token
end
end | ruby | def issue_token(kind)
session = Session.new(user: self, seconds: 3600)
session.save
if kind == :reset_token
self.reset_token = session.token
elsif kind == :verification_token
self.verification_token = session.token
end
end | [
"def",
"issue_token",
"(",
"kind",
")",
"session",
"=",
"Session",
".",
"new",
"(",
"user",
":",
"self",
",",
"seconds",
":",
"3600",
")",
"session",
".",
"save",
"if",
"kind",
"==",
":reset_token",
"self",
".",
"reset_token",
"=",
"session",
".",
"token",
"elsif",
"kind",
"==",
":verification_token",
"self",
".",
"verification_token",
"=",
"session",
".",
"token",
"end",
"end"
] | This method will generate a reset token that lasts for an hour. | [
"This",
"method",
"will",
"generate",
"a",
"reset",
"token",
"that",
"lasts",
"for",
"an",
"hour",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/models/rails_identity/user.rb#L66-L74 | train |
jeremyd/virtualmonkey | lib/virtualmonkey/elb_runner.rb | VirtualMonkey.ELBRunner.lookup_scripts | def lookup_scripts
scripts = [
[ 'connect', 'ELB connect' ],
[ 'disconnect', 'ELB disconnect' ]
]
# @scripts_to_run = {}
server = @servers.first
server.settings
st = ServerTemplate.find(server.server_template_href)
lookup_scripts_table(st,scripts)
# @scripts_to_run['connect'] = st.executables.detect { |ex| ex.name =~ /ELB connect/i }
# @scripts_to_run['disconnect'] = st.executables.detect { |ex| ex.name =~ /ELB disconnect/i }
end | ruby | def lookup_scripts
scripts = [
[ 'connect', 'ELB connect' ],
[ 'disconnect', 'ELB disconnect' ]
]
# @scripts_to_run = {}
server = @servers.first
server.settings
st = ServerTemplate.find(server.server_template_href)
lookup_scripts_table(st,scripts)
# @scripts_to_run['connect'] = st.executables.detect { |ex| ex.name =~ /ELB connect/i }
# @scripts_to_run['disconnect'] = st.executables.detect { |ex| ex.name =~ /ELB disconnect/i }
end | [
"def",
"lookup_scripts",
"scripts",
"=",
"[",
"[",
"'connect'",
",",
"'ELB connect'",
"]",
",",
"[",
"'disconnect'",
",",
"'ELB disconnect'",
"]",
"]",
"server",
"=",
"@servers",
".",
"first",
"server",
".",
"settings",
"st",
"=",
"ServerTemplate",
".",
"find",
"(",
"server",
".",
"server_template_href",
")",
"lookup_scripts_table",
"(",
"st",
",",
"scripts",
")",
"end"
] | Grab the scripts we plan to excersize | [
"Grab",
"the",
"scripts",
"we",
"plan",
"to",
"excersize"
] | b2c7255f20ac5ec881eb90afbb5e712160db0dcb | https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/elb_runner.rb#L110-L122 | train |
jeremyd/virtualmonkey | lib/virtualmonkey/elb_runner.rb | VirtualMonkey.ELBRunner.log_rotation_checks | def log_rotation_checks
detect_os
# this works for php
app_servers.each do |server|
server.settings
force_log_rotation(server)
log_check(server,"/mnt/log/#{server.apache_str}/access.log.1")
end
end | ruby | def log_rotation_checks
detect_os
# this works for php
app_servers.each do |server|
server.settings
force_log_rotation(server)
log_check(server,"/mnt/log/#{server.apache_str}/access.log.1")
end
end | [
"def",
"log_rotation_checks",
"detect_os",
"app_servers",
".",
"each",
"do",
"|",
"server",
"|",
"server",
".",
"settings",
"force_log_rotation",
"(",
"server",
")",
"log_check",
"(",
"server",
",",
"\"/mnt/log/#{server.apache_str}/access.log.1\"",
")",
"end",
"end"
] | This is really just a PHP server check. relocate? | [
"This",
"is",
"really",
"just",
"a",
"PHP",
"server",
"check",
".",
"relocate?"
] | b2c7255f20ac5ec881eb90afbb5e712160db0dcb | https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/elb_runner.rb#L125-L134 | train |
ecbypi/guise | lib/guise/introspection.rb | Guise.Introspection.has_guise? | def has_guise?(value)
value = value.to_s.classify
unless guise_options.values.include?(value)
raise ArgumentError, "no such guise #{value}"
end
association(guise_options.association_name).reader.any? do |record|
!record.marked_for_destruction? &&
record[guise_options.attribute] == value
end
end | ruby | def has_guise?(value)
value = value.to_s.classify
unless guise_options.values.include?(value)
raise ArgumentError, "no such guise #{value}"
end
association(guise_options.association_name).reader.any? do |record|
!record.marked_for_destruction? &&
record[guise_options.attribute] == value
end
end | [
"def",
"has_guise?",
"(",
"value",
")",
"value",
"=",
"value",
".",
"to_s",
".",
"classify",
"unless",
"guise_options",
".",
"values",
".",
"include?",
"(",
"value",
")",
"raise",
"ArgumentError",
",",
"\"no such guise #{value}\"",
"end",
"association",
"(",
"guise_options",
".",
"association_name",
")",
".",
"reader",
".",
"any?",
"do",
"|",
"record",
"|",
"!",
"record",
".",
"marked_for_destruction?",
"&&",
"record",
"[",
"guise_options",
".",
"attribute",
"]",
"==",
"value",
"end",
"end"
] | Checks if the record has a `guise` record identified by on the specified
`value`.
@param [String, Class, Symbol] value `guise` to check
@return [true, false] | [
"Checks",
"if",
"the",
"record",
"has",
"a",
"guise",
"record",
"identified",
"by",
"on",
"the",
"specified",
"value",
"."
] | f202fdec5a01514bde536b6f37b1129b9351fa00 | https://github.com/ecbypi/guise/blob/f202fdec5a01514bde536b6f37b1129b9351fa00/lib/guise/introspection.rb#L12-L23 | train |
koffeinfrei/technologist | lib/technologist/yaml_parser.rb | Technologist.YamlParser.instancify | def instancify(technology, rule)
class_name, attributes = send("parse_rule_of_type_#{rule.class.name.downcase}", rule)
Rule.const_get("#{class_name}Rule").new(technology, attributes)
end | ruby | def instancify(technology, rule)
class_name, attributes = send("parse_rule_of_type_#{rule.class.name.downcase}", rule)
Rule.const_get("#{class_name}Rule").new(technology, attributes)
end | [
"def",
"instancify",
"(",
"technology",
",",
"rule",
")",
"class_name",
",",
"attributes",
"=",
"send",
"(",
"\"parse_rule_of_type_#{rule.class.name.downcase}\"",
",",
"rule",
")",
"Rule",
".",
"const_get",
"(",
"\"#{class_name}Rule\"",
")",
".",
"new",
"(",
"technology",
",",
"attributes",
")",
"end"
] | Create a class instance for a rule entry | [
"Create",
"a",
"class",
"instance",
"for",
"a",
"rule",
"entry"
] | 0fd1d5c07c6d73ac5a184b26ad6db40981388573 | https://github.com/koffeinfrei/technologist/blob/0fd1d5c07c6d73ac5a184b26ad6db40981388573/lib/technologist/yaml_parser.rb#L33-L37 | train |
linrock/favicon_party | lib/favicon_party/fetcher.rb | FaviconParty.Fetcher.find_favicon_urls_in_html | def find_favicon_urls_in_html(html)
doc = Nokogiri.parse html
candidate_urls = doc.css(ICON_SELECTORS.join(",")).map {|e| e.attr('href') }.compact
candidate_urls.sort_by! {|href|
if href =~ /\.ico/
0
elsif href =~ /\.png/
1
else
2
end
}
uri = URI final_url
candidate_urls.map! do |href|
href = URI.encode(URI.decode(href.strip))
if href =~ /\A\/\//
href = "#{uri.scheme}:#{href}"
elsif href !~ /\Ahttp/
# Ignore invalid URLS - ex. {http://i50.tinypic.com/wbuzcn.png}
href = URI.join(url_root, href).to_s rescue nil
end
href
end.compact.uniq
end | ruby | def find_favicon_urls_in_html(html)
doc = Nokogiri.parse html
candidate_urls = doc.css(ICON_SELECTORS.join(",")).map {|e| e.attr('href') }.compact
candidate_urls.sort_by! {|href|
if href =~ /\.ico/
0
elsif href =~ /\.png/
1
else
2
end
}
uri = URI final_url
candidate_urls.map! do |href|
href = URI.encode(URI.decode(href.strip))
if href =~ /\A\/\//
href = "#{uri.scheme}:#{href}"
elsif href !~ /\Ahttp/
# Ignore invalid URLS - ex. {http://i50.tinypic.com/wbuzcn.png}
href = URI.join(url_root, href).to_s rescue nil
end
href
end.compact.uniq
end | [
"def",
"find_favicon_urls_in_html",
"(",
"html",
")",
"doc",
"=",
"Nokogiri",
".",
"parse",
"html",
"candidate_urls",
"=",
"doc",
".",
"css",
"(",
"ICON_SELECTORS",
".",
"join",
"(",
"\",\"",
")",
")",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"attr",
"(",
"'href'",
")",
"}",
".",
"compact",
"candidate_urls",
".",
"sort_by!",
"{",
"|",
"href",
"|",
"if",
"href",
"=~",
"/",
"\\.",
"/",
"0",
"elsif",
"href",
"=~",
"/",
"\\.",
"/",
"1",
"else",
"2",
"end",
"}",
"uri",
"=",
"URI",
"final_url",
"candidate_urls",
".",
"map!",
"do",
"|",
"href",
"|",
"href",
"=",
"URI",
".",
"encode",
"(",
"URI",
".",
"decode",
"(",
"href",
".",
"strip",
")",
")",
"if",
"href",
"=~",
"/",
"\\A",
"\\/",
"\\/",
"/",
"href",
"=",
"\"#{uri.scheme}:#{href}\"",
"elsif",
"href",
"!~",
"/",
"\\A",
"/",
"href",
"=",
"URI",
".",
"join",
"(",
"url_root",
",",
"href",
")",
".",
"to_s",
"rescue",
"nil",
"end",
"href",
"end",
".",
"compact",
".",
"uniq",
"end"
] | Tries to find favicon urls from the html content of query_url | [
"Tries",
"to",
"find",
"favicon",
"urls",
"from",
"the",
"html",
"content",
"of",
"query_url"
] | 645d3c6f4a7152bf705ac092976a74f405f83ca1 | https://github.com/linrock/favicon_party/blob/645d3c6f4a7152bf705ac092976a74f405f83ca1/lib/favicon_party/fetcher.rb#L70-L93 | train |
linrock/favicon_party | lib/favicon_party/fetcher.rb | FaviconParty.Fetcher.final_url | def final_url
return @final_url if !@final_url.nil?
location = final_location(FaviconParty::HTTPClient.head(@query_url))
if !location.nil?
if location =~ /\Ahttp/
@final_url = URI.encode location
else
uri = URI @query_url
root = "#{uri.scheme}://#{uri.host}"
@final_url = URI.encode URI.join(root, location).to_s
end
end
if !@final_url.nil?
if %w( 127.0.0.1 localhost ).any? {|host| @final_url.include? host }
# TODO Exception for invalid final urls
@final_url = @query_url
end
return @final_url
end
@final_url = @query_url
end | ruby | def final_url
return @final_url if !@final_url.nil?
location = final_location(FaviconParty::HTTPClient.head(@query_url))
if !location.nil?
if location =~ /\Ahttp/
@final_url = URI.encode location
else
uri = URI @query_url
root = "#{uri.scheme}://#{uri.host}"
@final_url = URI.encode URI.join(root, location).to_s
end
end
if !@final_url.nil?
if %w( 127.0.0.1 localhost ).any? {|host| @final_url.include? host }
# TODO Exception for invalid final urls
@final_url = @query_url
end
return @final_url
end
@final_url = @query_url
end | [
"def",
"final_url",
"return",
"@final_url",
"if",
"!",
"@final_url",
".",
"nil?",
"location",
"=",
"final_location",
"(",
"FaviconParty",
"::",
"HTTPClient",
".",
"head",
"(",
"@query_url",
")",
")",
"if",
"!",
"location",
".",
"nil?",
"if",
"location",
"=~",
"/",
"\\A",
"/",
"@final_url",
"=",
"URI",
".",
"encode",
"location",
"else",
"uri",
"=",
"URI",
"@query_url",
"root",
"=",
"\"#{uri.scheme}://#{uri.host}\"",
"@final_url",
"=",
"URI",
".",
"encode",
"URI",
".",
"join",
"(",
"root",
",",
"location",
")",
".",
"to_s",
"end",
"end",
"if",
"!",
"@final_url",
".",
"nil?",
"if",
"%w(",
"127.0.0.1",
"localhost",
")",
".",
"any?",
"{",
"|",
"host",
"|",
"@final_url",
".",
"include?",
"host",
"}",
"@final_url",
"=",
"@query_url",
"end",
"return",
"@final_url",
"end",
"@final_url",
"=",
"@query_url",
"end"
] | Follow redirects from the query url to get to the last url | [
"Follow",
"redirects",
"from",
"the",
"query",
"url",
"to",
"get",
"to",
"the",
"last",
"url"
] | 645d3c6f4a7152bf705ac092976a74f405f83ca1 | https://github.com/linrock/favicon_party/blob/645d3c6f4a7152bf705ac092976a74f405f83ca1/lib/favicon_party/fetcher.rb#L108-L128 | train |
bilus/kawaii | lib/kawaii/routing_methods.rb | Kawaii.RoutingMethods.context | def context(path, &block)
ctx = RouteContext.new(self, path)
# @todo Is there a better way to keep ordering of routes?
# An alternative would be to enter each route in a context only once
# (with 'prefix' based on containing contexts).
# On the other hand, we're only doing that when compiling routes, further
# processing is faster this way.
ctx.instance_eval(&block)
ctx.methods_used.each do |meth|
add_route!(meth, ctx)
end
end | ruby | def context(path, &block)
ctx = RouteContext.new(self, path)
# @todo Is there a better way to keep ordering of routes?
# An alternative would be to enter each route in a context only once
# (with 'prefix' based on containing contexts).
# On the other hand, we're only doing that when compiling routes, further
# processing is faster this way.
ctx.instance_eval(&block)
ctx.methods_used.each do |meth|
add_route!(meth, ctx)
end
end | [
"def",
"context",
"(",
"path",
",",
"&",
"block",
")",
"ctx",
"=",
"RouteContext",
".",
"new",
"(",
"self",
",",
"path",
")",
"ctx",
".",
"instance_eval",
"(",
"&",
"block",
")",
"ctx",
".",
"methods_used",
".",
"each",
"do",
"|",
"meth",
"|",
"add_route!",
"(",
"meth",
",",
"ctx",
")",
"end",
"end"
] | Create a context for route nesting.
@param path [String, Regexp, Matcher] any path specification which can
be consumed by {Matcher.compile}
@param block the route handler
@yield to the given block
@example A simple context
context '/foo' do
get '/bar' do
end
end | [
"Create",
"a",
"context",
"for",
"route",
"nesting",
"."
] | a72be28e713b0ed2b2cfc180a38bebe0c968b0b3 | https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/routing_methods.rb#L80-L91 | train |
bilus/kawaii | lib/kawaii/routing_methods.rb | Kawaii.RoutingMethods.match | def match(env)
routes[env[Rack::REQUEST_METHOD]]
.lazy # Lazy to avoid unnecessary calls to #match.
.map { |r| r.match(env) }
.find { |r| !r.nil? }
end | ruby | def match(env)
routes[env[Rack::REQUEST_METHOD]]
.lazy # Lazy to avoid unnecessary calls to #match.
.map { |r| r.match(env) }
.find { |r| !r.nil? }
end | [
"def",
"match",
"(",
"env",
")",
"routes",
"[",
"env",
"[",
"Rack",
"::",
"REQUEST_METHOD",
"]",
"]",
".",
"lazy",
".",
"map",
"{",
"|",
"r",
"|",
"r",
".",
"match",
"(",
"env",
")",
"}",
".",
"find",
"{",
"|",
"r",
"|",
"!",
"r",
".",
"nil?",
"}",
"end"
] | Tries to match against a Rack environment.
@param env [Hash] Rack environment
@return [Route] matching route. Can be nil if no match found. | [
"Tries",
"to",
"match",
"against",
"a",
"Rack",
"environment",
"."
] | a72be28e713b0ed2b2cfc180a38bebe0c968b0b3 | https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/routing_methods.rb#L96-L101 | train |
thedamfr/glass | lib/glass/timeline/timeline_item.rb | Glass.TimelineItem.insert! | def insert!(mirror=@client)
timeline_item = self
result = []
if file_upload?
for file in file_to_upload
media = Google::APIClient::UploadIO.new(file.contentUrl, file.content_type)
result << client.execute!(
:api_method => mirror.timeline.insert,
:body_object => timeline_item,
:media => media,
:parameters => {
:uploadType => 'multipart',
:alt => 'json'})
end
else
result << client.execute(
:api_method => mirror.timeline.insert,
:body_object => timeline_item)
end
return result.data
end | ruby | def insert!(mirror=@client)
timeline_item = self
result = []
if file_upload?
for file in file_to_upload
media = Google::APIClient::UploadIO.new(file.contentUrl, file.content_type)
result << client.execute!(
:api_method => mirror.timeline.insert,
:body_object => timeline_item,
:media => media,
:parameters => {
:uploadType => 'multipart',
:alt => 'json'})
end
else
result << client.execute(
:api_method => mirror.timeline.insert,
:body_object => timeline_item)
end
return result.data
end | [
"def",
"insert!",
"(",
"mirror",
"=",
"@client",
")",
"timeline_item",
"=",
"self",
"result",
"=",
"[",
"]",
"if",
"file_upload?",
"for",
"file",
"in",
"file_to_upload",
"media",
"=",
"Google",
"::",
"APIClient",
"::",
"UploadIO",
".",
"new",
"(",
"file",
".",
"contentUrl",
",",
"file",
".",
"content_type",
")",
"result",
"<<",
"client",
".",
"execute!",
"(",
":api_method",
"=>",
"mirror",
".",
"timeline",
".",
"insert",
",",
":body_object",
"=>",
"timeline_item",
",",
":media",
"=>",
"media",
",",
":parameters",
"=>",
"{",
":uploadType",
"=>",
"'multipart'",
",",
":alt",
"=>",
"'json'",
"}",
")",
"end",
"else",
"result",
"<<",
"client",
".",
"execute",
"(",
":api_method",
"=>",
"mirror",
".",
"timeline",
".",
"insert",
",",
":body_object",
"=>",
"timeline_item",
")",
"end",
"return",
"result",
".",
"data",
"end"
] | Insert a new Timeline Item in the user's glass.
@param [Google::APIClient::API] client
Authorized client instance.
@return Array[Google::APIClient::Schema::Mirror::V1::TimelineItem]
Timeline item instance if successful, nil otherwise. | [
"Insert",
"a",
"new",
"Timeline",
"Item",
"in",
"the",
"user",
"s",
"glass",
"."
] | dbbd39d3a3f3d18bd36bd5fbf59d8a9fe2f6d040 | https://github.com/thedamfr/glass/blob/dbbd39d3a3f3d18bd36bd5fbf59d8a9fe2f6d040/lib/glass/timeline/timeline_item.rb#L359-L379 | train |
sugaryourcoffee/syclink | lib/syclink/link.rb | SycLink.Link.select_defined | def select_defined(args)
args.select { |k, v| (ATTRS.include? k) && !v.nil? }
end | ruby | def select_defined(args)
args.select { |k, v| (ATTRS.include? k) && !v.nil? }
end | [
"def",
"select_defined",
"(",
"args",
")",
"args",
".",
"select",
"{",
"|",
"k",
",",
"v",
"|",
"(",
"ATTRS",
".",
"include?",
"k",
")",
"&&",
"!",
"v",
".",
"nil?",
"}",
"end"
] | Based on the ATTRS the args are returned that are included in the ATTRS.
args with nil values are omitted | [
"Based",
"on",
"the",
"ATTRS",
"the",
"args",
"are",
"returned",
"that",
"are",
"included",
"in",
"the",
"ATTRS",
".",
"args",
"with",
"nil",
"values",
"are",
"omitted"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/link.rb#L86-L88 | train |
jeremyvdw/disqussion | lib/disqussion/client/exports.rb | Disqussion.Exports.exportForum | def exportForum(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
if args.size == 1
options.merge!(:forum => args[0])
response = post('exports/exportForum', options)
else
puts "#{Kernel.caller.first}: exports.exportForum expects an arguments: forum"
end
end | ruby | def exportForum(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
if args.size == 1
options.merge!(:forum => args[0])
response = post('exports/exportForum', options)
else
puts "#{Kernel.caller.first}: exports.exportForum expects an arguments: forum"
end
end | [
"def",
"exportForum",
"(",
"*",
"args",
")",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"if",
"args",
".",
"size",
"==",
"1",
"options",
".",
"merge!",
"(",
":forum",
"=>",
"args",
"[",
"0",
"]",
")",
"response",
"=",
"post",
"(",
"'exports/exportForum'",
",",
"options",
")",
"else",
"puts",
"\"#{Kernel.caller.first}: exports.exportForum expects an arguments: forum\"",
"end",
"end"
] | Export a forum
@accessibility: public key, secret key
@methods: POST
@format: json, jsonp
@authenticated: true
@limited: false
@param forum [String] Forum short name (aka forum id).
@return [Hashie::Rash] Export infos
@param options [Hash] A customizable set of options.
@option options [String] :format. Defaults to "xml". Choices: xml, xml-old
@example Export forum "the88"
Disqussion::Client.exports.exportForum("the88")
@see: http://disqus.com/api/3.0/exports/exportForum.json | [
"Export",
"a",
"forum"
] | 5ad1b0325b7630daf41eb59fc8acbcb785cbc387 | https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/exports.rb#L16-L24 | train |
ktonon/code_node | spec/fixtures/activerecord/src/active_record/persistence.rb | ActiveRecord.Persistence.update_column | def update_column(name, value)
name = name.to_s
raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
raise ActiveRecordError, "can not update on a new record object" unless persisted?
updated_count = self.class.update_all({ name => value }, self.class.primary_key => id)
raw_write_attribute(name, value)
updated_count == 1
end | ruby | def update_column(name, value)
name = name.to_s
raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
raise ActiveRecordError, "can not update on a new record object" unless persisted?
updated_count = self.class.update_all({ name => value }, self.class.primary_key => id)
raw_write_attribute(name, value)
updated_count == 1
end | [
"def",
"update_column",
"(",
"name",
",",
"value",
")",
"name",
"=",
"name",
".",
"to_s",
"raise",
"ActiveRecordError",
",",
"\"#{name} is marked as readonly\"",
"if",
"self",
".",
"class",
".",
"readonly_attributes",
".",
"include?",
"(",
"name",
")",
"raise",
"ActiveRecordError",
",",
"\"can not update on a new record object\"",
"unless",
"persisted?",
"updated_count",
"=",
"self",
".",
"class",
".",
"update_all",
"(",
"{",
"name",
"=>",
"value",
"}",
",",
"self",
".",
"class",
".",
"primary_key",
"=>",
"id",
")",
"raw_write_attribute",
"(",
"name",
",",
"value",
")",
"updated_count",
"==",
"1",
"end"
] | Updates a single attribute of an object, without calling save.
* Validation is skipped.
* Callbacks are skipped.
* updated_at/updated_on column is not updated if that column is available.
Raises an +ActiveRecordError+ when called on new objects, or when the +name+
attribute is marked as readonly. | [
"Updates",
"a",
"single",
"attribute",
"of",
"an",
"object",
"without",
"calling",
"save",
"."
] | 48d5d1a7442d9cade602be4fb782a1b56c7677f5 | https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/persistence.rb#L192-L202 | train |
tubbo/active_copy | lib/active_copy/paths.rb | ActiveCopy.Paths.source_path | def source_path options={}
@source_path ||= if options[:relative]
File.join collection_path, "#{self.id}.md"
else
File.join root_path, collection_path, "#{self.id}.md"
end
end | ruby | def source_path options={}
@source_path ||= if options[:relative]
File.join collection_path, "#{self.id}.md"
else
File.join root_path, collection_path, "#{self.id}.md"
end
end | [
"def",
"source_path",
"options",
"=",
"{",
"}",
"@source_path",
"||=",
"if",
"options",
"[",
":relative",
"]",
"File",
".",
"join",
"collection_path",
",",
"\"#{self.id}.md\"",
"else",
"File",
".",
"join",
"root_path",
",",
"collection_path",
",",
"\"#{self.id}.md\"",
"end",
"end"
] | Return absolute path to Markdown file on this machine. | [
"Return",
"absolute",
"path",
"to",
"Markdown",
"file",
"on",
"this",
"machine",
"."
] | 63716fdd9283231e9ed0d8ac6af97633d3e97210 | https://github.com/tubbo/active_copy/blob/63716fdd9283231e9ed0d8ac6af97633d3e97210/lib/active_copy/paths.rb#L40-L46 | train |
mobyinc/Cathode | lib/cathode/update_request.rb | Cathode.UpdateRequest.default_action_block | def default_action_block
proc do
begin
record = if resource.singular
parent_model = resource.parent.model.find(parent_resource_id)
parent_model.send resource.name
else
record = model.find(params[:id])
end
record.update(instance_eval(&@strong_params))
body record.reload
rescue ActionController::ParameterMissing => error
body error.message
status :bad_request
end
end
end | ruby | def default_action_block
proc do
begin
record = if resource.singular
parent_model = resource.parent.model.find(parent_resource_id)
parent_model.send resource.name
else
record = model.find(params[:id])
end
record.update(instance_eval(&@strong_params))
body record.reload
rescue ActionController::ParameterMissing => error
body error.message
status :bad_request
end
end
end | [
"def",
"default_action_block",
"proc",
"do",
"begin",
"record",
"=",
"if",
"resource",
".",
"singular",
"parent_model",
"=",
"resource",
".",
"parent",
".",
"model",
".",
"find",
"(",
"parent_resource_id",
")",
"parent_model",
".",
"send",
"resource",
".",
"name",
"else",
"record",
"=",
"model",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"end",
"record",
".",
"update",
"(",
"instance_eval",
"(",
"&",
"@strong_params",
")",
")",
"body",
"record",
".",
"reload",
"rescue",
"ActionController",
"::",
"ParameterMissing",
"=>",
"error",
"body",
"error",
".",
"message",
"status",
":bad_request",
"end",
"end",
"end"
] | Sets the default action to update a resource. If the resource is
singular, updates the parent's associated resource. Otherwise, updates the
resource directly. | [
"Sets",
"the",
"default",
"action",
"to",
"update",
"a",
"resource",
".",
"If",
"the",
"resource",
"is",
"singular",
"updates",
"the",
"parent",
"s",
"associated",
"resource",
".",
"Otherwise",
"updates",
"the",
"resource",
"directly",
"."
] | e17be4fb62ad61417e2a3a0a77406459015468a1 | https://github.com/mobyinc/Cathode/blob/e17be4fb62ad61417e2a3a0a77406459015468a1/lib/cathode/update_request.rb#L7-L24 | train |
groupdocs-signature-cloud/groupdocs-signature-cloud-ruby | lib/groupdocs_signature_cloud/api_client.rb | GroupDocsSignatureCloud.ApiClient.deserialize | def deserialize(response, return_type)
body = response.body
# handle file downloading - return the File instance processed in request callbacks
# note that response body is empty when the file is written in chunks in request on_body callback
return @tempfile if return_type == 'File'
return nil if body.nil? || body.empty?
# return response body directly for String return type
return body if return_type == 'String'
# ensuring a default content type
content_type = response.headers['Content-Type'] || 'application/json'
raise "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w[String Date DateTime].include?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end | ruby | def deserialize(response, return_type)
body = response.body
# handle file downloading - return the File instance processed in request callbacks
# note that response body is empty when the file is written in chunks in request on_body callback
return @tempfile if return_type == 'File'
return nil if body.nil? || body.empty?
# return response body directly for String return type
return body if return_type == 'String'
# ensuring a default content type
content_type = response.headers['Content-Type'] || 'application/json'
raise "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w[String Date DateTime].include?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end | [
"def",
"deserialize",
"(",
"response",
",",
"return_type",
")",
"body",
"=",
"response",
".",
"body",
"return",
"@tempfile",
"if",
"return_type",
"==",
"'File'",
"return",
"nil",
"if",
"body",
".",
"nil?",
"||",
"body",
".",
"empty?",
"return",
"body",
"if",
"return_type",
"==",
"'String'",
"content_type",
"=",
"response",
".",
"headers",
"[",
"'Content-Type'",
"]",
"||",
"'application/json'",
"raise",
"\"Content-Type is not supported: #{content_type}\"",
"unless",
"json_mime?",
"(",
"content_type",
")",
"begin",
"data",
"=",
"JSON",
".",
"parse",
"(",
"\"[#{body}]\"",
",",
":symbolize_names",
"=>",
"true",
")",
"[",
"0",
"]",
"rescue",
"JSON",
"::",
"ParserError",
"=>",
"e",
"if",
"%w[",
"String",
"Date",
"DateTime",
"]",
".",
"include?",
"(",
"return_type",
")",
"data",
"=",
"body",
"else",
"raise",
"e",
"end",
"end",
"convert_to_type",
"data",
",",
"return_type",
"end"
] | Deserialize the response to the given return type.
@param [Response] response HTTP response
@param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" | [
"Deserialize",
"the",
"response",
"to",
"the",
"given",
"return",
"type",
"."
] | d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0 | https://github.com/groupdocs-signature-cloud/groupdocs-signature-cloud-ruby/blob/d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0/lib/groupdocs_signature_cloud/api_client.rb#L150-L178 | train |
davidan1981/rails-identity | app/controllers/rails_identity/sessions_controller.rb | RailsIdentity.SessionsController.index | def index
@sessions = Session.where(user: @user)
expired = []
active = []
@sessions.each do |session|
if session.expired?
expired << session.uuid
else
active << session
end
end
SessionsCleanupJob.perform_later(*expired)
render json: active, except: [:secret]
end | ruby | def index
@sessions = Session.where(user: @user)
expired = []
active = []
@sessions.each do |session|
if session.expired?
expired << session.uuid
else
active << session
end
end
SessionsCleanupJob.perform_later(*expired)
render json: active, except: [:secret]
end | [
"def",
"index",
"@sessions",
"=",
"Session",
".",
"where",
"(",
"user",
":",
"@user",
")",
"expired",
"=",
"[",
"]",
"active",
"=",
"[",
"]",
"@sessions",
".",
"each",
"do",
"|",
"session",
"|",
"if",
"session",
".",
"expired?",
"expired",
"<<",
"session",
".",
"uuid",
"else",
"active",
"<<",
"session",
"end",
"end",
"SessionsCleanupJob",
".",
"perform_later",
"(",
"*",
"expired",
")",
"render",
"json",
":",
"active",
",",
"except",
":",
"[",
":secret",
"]",
"end"
] | Lists all sessions that belong to the specified or authenticated user. | [
"Lists",
"all",
"sessions",
"that",
"belong",
"to",
"the",
"specified",
"or",
"authenticated",
"user",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/controllers/rails_identity/sessions_controller.rb#L19-L32 | train |
davidan1981/rails-identity | app/controllers/rails_identity/sessions_controller.rb | RailsIdentity.SessionsController.create | def create
# See if OAuth is used first. When authenticated successfully, either
# the existing user will be found or a new user will be created.
# Failure will be redirected to this action but will not match this
# branch.
if (omniauth_hash = request.env["omniauth.auth"])
@user = User.from_omniauth_hash(omniauth_hash)
# Then see if the request already has authentication. Note that if the
# user does not have access to the specified session owner, 401 will
# be thrown.
elsif accept_auth
@user = @auth_user
# Otherwise, it's a normal login process. Use username and password to
# authenticate. The user must exist, the password must be vaild, and
# the email must have been verified.
else
@user = User.find_by_username(session_params[:username])
if (@user.nil? || [email protected](session_params[:password]) ||
[email protected])
raise ApplicationController::UNAUTHORIZED_ERROR
end
end
# Finally, create session regardless of the method and store it.
@session = Session.new(user: @user)
if @session.save
if omniauth_hash
# redirect_to the app page that accepts new session token
url = Rails.application.config.oauth_landing_page_url
url = "#{url}?token=#{@session.token}"
render inline: "", status: 302, location: url
else
render json: @session, except: [:secret], status: 201
end
else
# :nocov:
render_errors 400, @session.full_error_messages
# :nocov:
end
end | ruby | def create
# See if OAuth is used first. When authenticated successfully, either
# the existing user will be found or a new user will be created.
# Failure will be redirected to this action but will not match this
# branch.
if (omniauth_hash = request.env["omniauth.auth"])
@user = User.from_omniauth_hash(omniauth_hash)
# Then see if the request already has authentication. Note that if the
# user does not have access to the specified session owner, 401 will
# be thrown.
elsif accept_auth
@user = @auth_user
# Otherwise, it's a normal login process. Use username and password to
# authenticate. The user must exist, the password must be vaild, and
# the email must have been verified.
else
@user = User.find_by_username(session_params[:username])
if (@user.nil? || [email protected](session_params[:password]) ||
[email protected])
raise ApplicationController::UNAUTHORIZED_ERROR
end
end
# Finally, create session regardless of the method and store it.
@session = Session.new(user: @user)
if @session.save
if omniauth_hash
# redirect_to the app page that accepts new session token
url = Rails.application.config.oauth_landing_page_url
url = "#{url}?token=#{@session.token}"
render inline: "", status: 302, location: url
else
render json: @session, except: [:secret], status: 201
end
else
# :nocov:
render_errors 400, @session.full_error_messages
# :nocov:
end
end | [
"def",
"create",
"if",
"(",
"omniauth_hash",
"=",
"request",
".",
"env",
"[",
"\"omniauth.auth\"",
"]",
")",
"@user",
"=",
"User",
".",
"from_omniauth_hash",
"(",
"omniauth_hash",
")",
"elsif",
"accept_auth",
"@user",
"=",
"@auth_user",
"else",
"@user",
"=",
"User",
".",
"find_by_username",
"(",
"session_params",
"[",
":username",
"]",
")",
"if",
"(",
"@user",
".",
"nil?",
"||",
"!",
"@user",
".",
"authenticate",
"(",
"session_params",
"[",
":password",
"]",
")",
"||",
"!",
"@user",
".",
"verified",
")",
"raise",
"ApplicationController",
"::",
"UNAUTHORIZED_ERROR",
"end",
"end",
"@session",
"=",
"Session",
".",
"new",
"(",
"user",
":",
"@user",
")",
"if",
"@session",
".",
"save",
"if",
"omniauth_hash",
"url",
"=",
"Rails",
".",
"application",
".",
"config",
".",
"oauth_landing_page_url",
"url",
"=",
"\"#{url}?token=#{@session.token}\"",
"render",
"inline",
":",
"\"\"",
",",
"status",
":",
"302",
",",
"location",
":",
"url",
"else",
"render",
"json",
":",
"@session",
",",
"except",
":",
"[",
":secret",
"]",
",",
"status",
":",
"201",
"end",
"else",
"render_errors",
"400",
",",
"@session",
".",
"full_error_messages",
"end",
"end"
] | This action is essentially the login action. Note that get_user is not
triggered for this action because we will look at username first. That
would be the "normal" way to login. The alternative would be with the
token based authentication. If the latter doesn't make sense, just use
the username and password approach.
A ApplicationController::UNAUTHORIZED_ERROR is thrown if user is not
verified. | [
"This",
"action",
"is",
"essentially",
"the",
"login",
"action",
".",
"Note",
"that",
"get_user",
"is",
"not",
"triggered",
"for",
"this",
"action",
"because",
"we",
"will",
"look",
"at",
"username",
"first",
".",
"That",
"would",
"be",
"the",
"normal",
"way",
"to",
"login",
".",
"The",
"alternative",
"would",
"be",
"with",
"the",
"token",
"based",
"authentication",
".",
"If",
"the",
"latter",
"doesn",
"t",
"make",
"sense",
"just",
"use",
"the",
"username",
"and",
"password",
"approach",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/controllers/rails_identity/sessions_controller.rb#L44-L86 | train |
davidan1981/rails-identity | app/controllers/rails_identity/sessions_controller.rb | RailsIdentity.SessionsController.get_session | def get_session
session_id = params[:id]
if session_id == "current"
if @auth_session.nil?
raise Repia::Errors::NotFound
end
session_id = @auth_session.id
end
@session = find_object(Session, session_id)
authorize_for!(@session)
if @session.expired?
@session.destroy
raise Repia::Errors::NotFound
end
end | ruby | def get_session
session_id = params[:id]
if session_id == "current"
if @auth_session.nil?
raise Repia::Errors::NotFound
end
session_id = @auth_session.id
end
@session = find_object(Session, session_id)
authorize_for!(@session)
if @session.expired?
@session.destroy
raise Repia::Errors::NotFound
end
end | [
"def",
"get_session",
"session_id",
"=",
"params",
"[",
":id",
"]",
"if",
"session_id",
"==",
"\"current\"",
"if",
"@auth_session",
".",
"nil?",
"raise",
"Repia",
"::",
"Errors",
"::",
"NotFound",
"end",
"session_id",
"=",
"@auth_session",
".",
"id",
"end",
"@session",
"=",
"find_object",
"(",
"Session",
",",
"session_id",
")",
"authorize_for!",
"(",
"@session",
")",
"if",
"@session",
".",
"expired?",
"@session",
".",
"destroy",
"raise",
"Repia",
"::",
"Errors",
"::",
"NotFound",
"end",
"end"
] | Get the specified or current session.
A Repia::Errors::NotFound is raised if the session does not
exist (or deleted due to expiration).
A ApplicationController::UNAUTHORIZED_ERROR is raised if the
authenticated user does not have authorization for the specified
session. | [
"Get",
"the",
"specified",
"or",
"current",
"session",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/controllers/rails_identity/sessions_controller.rb#L120-L134 | train |
gregspurrier/has_enumeration | lib/has_enumeration/class_methods.rb | HasEnumeration.ClassMethods.has_enumeration | def has_enumeration(enumeration, mapping, options = {})
unless mapping.is_a?(Hash)
# Recast the mapping as a symbol -> string hash
mapping_hash = {}
mapping.each {|m| mapping_hash[m] = m.to_s}
mapping = mapping_hash
end
# The underlying attribute
attribute = options[:attribute] || enumeration
# ActiveRecord's composed_of method will do most of the work for us.
# All we have to do is cons up a class that implements the bidirectional
# mapping described by the provided hash.
klass = create_enumeration_mapping_class(mapping)
attr_enumeration_mapping_classes[enumeration] = klass
# Bind the class to a name within the scope of this class
mapping_class_name = enumeration.to_s.camelize
const_set(mapping_class_name, klass)
scoped_class_name = [self.name, mapping_class_name].join('::')
composed_of(enumeration,
:class_name => scoped_class_name,
:mapping => [attribute.to_s, 'raw_value'],
:converter => :from_sym,
:allow_nil => true
)
if ActiveRecord::VERSION::MAJOR >= 3 && ActiveRecord::VERSION::MINOR == 0
# Install this attributes mapping for use later when extending
# Arel attributes on the fly.
::Arel::Table.has_enumeration_mappings[table_name][attribute] = mapping
else
# Install our aggregate condition handling override, but only once
unless @aggregate_conditions_override_installed
extend HasEnumeration::AggregateConditionsOverride
@aggregate_conditions_override_installed = true
end
end
end | ruby | def has_enumeration(enumeration, mapping, options = {})
unless mapping.is_a?(Hash)
# Recast the mapping as a symbol -> string hash
mapping_hash = {}
mapping.each {|m| mapping_hash[m] = m.to_s}
mapping = mapping_hash
end
# The underlying attribute
attribute = options[:attribute] || enumeration
# ActiveRecord's composed_of method will do most of the work for us.
# All we have to do is cons up a class that implements the bidirectional
# mapping described by the provided hash.
klass = create_enumeration_mapping_class(mapping)
attr_enumeration_mapping_classes[enumeration] = klass
# Bind the class to a name within the scope of this class
mapping_class_name = enumeration.to_s.camelize
const_set(mapping_class_name, klass)
scoped_class_name = [self.name, mapping_class_name].join('::')
composed_of(enumeration,
:class_name => scoped_class_name,
:mapping => [attribute.to_s, 'raw_value'],
:converter => :from_sym,
:allow_nil => true
)
if ActiveRecord::VERSION::MAJOR >= 3 && ActiveRecord::VERSION::MINOR == 0
# Install this attributes mapping for use later when extending
# Arel attributes on the fly.
::Arel::Table.has_enumeration_mappings[table_name][attribute] = mapping
else
# Install our aggregate condition handling override, but only once
unless @aggregate_conditions_override_installed
extend HasEnumeration::AggregateConditionsOverride
@aggregate_conditions_override_installed = true
end
end
end | [
"def",
"has_enumeration",
"(",
"enumeration",
",",
"mapping",
",",
"options",
"=",
"{",
"}",
")",
"unless",
"mapping",
".",
"is_a?",
"(",
"Hash",
")",
"mapping_hash",
"=",
"{",
"}",
"mapping",
".",
"each",
"{",
"|",
"m",
"|",
"mapping_hash",
"[",
"m",
"]",
"=",
"m",
".",
"to_s",
"}",
"mapping",
"=",
"mapping_hash",
"end",
"attribute",
"=",
"options",
"[",
":attribute",
"]",
"||",
"enumeration",
"klass",
"=",
"create_enumeration_mapping_class",
"(",
"mapping",
")",
"attr_enumeration_mapping_classes",
"[",
"enumeration",
"]",
"=",
"klass",
"mapping_class_name",
"=",
"enumeration",
".",
"to_s",
".",
"camelize",
"const_set",
"(",
"mapping_class_name",
",",
"klass",
")",
"scoped_class_name",
"=",
"[",
"self",
".",
"name",
",",
"mapping_class_name",
"]",
".",
"join",
"(",
"'::'",
")",
"composed_of",
"(",
"enumeration",
",",
":class_name",
"=>",
"scoped_class_name",
",",
":mapping",
"=>",
"[",
"attribute",
".",
"to_s",
",",
"'raw_value'",
"]",
",",
":converter",
"=>",
":from_sym",
",",
":allow_nil",
"=>",
"true",
")",
"if",
"ActiveRecord",
"::",
"VERSION",
"::",
"MAJOR",
">=",
"3",
"&&",
"ActiveRecord",
"::",
"VERSION",
"::",
"MINOR",
"==",
"0",
"::",
"Arel",
"::",
"Table",
".",
"has_enumeration_mappings",
"[",
"table_name",
"]",
"[",
"attribute",
"]",
"=",
"mapping",
"else",
"unless",
"@aggregate_conditions_override_installed",
"extend",
"HasEnumeration",
"::",
"AggregateConditionsOverride",
"@aggregate_conditions_override_installed",
"=",
"true",
"end",
"end",
"end"
] | Declares an enumerated attribute called +enumeration+ consisting of
the symbols defined in +mapping+.
When the database representation of the attribute is a string, +mapping+
can be an array of symbols. The string representation of the symbol
will be stored in the databased. E.g.:
has_enumeration :color, [:red, :green, :blue]
When the database representation of the attribute is not a string, or
if its values do not match up with the string versions of its symbols,
an hash mapping symbols to their underlying values may be used:
has_enumeration :color, :red => 1, :green => 2, :blue => 3
By default, has_enumeration assumes that the column in the database
has the same name as the enumeration. If this is not the case, the
column can be specified with the :attribute option:
has_enumeration :color, [:red, :green, :blue], :attribute => :hue | [
"Declares",
"an",
"enumerated",
"attribute",
"called",
"+",
"enumeration",
"+",
"consisting",
"of",
"the",
"symbols",
"defined",
"in",
"+",
"mapping",
"+",
"."
] | 40487c5b4958364ca6acaab3f05561ae0dca073e | https://github.com/gregspurrier/has_enumeration/blob/40487c5b4958364ca6acaab3f05561ae0dca073e/lib/has_enumeration/class_methods.rb#L24-L64 | train |
kmewhort/similarity_tree | lib/similarity_tree/node.rb | SimilarityTree.Node.depth_first_recurse | def depth_first_recurse(node = nil, depth = 0, &block)
node = self if node == nil
yield node, depth
node.children.each do |child|
depth_first_recurse(child, depth+1, &block)
end
end | ruby | def depth_first_recurse(node = nil, depth = 0, &block)
node = self if node == nil
yield node, depth
node.children.each do |child|
depth_first_recurse(child, depth+1, &block)
end
end | [
"def",
"depth_first_recurse",
"(",
"node",
"=",
"nil",
",",
"depth",
"=",
"0",
",",
"&",
"block",
")",
"node",
"=",
"self",
"if",
"node",
"==",
"nil",
"yield",
"node",
",",
"depth",
"node",
".",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"depth_first_recurse",
"(",
"child",
",",
"depth",
"+",
"1",
",",
"&",
"block",
")",
"end",
"end"
] | helper for recursion into descendents | [
"helper",
"for",
"recursion",
"into",
"descendents"
] | d688c6d86e2a5a81ff71e81ef805c9af6cb8c8e7 | https://github.com/kmewhort/similarity_tree/blob/d688c6d86e2a5a81ff71e81ef805c9af6cb8c8e7/lib/similarity_tree/node.rb#L45-L51 | train |
chetan/curb_threadpool | lib/curb_threadpool.rb | Curl.ThreadPool.perform | def perform(async=false, &block)
@results = {}
@clients.each do |client|
@threads << Thread.new do
loop do
break if @reqs.empty?
req = @reqs.shift
break if req.nil? # can sometimes reach here due to a race condition. saw it a lot on travis
client.url = req.uri
args = ["http_#{req.method}"]
if [:put, :post].include? req.method
# add body to args for these methods
if req.body then
if req.body.kind_of? Array then
args += req.body
else
args << req.body
end
else
args << ""
end
end
client.send(*args)
if block then
yield(req, client.body_str)
else
@results[req.key] = client.body_str
end
end
end
end
if async then
# don't wait for threads to join, just return
return true
end
join()
return true if block
return @results
end | ruby | def perform(async=false, &block)
@results = {}
@clients.each do |client|
@threads << Thread.new do
loop do
break if @reqs.empty?
req = @reqs.shift
break if req.nil? # can sometimes reach here due to a race condition. saw it a lot on travis
client.url = req.uri
args = ["http_#{req.method}"]
if [:put, :post].include? req.method
# add body to args for these methods
if req.body then
if req.body.kind_of? Array then
args += req.body
else
args << req.body
end
else
args << ""
end
end
client.send(*args)
if block then
yield(req, client.body_str)
else
@results[req.key] = client.body_str
end
end
end
end
if async then
# don't wait for threads to join, just return
return true
end
join()
return true if block
return @results
end | [
"def",
"perform",
"(",
"async",
"=",
"false",
",",
"&",
"block",
")",
"@results",
"=",
"{",
"}",
"@clients",
".",
"each",
"do",
"|",
"client",
"|",
"@threads",
"<<",
"Thread",
".",
"new",
"do",
"loop",
"do",
"break",
"if",
"@reqs",
".",
"empty?",
"req",
"=",
"@reqs",
".",
"shift",
"break",
"if",
"req",
".",
"nil?",
"client",
".",
"url",
"=",
"req",
".",
"uri",
"args",
"=",
"[",
"\"http_#{req.method}\"",
"]",
"if",
"[",
":put",
",",
":post",
"]",
".",
"include?",
"req",
".",
"method",
"if",
"req",
".",
"body",
"then",
"if",
"req",
".",
"body",
".",
"kind_of?",
"Array",
"then",
"args",
"+=",
"req",
".",
"body",
"else",
"args",
"<<",
"req",
".",
"body",
"end",
"else",
"args",
"<<",
"\"\"",
"end",
"end",
"client",
".",
"send",
"(",
"*",
"args",
")",
"if",
"block",
"then",
"yield",
"(",
"req",
",",
"client",
".",
"body_str",
")",
"else",
"@results",
"[",
"req",
".",
"key",
"]",
"=",
"client",
".",
"body_str",
"end",
"end",
"end",
"end",
"if",
"async",
"then",
"return",
"true",
"end",
"join",
"(",
")",
"return",
"true",
"if",
"block",
"return",
"@results",
"end"
] | Execute requests. By default, will block until complete and return results.
@param [Boolean] async If true, will not wait for requests to finish.
(Default=false)
@param [Block] block If passed, responses will be passed into the callback
instead of being returned directly
@yield [Request, String] Passes to the block the request and the response body
@return [Hash<Key, String>] Hash of responses, if no block given. Returns true otherwise | [
"Execute",
"requests",
".",
"By",
"default",
"will",
"block",
"until",
"complete",
"and",
"return",
"results",
"."
] | 4bea2ac49c67fe2545cc587c7a255224ff9bb477 | https://github.com/chetan/curb_threadpool/blob/4bea2ac49c67fe2545cc587c7a255224ff9bb477/lib/curb_threadpool.rb#L107-L154 | train |
chetan/curb_threadpool | lib/curb_threadpool.rb | Curl.ThreadPool.collate_results | def collate_results(results)
ret = []
results.size.times do |i|
ret << results[i]
end
return ret
end | ruby | def collate_results(results)
ret = []
results.size.times do |i|
ret << results[i]
end
return ret
end | [
"def",
"collate_results",
"(",
"results",
")",
"ret",
"=",
"[",
"]",
"results",
".",
"size",
".",
"times",
"do",
"|",
"i",
"|",
"ret",
"<<",
"results",
"[",
"i",
"]",
"end",
"return",
"ret",
"end"
] | Create ordered array from hash of results | [
"Create",
"ordered",
"array",
"from",
"hash",
"of",
"results"
] | 4bea2ac49c67fe2545cc587c7a255224ff9bb477 | https://github.com/chetan/curb_threadpool/blob/4bea2ac49c67fe2545cc587c7a255224ff9bb477/lib/curb_threadpool.rb#L160-L166 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.