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 |
---|---|---|---|---|---|---|---|---|---|---|---|
caruby/core | lib/caruby/database/sql_executor.rb | CaRuby.SQLExecutor.replace_nil_binds | def replace_nil_binds(sql, args)
nils = []
args.each_with_index { |value, i| nils << i if value.nil? }
unless nils.empty? then
logger.debug { "SQL executor working around RDBI bug by eliminating the nil arguments #{nils.to_series} for the SQL:\n#{sql}..." }
# Quoted ? is too much of a pain for this hack; bail out.
raise ArgumentError.new("RDBI work-around does not support quoted ? in transactional SQL: #{sql}") if sql =~ /'[^,]*[?][^,]*'/
prefix, binds_s, suffix = /(.+\s*values\s*\()([^)]*)(\).*)/i.match(sql).captures
sql = prefix
binds = binds_s.split('?')
last = binds_s[-1, 1]
del_cnt = 0
binds.each_with_index do |s, i|
sql << s
if nils.include?(i) then
args.delete_at(i - del_cnt)
del_cnt += 1
sql << 'NULL'
elsif i < binds.size - 1 or last == '?'
sql << '?'
end
end
sql << suffix
end
logger.debug { "SQL executor converted the SQL to:\n#{sql}\nwith arguments #{args.qp}" }
return args.unshift(sql)
end | ruby | def replace_nil_binds(sql, args)
nils = []
args.each_with_index { |value, i| nils << i if value.nil? }
unless nils.empty? then
logger.debug { "SQL executor working around RDBI bug by eliminating the nil arguments #{nils.to_series} for the SQL:\n#{sql}..." }
# Quoted ? is too much of a pain for this hack; bail out.
raise ArgumentError.new("RDBI work-around does not support quoted ? in transactional SQL: #{sql}") if sql =~ /'[^,]*[?][^,]*'/
prefix, binds_s, suffix = /(.+\s*values\s*\()([^)]*)(\).*)/i.match(sql).captures
sql = prefix
binds = binds_s.split('?')
last = binds_s[-1, 1]
del_cnt = 0
binds.each_with_index do |s, i|
sql << s
if nils.include?(i) then
args.delete_at(i - del_cnt)
del_cnt += 1
sql << 'NULL'
elsif i < binds.size - 1 or last == '?'
sql << '?'
end
end
sql << suffix
end
logger.debug { "SQL executor converted the SQL to:\n#{sql}\nwith arguments #{args.qp}" }
return args.unshift(sql)
end | [
"def",
"replace_nil_binds",
"(",
"sql",
",",
"args",
")",
"nils",
"=",
"[",
"]",
"args",
".",
"each_with_index",
"{",
"|",
"value",
",",
"i",
"|",
"nils",
"<<",
"i",
"if",
"value",
".",
"nil?",
"}",
"unless",
"nils",
".",
"empty?",
"then",
"logger",
".",
"debug",
"{",
"\"SQL executor working around RDBI bug by eliminating the nil arguments #{nils.to_series} for the SQL:\\n#{sql}...\"",
"}",
"# Quoted ? is too much of a pain for this hack; bail out.",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"RDBI work-around does not support quoted ? in transactional SQL: #{sql}\"",
")",
"if",
"sql",
"=~",
"/",
"/",
"prefix",
",",
"binds_s",
",",
"suffix",
"=",
"/",
"\\s",
"\\s",
"\\(",
"\\)",
"/i",
".",
"match",
"(",
"sql",
")",
".",
"captures",
"sql",
"=",
"prefix",
"binds",
"=",
"binds_s",
".",
"split",
"(",
"'?'",
")",
"last",
"=",
"binds_s",
"[",
"-",
"1",
",",
"1",
"]",
"del_cnt",
"=",
"0",
"binds",
".",
"each_with_index",
"do",
"|",
"s",
",",
"i",
"|",
"sql",
"<<",
"s",
"if",
"nils",
".",
"include?",
"(",
"i",
")",
"then",
"args",
".",
"delete_at",
"(",
"i",
"-",
"del_cnt",
")",
"del_cnt",
"+=",
"1",
"sql",
"<<",
"'NULL'",
"elsif",
"i",
"<",
"binds",
".",
"size",
"-",
"1",
"or",
"last",
"==",
"'?'",
"sql",
"<<",
"'?'",
"end",
"end",
"sql",
"<<",
"suffix",
"end",
"logger",
".",
"debug",
"{",
"\"SQL executor converted the SQL to:\\n#{sql}\\nwith arguments #{args.qp}\"",
"}",
"return",
"args",
".",
"unshift",
"(",
"sql",
")",
"end"
] | Replaces nil arguments with a +NULL+ literal in the given SQL.
@param (see #transact)
@return [Array] the (possibly modified) SQL followed by the non-nil arguments | [
"Replaces",
"nil",
"arguments",
"with",
"a",
"+",
"NULL",
"+",
"literal",
"in",
"the",
"given",
"SQL",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/sql_executor.rb#L146-L172 | train |
minch/buoy_data | lib/buoy_data/noaa_station.rb | BuoyData.NoaaStation.current_reading | def current_reading(doc)
reading = {}
xpath = "//table/caption[@class='titleDataHeader']["
xpath += "contains(text(),'Conditions')"
xpath += " and "
xpath += "not(contains(text(),'Solar Radiation'))"
xpath += "]"
# Get the reading timestamp
source_updated_at = reading_timestamp(doc, xpath)
reading[:source_updated_at] = source_updated_at
# Get the reading data
xpath += "/../tr"
elements = doc.xpath xpath
unless elements.empty?
elements.each do |element|
r = scrape_condition_from_element(element)
reading.merge! r unless r.empty?
end
end
reading
end | ruby | def current_reading(doc)
reading = {}
xpath = "//table/caption[@class='titleDataHeader']["
xpath += "contains(text(),'Conditions')"
xpath += " and "
xpath += "not(contains(text(),'Solar Radiation'))"
xpath += "]"
# Get the reading timestamp
source_updated_at = reading_timestamp(doc, xpath)
reading[:source_updated_at] = source_updated_at
# Get the reading data
xpath += "/../tr"
elements = doc.xpath xpath
unless elements.empty?
elements.each do |element|
r = scrape_condition_from_element(element)
reading.merge! r unless r.empty?
end
end
reading
end | [
"def",
"current_reading",
"(",
"doc",
")",
"reading",
"=",
"{",
"}",
"xpath",
"=",
"\"//table/caption[@class='titleDataHeader'][\"",
"xpath",
"+=",
"\"contains(text(),'Conditions')\"",
"xpath",
"+=",
"\" and \"",
"xpath",
"+=",
"\"not(contains(text(),'Solar Radiation'))\"",
"xpath",
"+=",
"\"]\"",
"# Get the reading timestamp",
"source_updated_at",
"=",
"reading_timestamp",
"(",
"doc",
",",
"xpath",
")",
"reading",
"[",
":source_updated_at",
"]",
"=",
"source_updated_at",
"# Get the reading data",
"xpath",
"+=",
"\"/../tr\"",
"elements",
"=",
"doc",
".",
"xpath",
"xpath",
"unless",
"elements",
".",
"empty?",
"elements",
".",
"each",
"do",
"|",
"element",
"|",
"r",
"=",
"scrape_condition_from_element",
"(",
"element",
")",
"reading",
".",
"merge!",
"r",
"unless",
"r",
".",
"empty?",
"end",
"end",
"reading",
"end"
] | Reding from the 'Conditions at..as of..' table | [
"Reding",
"from",
"the",
"Conditions",
"at",
"..",
"as",
"of",
"..",
"table"
] | 6f1e36828ed6df1cb2610d09cc046118291dbe55 | https://github.com/minch/buoy_data/blob/6f1e36828ed6df1cb2610d09cc046118291dbe55/lib/buoy_data/noaa_station.rb#L73-L98 | train |
m-31/vcenter_lib | lib/vcenter_lib/vm_converter.rb | VcenterLib.VmConverter.facts | def facts
logger.debug "get complete data of all VMs in all datacenters: begin"
result = Hash[vm_mos_to_h(@vcenter.vms).map do |h|
[h['name'], Hash[h.map { |k, v| [k.tr('.', '_'), v] }]]
end]
logger.debug "get complete data of all VMs in all datacenters: end"
result
end | ruby | def facts
logger.debug "get complete data of all VMs in all datacenters: begin"
result = Hash[vm_mos_to_h(@vcenter.vms).map do |h|
[h['name'], Hash[h.map { |k, v| [k.tr('.', '_'), v] }]]
end]
logger.debug "get complete data of all VMs in all datacenters: end"
result
end | [
"def",
"facts",
"logger",
".",
"debug",
"\"get complete data of all VMs in all datacenters: begin\"",
"result",
"=",
"Hash",
"[",
"vm_mos_to_h",
"(",
"@vcenter",
".",
"vms",
")",
".",
"map",
"do",
"|",
"h",
"|",
"[",
"h",
"[",
"'name'",
"]",
",",
"Hash",
"[",
"h",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
".",
"tr",
"(",
"'.'",
",",
"'_'",
")",
",",
"v",
"]",
"}",
"]",
"]",
"end",
"]",
"logger",
".",
"debug",
"\"get complete data of all VMs in all datacenters: end\"",
"result",
"end"
] | get all vms and their facts as hash with vm.name as key | [
"get",
"all",
"vms",
"and",
"their",
"facts",
"as",
"hash",
"with",
"vm",
".",
"name",
"as",
"key"
] | 28ed325c73a1faaa5347919006d5a63c1bef6588 | https://github.com/m-31/vcenter_lib/blob/28ed325c73a1faaa5347919006d5a63c1bef6588/lib/vcenter_lib/vm_converter.rb#L54-L61 | train |
ludocracy/Duxml | lib/duxml/doc/element.rb | Duxml.ElementGuts.traverse | def traverse(node=nil, &block)
return self.to_enum unless block_given?
node_stack = [node || self]
until node_stack.empty?
current = node_stack.shift
if current
yield current
node_stack = node_stack.insert(0, *current.nodes) if current.respond_to?(:nodes)
end
end
node || self if block_given?
end | ruby | def traverse(node=nil, &block)
return self.to_enum unless block_given?
node_stack = [node || self]
until node_stack.empty?
current = node_stack.shift
if current
yield current
node_stack = node_stack.insert(0, *current.nodes) if current.respond_to?(:nodes)
end
end
node || self if block_given?
end | [
"def",
"traverse",
"(",
"node",
"=",
"nil",
",",
"&",
"block",
")",
"return",
"self",
".",
"to_enum",
"unless",
"block_given?",
"node_stack",
"=",
"[",
"node",
"||",
"self",
"]",
"until",
"node_stack",
".",
"empty?",
"current",
"=",
"node_stack",
".",
"shift",
"if",
"current",
"yield",
"current",
"node_stack",
"=",
"node_stack",
".",
"insert",
"(",
"0",
",",
"current",
".",
"nodes",
")",
"if",
"current",
".",
"respond_to?",
"(",
":nodes",
")",
"end",
"end",
"node",
"||",
"self",
"if",
"block_given?",
"end"
] | pre-order traverse through this node and all of its descendants
@param &block [block] code to execute for each yielded node | [
"pre",
"-",
"order",
"traverse",
"through",
"this",
"node",
"and",
"all",
"of",
"its",
"descendants"
] | b7d16c0bd27195825620091dfa60e21712221720 | https://github.com/ludocracy/Duxml/blob/b7d16c0bd27195825620091dfa60e21712221720/lib/duxml/doc/element.rb#L215-L226 | train |
sheax0r/ruby-cloudpassage | lib/cloudpassage/base.rb | Cloudpassage.Base.method_missing | def method_missing(sym, *args, &block)
if (data && data[sym])
data[sym]
else
super(sym, *args, &block)
end
end | ruby | def method_missing(sym, *args, &block)
if (data && data[sym])
data[sym]
else
super(sym, *args, &block)
end
end | [
"def",
"method_missing",
"(",
"sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"(",
"data",
"&&",
"data",
"[",
"sym",
"]",
")",
"data",
"[",
"sym",
"]",
"else",
"super",
"(",
"sym",
",",
"args",
",",
"block",
")",
"end",
"end"
] | If method is missing, try to pass through to underlying data hash. | [
"If",
"method",
"is",
"missing",
"try",
"to",
"pass",
"through",
"to",
"underlying",
"data",
"hash",
"."
] | b70d24d0d5f91d92ae8532ed11c087ee9130f6dc | https://github.com/sheax0r/ruby-cloudpassage/blob/b70d24d0d5f91d92ae8532ed11c087ee9130f6dc/lib/cloudpassage/base.rb#L42-L48 | train |
bradfeehan/derelict | lib/derelict/instance.rb | Derelict.Instance.validate! | def validate!
logger.debug "Starting validation for #{description}"
raise NotFound.new path unless File.exists? path
raise NonDirectory.new path unless File.directory? path
raise MissingBinary.new vagrant unless File.exists? vagrant
raise MissingBinary.new vagrant unless File.executable? vagrant
logger.info "Successfully validated #{description}"
self
end | ruby | def validate!
logger.debug "Starting validation for #{description}"
raise NotFound.new path unless File.exists? path
raise NonDirectory.new path unless File.directory? path
raise MissingBinary.new vagrant unless File.exists? vagrant
raise MissingBinary.new vagrant unless File.executable? vagrant
logger.info "Successfully validated #{description}"
self
end | [
"def",
"validate!",
"logger",
".",
"debug",
"\"Starting validation for #{description}\"",
"raise",
"NotFound",
".",
"new",
"path",
"unless",
"File",
".",
"exists?",
"path",
"raise",
"NonDirectory",
".",
"new",
"path",
"unless",
"File",
".",
"directory?",
"path",
"raise",
"MissingBinary",
".",
"new",
"vagrant",
"unless",
"File",
".",
"exists?",
"vagrant",
"raise",
"MissingBinary",
".",
"new",
"vagrant",
"unless",
"File",
".",
"executable?",
"vagrant",
"logger",
".",
"info",
"\"Successfully validated #{description}\"",
"self",
"end"
] | Initialize an instance for a particular directory
* path: The path to the Vagrant installation folder (optional,
defaults to DEFAULT_PATH)
Validates the data used for this instance
Raises exceptions on failure:
* +Derelict::Instance::NotFound+ if the instance is not found
* +Derelict::Instance::NonDirectory+ if the path is a file,
instead of a directory as expected
* +Derelict::Instance::MissingBinary+ if the "vagrant" binary
isn't in the expected location or is not executable | [
"Initialize",
"an",
"instance",
"for",
"a",
"particular",
"directory"
] | c9d70f04562280a34083dd060b0e4099e6f32d8d | https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/instance.rb#L39-L47 | train |
bradfeehan/derelict | lib/derelict/instance.rb | Derelict.Instance.version | def version
logger.info "Determining Vagrant version for #{description}"
output = execute!("--version").stdout
Derelict::Parser::Version.new(output).version
end | ruby | def version
logger.info "Determining Vagrant version for #{description}"
output = execute!("--version").stdout
Derelict::Parser::Version.new(output).version
end | [
"def",
"version",
"logger",
".",
"info",
"\"Determining Vagrant version for #{description}\"",
"output",
"=",
"execute!",
"(",
"\"--version\"",
")",
".",
"stdout",
"Derelict",
"::",
"Parser",
"::",
"Version",
".",
"new",
"(",
"output",
")",
".",
"version",
"end"
] | Determines the version of this Vagrant instance | [
"Determines",
"the",
"version",
"of",
"this",
"Vagrant",
"instance"
] | c9d70f04562280a34083dd060b0e4099e6f32d8d | https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/instance.rb#L50-L54 | train |
bradfeehan/derelict | lib/derelict/instance.rb | Derelict.Instance.execute | def execute(subcommand, *arguments, &block)
options = arguments.last.is_a?(Hash) ? arguments.pop : Hash.new
command = command(subcommand, *arguments)
command = "sudo -- #{command}" if options.delete(:sudo)
logger.debug "Executing #{command} using #{description}"
Executer.execute command, options, &block
end | ruby | def execute(subcommand, *arguments, &block)
options = arguments.last.is_a?(Hash) ? arguments.pop : Hash.new
command = command(subcommand, *arguments)
command = "sudo -- #{command}" if options.delete(:sudo)
logger.debug "Executing #{command} using #{description}"
Executer.execute command, options, &block
end | [
"def",
"execute",
"(",
"subcommand",
",",
"*",
"arguments",
",",
"&",
"block",
")",
"options",
"=",
"arguments",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"arguments",
".",
"pop",
":",
"Hash",
".",
"new",
"command",
"=",
"command",
"(",
"subcommand",
",",
"arguments",
")",
"command",
"=",
"\"sudo -- #{command}\"",
"if",
"options",
".",
"delete",
"(",
":sudo",
")",
"logger",
".",
"debug",
"\"Executing #{command} using #{description}\"",
"Executer",
".",
"execute",
"command",
",",
"options",
",",
"block",
"end"
] | Executes a Vagrant subcommand using this instance
* subcommand: Vagrant subcommand to run (:up, :status, etc.)
* arguments: Arguments to pass to the subcommand (optional)
* options: If the last argument is a Hash, it will be used
as a hash of options. A list of valid options is
below. Any options provided that aren't in the
list of valid options will get passed through to
Derelict::Executer.execute.
Valid option keys:
* sudo: Whether to run the command as root, or not
(defaults to false)
* block: Passed through to Derelict::Executer.execute | [
"Executes",
"a",
"Vagrant",
"subcommand",
"using",
"this",
"instance"
] | c9d70f04562280a34083dd060b0e4099e6f32d8d | https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/instance.rb#L70-L76 | train |
bradfeehan/derelict | lib/derelict/instance.rb | Derelict.Instance.command | def command(subcommand, *arguments)
args = [vagrant, subcommand.to_s, arguments].flatten
args.map {|a| Shellwords.escape a }.join(' ').tap do |command|
logger.debug "Generated command '#{command}' from " +
"subcommand '#{subcommand.to_s}' with arguments " +
arguments.inspect
end
end | ruby | def command(subcommand, *arguments)
args = [vagrant, subcommand.to_s, arguments].flatten
args.map {|a| Shellwords.escape a }.join(' ').tap do |command|
logger.debug "Generated command '#{command}' from " +
"subcommand '#{subcommand.to_s}' with arguments " +
arguments.inspect
end
end | [
"def",
"command",
"(",
"subcommand",
",",
"*",
"arguments",
")",
"args",
"=",
"[",
"vagrant",
",",
"subcommand",
".",
"to_s",
",",
"arguments",
"]",
".",
"flatten",
"args",
".",
"map",
"{",
"|",
"a",
"|",
"Shellwords",
".",
"escape",
"a",
"}",
".",
"join",
"(",
"' '",
")",
".",
"tap",
"do",
"|",
"command",
"|",
"logger",
".",
"debug",
"\"Generated command '#{command}' from \"",
"+",
"\"subcommand '#{subcommand.to_s}' with arguments \"",
"+",
"arguments",
".",
"inspect",
"end",
"end"
] | Constructs the command to execute a Vagrant subcommand
* subcommand: Vagrant subcommand to run (:up, :status, etc.)
* arguments: Arguments to pass to the subcommand (optional) | [
"Constructs",
"the",
"command",
"to",
"execute",
"a",
"Vagrant",
"subcommand"
] | c9d70f04562280a34083dd060b0e4099e6f32d8d | https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/instance.rb#L138-L145 | train |
redding/deas | lib/deas/show_exceptions.rb | Deas.ShowExceptions.call! | def call!(env)
status, headers, body = @app.call(env)
if error = env['deas.error']
error_body = Body.new(error)
headers['Content-Length'] = error_body.size.to_s
headers['Content-Type'] = error_body.mime_type.to_s
body = [error_body.content]
end
[status, headers, body]
end | ruby | def call!(env)
status, headers, body = @app.call(env)
if error = env['deas.error']
error_body = Body.new(error)
headers['Content-Length'] = error_body.size.to_s
headers['Content-Type'] = error_body.mime_type.to_s
body = [error_body.content]
end
[status, headers, body]
end | [
"def",
"call!",
"(",
"env",
")",
"status",
",",
"headers",
",",
"body",
"=",
"@app",
".",
"call",
"(",
"env",
")",
"if",
"error",
"=",
"env",
"[",
"'deas.error'",
"]",
"error_body",
"=",
"Body",
".",
"new",
"(",
"error",
")",
"headers",
"[",
"'Content-Length'",
"]",
"=",
"error_body",
".",
"size",
".",
"to_s",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"error_body",
".",
"mime_type",
".",
"to_s",
"body",
"=",
"[",
"error_body",
".",
"content",
"]",
"end",
"[",
"status",
",",
"headers",
",",
"body",
"]",
"end"
] | The real Rack call interface. | [
"The",
"real",
"Rack",
"call",
"interface",
"."
] | 865dbfa210a10f974552c2b92325306d98755283 | https://github.com/redding/deas/blob/865dbfa210a10f974552c2b92325306d98755283/lib/deas/show_exceptions.rb#L24-L34 | train |
ChaseLEngel/HelpDeskAPI | lib/helpdeskapi.rb | HelpDeskAPI.Client.sign_in | def sign_in
# Contact sign in page to set cookies.
begin
sign_in_res = RestClient.get(Endpoints::SIGN_IN)
rescue RestClient::ExceptionWithResponse => error
fail HelpDeskAPI::Exceptions.SignInError, "Error contacting #{Endpoints::SIGN_IN}: #{error}"
end
# Parse authenticity_token from sign in form.
page = Nokogiri::HTML(sign_in_res)
HelpDeskAPI::Authentication.authenticity_token = page.css('form').css('input')[1]['value']
unless HelpDeskAPI::Authentication.authenticity_token
fail HelpDeskAPI::Exceptions.AuthenticityTokenError, 'Error parsing authenticity_token: Token not found.'
end
# Parse sign_in HTML for csrf-token
page.css('meta').each do |tag|
HelpDeskAPI::Authentication.csrf_token = tag['content'] if tag['name'] == 'csrf-token'
end
unless HelpDeskAPI::Authentication.csrf_token
fail HelpDeskAPI::Exceptions.CsrfTokenError, 'No csrf-token found'
end
# Set cookies for later requests
HelpDeskAPI::Authentication.cookies = sign_in_res.cookies
# Simulate sign in form submit button.
body = {
'authenticity_token': HelpDeskAPI::Authentication.authenticity_token,
'user[email_address]': HelpDeskAPI::Authentication.username,
'user[password]': HelpDeskAPI::Authentication.password
}
RestClient.post(Endpoints::SESSIONS, body, {:cookies => HelpDeskAPI::Authentication.cookies}) do |response, request, result, &block|
# Response should be a 302 redirect from /sessions
if Request::responseError?(response)
fail HelpDeskAPI::Exceptions.SessionsError, "Error contacting #{Endpoints::SESSIONS}: #{error}"
end
# Update cookies just incase
HelpDeskAPI::Authentication.cookies = response.cookies
end
end | ruby | def sign_in
# Contact sign in page to set cookies.
begin
sign_in_res = RestClient.get(Endpoints::SIGN_IN)
rescue RestClient::ExceptionWithResponse => error
fail HelpDeskAPI::Exceptions.SignInError, "Error contacting #{Endpoints::SIGN_IN}: #{error}"
end
# Parse authenticity_token from sign in form.
page = Nokogiri::HTML(sign_in_res)
HelpDeskAPI::Authentication.authenticity_token = page.css('form').css('input')[1]['value']
unless HelpDeskAPI::Authentication.authenticity_token
fail HelpDeskAPI::Exceptions.AuthenticityTokenError, 'Error parsing authenticity_token: Token not found.'
end
# Parse sign_in HTML for csrf-token
page.css('meta').each do |tag|
HelpDeskAPI::Authentication.csrf_token = tag['content'] if tag['name'] == 'csrf-token'
end
unless HelpDeskAPI::Authentication.csrf_token
fail HelpDeskAPI::Exceptions.CsrfTokenError, 'No csrf-token found'
end
# Set cookies for later requests
HelpDeskAPI::Authentication.cookies = sign_in_res.cookies
# Simulate sign in form submit button.
body = {
'authenticity_token': HelpDeskAPI::Authentication.authenticity_token,
'user[email_address]': HelpDeskAPI::Authentication.username,
'user[password]': HelpDeskAPI::Authentication.password
}
RestClient.post(Endpoints::SESSIONS, body, {:cookies => HelpDeskAPI::Authentication.cookies}) do |response, request, result, &block|
# Response should be a 302 redirect from /sessions
if Request::responseError?(response)
fail HelpDeskAPI::Exceptions.SessionsError, "Error contacting #{Endpoints::SESSIONS}: #{error}"
end
# Update cookies just incase
HelpDeskAPI::Authentication.cookies = response.cookies
end
end | [
"def",
"sign_in",
"# Contact sign in page to set cookies.",
"begin",
"sign_in_res",
"=",
"RestClient",
".",
"get",
"(",
"Endpoints",
"::",
"SIGN_IN",
")",
"rescue",
"RestClient",
"::",
"ExceptionWithResponse",
"=>",
"error",
"fail",
"HelpDeskAPI",
"::",
"Exceptions",
".",
"SignInError",
",",
"\"Error contacting #{Endpoints::SIGN_IN}: #{error}\"",
"end",
"# Parse authenticity_token from sign in form.",
"page",
"=",
"Nokogiri",
"::",
"HTML",
"(",
"sign_in_res",
")",
"HelpDeskAPI",
"::",
"Authentication",
".",
"authenticity_token",
"=",
"page",
".",
"css",
"(",
"'form'",
")",
".",
"css",
"(",
"'input'",
")",
"[",
"1",
"]",
"[",
"'value'",
"]",
"unless",
"HelpDeskAPI",
"::",
"Authentication",
".",
"authenticity_token",
"fail",
"HelpDeskAPI",
"::",
"Exceptions",
".",
"AuthenticityTokenError",
",",
"'Error parsing authenticity_token: Token not found.'",
"end",
"# Parse sign_in HTML for csrf-token",
"page",
".",
"css",
"(",
"'meta'",
")",
".",
"each",
"do",
"|",
"tag",
"|",
"HelpDeskAPI",
"::",
"Authentication",
".",
"csrf_token",
"=",
"tag",
"[",
"'content'",
"]",
"if",
"tag",
"[",
"'name'",
"]",
"==",
"'csrf-token'",
"end",
"unless",
"HelpDeskAPI",
"::",
"Authentication",
".",
"csrf_token",
"fail",
"HelpDeskAPI",
"::",
"Exceptions",
".",
"CsrfTokenError",
",",
"'No csrf-token found'",
"end",
"# Set cookies for later requests",
"HelpDeskAPI",
"::",
"Authentication",
".",
"cookies",
"=",
"sign_in_res",
".",
"cookies",
"# Simulate sign in form submit button.",
"body",
"=",
"{",
"'authenticity_token'",
":",
"HelpDeskAPI",
"::",
"Authentication",
".",
"authenticity_token",
",",
"'user[email_address]'",
":",
"HelpDeskAPI",
"::",
"Authentication",
".",
"username",
",",
"'user[password]'",
":",
"HelpDeskAPI",
"::",
"Authentication",
".",
"password",
"}",
"RestClient",
".",
"post",
"(",
"Endpoints",
"::",
"SESSIONS",
",",
"body",
",",
"{",
":cookies",
"=>",
"HelpDeskAPI",
"::",
"Authentication",
".",
"cookies",
"}",
")",
"do",
"|",
"response",
",",
"request",
",",
"result",
",",
"&",
"block",
"|",
"# Response should be a 302 redirect from /sessions",
"if",
"Request",
"::",
"responseError?",
"(",
"response",
")",
"fail",
"HelpDeskAPI",
"::",
"Exceptions",
".",
"SessionsError",
",",
"\"Error contacting #{Endpoints::SESSIONS}: #{error}\"",
"end",
"# Update cookies just incase",
"HelpDeskAPI",
"::",
"Authentication",
".",
"cookies",
"=",
"response",
".",
"cookies",
"end",
"end"
] | Authenicate user and set cookies.
This will be called automatically on endpoint request. | [
"Authenicate",
"user",
"and",
"set",
"cookies",
".",
"This",
"will",
"be",
"called",
"automatically",
"on",
"endpoint",
"request",
"."
] | d243cced2bb121d30b06e4fed7f02da0d333783a | https://github.com/ChaseLEngel/HelpDeskAPI/blob/d243cced2bb121d30b06e4fed7f02da0d333783a/lib/helpdeskapi.rb#L27-L66 | train |
celldee/ffi-rxs | lib/ffi-rxs/message.rb | XS.Message.copy_in_bytes | def copy_in_bytes bytes, len
data_buffer = LibC.malloc len
# writes the exact number of bytes, no null byte to terminate string
data_buffer.write_string bytes, len
# use libC to call free on the data buffer; earlier versions used an
# FFI::Function here that called back into Ruby, but Rubinius won't
# support that and there are issues with the other runtimes too
LibXS.xs_msg_init_data @pointer, data_buffer, len, LibC::Free, nil
end | ruby | def copy_in_bytes bytes, len
data_buffer = LibC.malloc len
# writes the exact number of bytes, no null byte to terminate string
data_buffer.write_string bytes, len
# use libC to call free on the data buffer; earlier versions used an
# FFI::Function here that called back into Ruby, but Rubinius won't
# support that and there are issues with the other runtimes too
LibXS.xs_msg_init_data @pointer, data_buffer, len, LibC::Free, nil
end | [
"def",
"copy_in_bytes",
"bytes",
",",
"len",
"data_buffer",
"=",
"LibC",
".",
"malloc",
"len",
"# writes the exact number of bytes, no null byte to terminate string",
"data_buffer",
".",
"write_string",
"bytes",
",",
"len",
"# use libC to call free on the data buffer; earlier versions used an",
"# FFI::Function here that called back into Ruby, but Rubinius won't ",
"# support that and there are issues with the other runtimes too",
"LibXS",
".",
"xs_msg_init_data",
"@pointer",
",",
"data_buffer",
",",
"len",
",",
"LibC",
"::",
"Free",
",",
"nil",
"end"
] | Makes a copy of +len+ bytes from the ruby string +bytes+. Library
handles deallocation of the native memory buffer.
Can only be initialized via #copy_in_string or #copy_in_bytes once.
@param bytes
@param length | [
"Makes",
"a",
"copy",
"of",
"+",
"len",
"+",
"bytes",
"from",
"the",
"ruby",
"string",
"+",
"bytes",
"+",
".",
"Library",
"handles",
"deallocation",
"of",
"the",
"native",
"memory",
"buffer",
"."
] | 95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e | https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/message.rb#L135-L144 | train |
mediasp/confuse | lib/confuse/config.rb | Confuse.Config.check | def check
@definition.namespaces.each do |(namespace, ns)|
ns.items.each do |key, _|
lookup(namespace, key)
end
end
end | ruby | def check
@definition.namespaces.each do |(namespace, ns)|
ns.items.each do |key, _|
lookup(namespace, key)
end
end
end | [
"def",
"check",
"@definition",
".",
"namespaces",
".",
"each",
"do",
"|",
"(",
"namespace",
",",
"ns",
")",
"|",
"ns",
".",
"items",
".",
"each",
"do",
"|",
"key",
",",
"_",
"|",
"lookup",
"(",
"namespace",
",",
"key",
")",
"end",
"end",
"end"
] | check items have a value. Will raise Undefined error if a required item
has no value. | [
"check",
"items",
"have",
"a",
"value",
".",
"Will",
"raise",
"Undefined",
"error",
"if",
"a",
"required",
"item",
"has",
"no",
"value",
"."
] | 7e0e976d9461cd794b222305a24fa44946d6a9d3 | https://github.com/mediasp/confuse/blob/7e0e976d9461cd794b222305a24fa44946d6a9d3/lib/confuse/config.rb#L35-L41 | train |
mccraigmccraig/rsxml | lib/rsxml/util.rb | Rsxml.Util.check_opts | def check_opts(constraints, opts)
opts ||= {}
opts.each{|k,v| raise "opt not permitted: #{k.inspect}" if !constraints.has_key?(k)}
Hash[constraints.map do |k,constraint|
if opts.has_key?(k)
v = opts[k]
if constraint.is_a?(Array)
raise "unknown value for opt #{k.inspect}: #{v.inspect}. permitted values are: #{constraint.inspect}" if !constraint.include?(v)
[k,v]
elsif constraint.is_a?(Hash)
raise "opt #{k.inspect} must be a Hash" if !v.is_a?(Hash)
[k,check_opts(constraint, v || {})]
else
[k,v]
end
end
end]
end | ruby | def check_opts(constraints, opts)
opts ||= {}
opts.each{|k,v| raise "opt not permitted: #{k.inspect}" if !constraints.has_key?(k)}
Hash[constraints.map do |k,constraint|
if opts.has_key?(k)
v = opts[k]
if constraint.is_a?(Array)
raise "unknown value for opt #{k.inspect}: #{v.inspect}. permitted values are: #{constraint.inspect}" if !constraint.include?(v)
[k,v]
elsif constraint.is_a?(Hash)
raise "opt #{k.inspect} must be a Hash" if !v.is_a?(Hash)
[k,check_opts(constraint, v || {})]
else
[k,v]
end
end
end]
end | [
"def",
"check_opts",
"(",
"constraints",
",",
"opts",
")",
"opts",
"||=",
"{",
"}",
"opts",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"raise",
"\"opt not permitted: #{k.inspect}\"",
"if",
"!",
"constraints",
".",
"has_key?",
"(",
"k",
")",
"}",
"Hash",
"[",
"constraints",
".",
"map",
"do",
"|",
"k",
",",
"constraint",
"|",
"if",
"opts",
".",
"has_key?",
"(",
"k",
")",
"v",
"=",
"opts",
"[",
"k",
"]",
"if",
"constraint",
".",
"is_a?",
"(",
"Array",
")",
"raise",
"\"unknown value for opt #{k.inspect}: #{v.inspect}. permitted values are: #{constraint.inspect}\"",
"if",
"!",
"constraint",
".",
"include?",
"(",
"v",
")",
"[",
"k",
",",
"v",
"]",
"elsif",
"constraint",
".",
"is_a?",
"(",
"Hash",
")",
"raise",
"\"opt #{k.inspect} must be a Hash\"",
"if",
"!",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"[",
"k",
",",
"check_opts",
"(",
"constraint",
",",
"v",
"||",
"{",
"}",
")",
"]",
"else",
"[",
"k",
",",
"v",
"]",
"end",
"end",
"end",
"]",
"end"
] | simple option checking, with value constraints and sub-hash checking | [
"simple",
"option",
"checking",
"with",
"value",
"constraints",
"and",
"sub",
"-",
"hash",
"checking"
] | 3699c186f01be476a5942d64cd5c39f4d6bbe175 | https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/util.rb#L6-L23 | train |
justfalter/align | lib/align/pairwise_algorithm.rb | Align.PairwiseAlgorithm.max4 | def max4(a,b,c,d)
x = a >= b ? a : b
y = c >= d ? c : d
(x >= y) ? x : y
end | ruby | def max4(a,b,c,d)
x = a >= b ? a : b
y = c >= d ? c : d
(x >= y) ? x : y
end | [
"def",
"max4",
"(",
"a",
",",
"b",
",",
"c",
",",
"d",
")",
"x",
"=",
"a",
">=",
"b",
"?",
"a",
":",
"b",
"y",
"=",
"c",
">=",
"d",
"?",
"c",
":",
"d",
"(",
"x",
">=",
"y",
")",
"?",
"x",
":",
"y",
"end"
] | Returns the max of 4 integers | [
"Returns",
"the",
"max",
"of",
"4",
"integers"
] | e95ac63253e99ee18d66c1e7d9695f5eb80036cf | https://github.com/justfalter/align/blob/e95ac63253e99ee18d66c1e7d9695f5eb80036cf/lib/align/pairwise_algorithm.rb#L24-L28 | train |
yohoushi/multiforecast-client | lib/multiforecast/client.rb | MultiForecast.Client.get_complex | def get_complex(path)
client(path).get_complex(service_name(path), section_name(path), graph_name(path)).tap do |graph|
graph['base_uri'] = client(path).base_uri
graph['path'] = path
end
end | ruby | def get_complex(path)
client(path).get_complex(service_name(path), section_name(path), graph_name(path)).tap do |graph|
graph['base_uri'] = client(path).base_uri
graph['path'] = path
end
end | [
"def",
"get_complex",
"(",
"path",
")",
"client",
"(",
"path",
")",
".",
"get_complex",
"(",
"service_name",
"(",
"path",
")",
",",
"section_name",
"(",
"path",
")",
",",
"graph_name",
"(",
"path",
")",
")",
".",
"tap",
"do",
"|",
"graph",
"|",
"graph",
"[",
"'base_uri'",
"]",
"=",
"client",
"(",
"path",
")",
".",
"base_uri",
"graph",
"[",
"'path'",
"]",
"=",
"path",
"end",
"end"
] | Get a complex graph
@param [String] path
@return [Hash] the graph property
@example
{"number"=>0,
"complex"=>true,
"created_at"=>"2013/05/20 15:08:28",
"service_name"=>"app name",
"section_name"=>"host name",
"id"=>18,
"graph_name"=>"complex graph test",
"data"=>
[{"gmode"=>"gauge", "stack"=>false, "type"=>"AREA", "graph_id"=>218},
{"gmode"=>"gauge", "stack"=>true, "type"=>"AREA", "graph_id"=>217}],
"sumup"=>false,
"description"=>"complex graph test",
"sort"=>10,
"updated_at"=>"2013/05/20 15:08:28"} | [
"Get",
"a",
"complex",
"graph"
] | 0c25f60f9930aeb8837061df025ddbfd8677e74e | https://github.com/yohoushi/multiforecast-client/blob/0c25f60f9930aeb8837061df025ddbfd8677e74e/lib/multiforecast/client.rb#L257-L262 | train |
yohoushi/multiforecast-client | lib/multiforecast/client.rb | MultiForecast.Client.delete_complex | def delete_complex(path)
client(path).delete_complex(service_name(path), section_name(path), graph_name(path))
end | ruby | def delete_complex(path)
client(path).delete_complex(service_name(path), section_name(path), graph_name(path))
end | [
"def",
"delete_complex",
"(",
"path",
")",
"client",
"(",
"path",
")",
".",
"delete_complex",
"(",
"service_name",
"(",
"path",
")",
",",
"section_name",
"(",
"path",
")",
",",
"graph_name",
"(",
"path",
")",
")",
"end"
] | Delete a complex graph
@param [String] path
@return [Hash] error response
@example
{"error"=>0} #=> Success
{"error"=>1} #=> Error | [
"Delete",
"a",
"complex",
"graph"
] | 0c25f60f9930aeb8837061df025ddbfd8677e74e | https://github.com/yohoushi/multiforecast-client/blob/0c25f60f9930aeb8837061df025ddbfd8677e74e/lib/multiforecast/client.rb#L271-L273 | train |
fenton-project/fenton_shell | lib/fenton_shell/certificate.rb | FentonShell.Certificate.certificate_create | def certificate_create(global_options, options)
result = Excon.post(
"#{global_options[:fenton_server_url]}/certificates.json",
body: certificate_json(options),
headers: { 'Content-Type' => 'application/json' }
)
write_client_certificate(
public_key_cert_location(options[:public_key]),
JSON.parse(result.body)['data']['attributes']['certificate']
)
[result.status, JSON.parse(result.body)]
end | ruby | def certificate_create(global_options, options)
result = Excon.post(
"#{global_options[:fenton_server_url]}/certificates.json",
body: certificate_json(options),
headers: { 'Content-Type' => 'application/json' }
)
write_client_certificate(
public_key_cert_location(options[:public_key]),
JSON.parse(result.body)['data']['attributes']['certificate']
)
[result.status, JSON.parse(result.body)]
end | [
"def",
"certificate_create",
"(",
"global_options",
",",
"options",
")",
"result",
"=",
"Excon",
".",
"post",
"(",
"\"#{global_options[:fenton_server_url]}/certificates.json\"",
",",
"body",
":",
"certificate_json",
"(",
"options",
")",
",",
"headers",
":",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"write_client_certificate",
"(",
"public_key_cert_location",
"(",
"options",
"[",
":public_key",
"]",
")",
",",
"JSON",
".",
"parse",
"(",
"result",
".",
"body",
")",
"[",
"'data'",
"]",
"[",
"'attributes'",
"]",
"[",
"'certificate'",
"]",
")",
"[",
"result",
".",
"status",
",",
"JSON",
".",
"parse",
"(",
"result",
".",
"body",
")",
"]",
"end"
] | Sends a post request with json from the command line certificate
@param global_options [Hash] global command line options
@param options [Hash] json fields to send to fenton server
@return [Fixnum] http status code
@return [String] message back from fenton server | [
"Sends",
"a",
"post",
"request",
"with",
"json",
"from",
"the",
"command",
"line",
"certificate"
] | 6e1d76186fa7ee7a3be141afad9361e3a3e0ec91 | https://github.com/fenton-project/fenton_shell/blob/6e1d76186fa7ee7a3be141afad9361e3a3e0ec91/lib/fenton_shell/certificate.rb#L34-L47 | train |
klacointe/has_media | lib/has_media.rb | HasMedia.ClassMethods.set_relations | def set_relations(context, relation)
@contexts ||= {}
@contexts[relation] ||= []
@media_relation_set ||= []
if @contexts[relation].include?(context)
raise Exception.new("You should NOT use same context identifier for several has_one or has_many relation to media")
end
@contexts[relation] << context
return if @media_relation_set.include? self
has_many :media, :through => :media_links, :dependent => :destroy
@media_relation_set << self
end | ruby | def set_relations(context, relation)
@contexts ||= {}
@contexts[relation] ||= []
@media_relation_set ||= []
if @contexts[relation].include?(context)
raise Exception.new("You should NOT use same context identifier for several has_one or has_many relation to media")
end
@contexts[relation] << context
return if @media_relation_set.include? self
has_many :media, :through => :media_links, :dependent => :destroy
@media_relation_set << self
end | [
"def",
"set_relations",
"(",
"context",
",",
"relation",
")",
"@contexts",
"||=",
"{",
"}",
"@contexts",
"[",
"relation",
"]",
"||=",
"[",
"]",
"@media_relation_set",
"||=",
"[",
"]",
"if",
"@contexts",
"[",
"relation",
"]",
".",
"include?",
"(",
"context",
")",
"raise",
"Exception",
".",
"new",
"(",
"\"You should NOT use same context identifier for several has_one or has_many relation to media\"",
")",
"end",
"@contexts",
"[",
"relation",
"]",
"<<",
"context",
"return",
"if",
"@media_relation_set",
".",
"include?",
"self",
"has_many",
":media",
",",
":through",
"=>",
":media_links",
",",
":dependent",
"=>",
":destroy",
"@media_relation_set",
"<<",
"self",
"end"
] | set_relations
add relation on medium if not exists
Also check if a class has a duplicate context
@param [String] context
@param [String] relation type, one of :has_many, :has_one | [
"set_relations",
"add",
"relation",
"on",
"medium",
"if",
"not",
"exists",
"Also",
"check",
"if",
"a",
"class",
"has",
"a",
"duplicate",
"context"
] | a886d36a914d8244f3761455458b9d0226fa22d5 | https://github.com/klacointe/has_media/blob/a886d36a914d8244f3761455458b9d0226fa22d5/lib/has_media.rb#L199-L211 | train |
jellymann/someapi | lib/someapi.rb | Some.API.method_missing | def method_missing meth, *args, &block
meth_s = meth.to_s
if @method && meth_s =~ API_REGEX
if meth_s.end_with?('!')
# `foo! bar' is syntactic sugar for `foo.! bar'
self[meth_s[0...-1]].!(args[0] || {})
else
# chain the method name onto URL path
self[meth_s]
end
else
super
end
end | ruby | def method_missing meth, *args, &block
meth_s = meth.to_s
if @method && meth_s =~ API_REGEX
if meth_s.end_with?('!')
# `foo! bar' is syntactic sugar for `foo.! bar'
self[meth_s[0...-1]].!(args[0] || {})
else
# chain the method name onto URL path
self[meth_s]
end
else
super
end
end | [
"def",
"method_missing",
"meth",
",",
"*",
"args",
",",
"&",
"block",
"meth_s",
"=",
"meth",
".",
"to_s",
"if",
"@method",
"&&",
"meth_s",
"=~",
"API_REGEX",
"if",
"meth_s",
".",
"end_with?",
"(",
"'!'",
")",
"# `foo! bar' is syntactic sugar for `foo.! bar'",
"self",
"[",
"meth_s",
"[",
"0",
"...",
"-",
"1",
"]",
"]",
".",
"!",
"(",
"args",
"[",
"0",
"]",
"||",
"{",
"}",
")",
"else",
"# chain the method name onto URL path",
"self",
"[",
"meth_s",
"]",
"end",
"else",
"super",
"end",
"end"
] | this is where the fun begins... | [
"this",
"is",
"where",
"the",
"fun",
"begins",
"..."
] | 77fc6e72612d30b7da6de0f4b60d971de78667a9 | https://github.com/jellymann/someapi/blob/77fc6e72612d30b7da6de0f4b60d971de78667a9/lib/someapi.rb#L81-L96 | train |
victorgama/xcellus | lib/xcellus.rb | Xcellus.Instance.save | def save(path)
unless path.kind_of? String
raise ArgumentError, 'save expects a string path'
end
Xcellus::_save(@handle, path)
end | ruby | def save(path)
unless path.kind_of? String
raise ArgumentError, 'save expects a string path'
end
Xcellus::_save(@handle, path)
end | [
"def",
"save",
"(",
"path",
")",
"unless",
"path",
".",
"kind_of?",
"String",
"raise",
"ArgumentError",
",",
"'save expects a string path'",
"end",
"Xcellus",
"::",
"_save",
"(",
"@handle",
",",
"path",
")",
"end"
] | Saves the current modifications to the provided path. | [
"Saves",
"the",
"current",
"modifications",
"to",
"the",
"provided",
"path",
"."
] | 6d0ef725ae173a05385e68ca44558d49b12ee1cb | https://github.com/victorgama/xcellus/blob/6d0ef725ae173a05385e68ca44558d49b12ee1cb/lib/xcellus.rb#L116-L122 | train |
samsao/danger-samsao | lib/samsao/helpers.rb | Samsao.Helpers.changelog_modified? | def changelog_modified?(*changelogs)
changelogs = config.changelogs if changelogs.nil? || changelogs.empty?
changelogs.any? { |changelog| git.modified_files.include?(changelog) }
end | ruby | def changelog_modified?(*changelogs)
changelogs = config.changelogs if changelogs.nil? || changelogs.empty?
changelogs.any? { |changelog| git.modified_files.include?(changelog) }
end | [
"def",
"changelog_modified?",
"(",
"*",
"changelogs",
")",
"changelogs",
"=",
"config",
".",
"changelogs",
"if",
"changelogs",
".",
"nil?",
"||",
"changelogs",
".",
"empty?",
"changelogs",
".",
"any?",
"{",
"|",
"changelog",
"|",
"git",
".",
"modified_files",
".",
"include?",
"(",
"changelog",
")",
"}",
"end"
] | Check if any changelog were modified. When the helper receives nothing,
changelogs defined by the config are used.
@return [Bool] True
If any changelogs were modified in this commit | [
"Check",
"if",
"any",
"changelog",
"were",
"modified",
".",
"When",
"the",
"helper",
"receives",
"nothing",
"changelogs",
"defined",
"by",
"the",
"config",
"are",
"used",
"."
] | 59a9d6d87e6c58d5c6aadc96fae99555f7ea297b | https://github.com/samsao/danger-samsao/blob/59a9d6d87e6c58d5c6aadc96fae99555f7ea297b/lib/samsao/helpers.rb#L12-L16 | train |
samsao/danger-samsao | lib/samsao/helpers.rb | Samsao.Helpers.has_app_changes? | def has_app_changes?(*sources)
sources = config.sources if sources.nil? || sources.empty?
sources.any? do |source|
pattern = Samsao::Regexp.from_matcher(source, when_string_pattern_prefix_with: '^')
modified_file?(pattern)
end
end | ruby | def has_app_changes?(*sources)
sources = config.sources if sources.nil? || sources.empty?
sources.any? do |source|
pattern = Samsao::Regexp.from_matcher(source, when_string_pattern_prefix_with: '^')
modified_file?(pattern)
end
end | [
"def",
"has_app_changes?",
"(",
"*",
"sources",
")",
"sources",
"=",
"config",
".",
"sources",
"if",
"sources",
".",
"nil?",
"||",
"sources",
".",
"empty?",
"sources",
".",
"any?",
"do",
"|",
"source",
"|",
"pattern",
"=",
"Samsao",
"::",
"Regexp",
".",
"from_matcher",
"(",
"source",
",",
"when_string_pattern_prefix_with",
":",
"'^'",
")",
"modified_file?",
"(",
"pattern",
")",
"end",
"end"
] | Return true if any source files are in the git modified files list.
@return [Bool] | [
"Return",
"true",
"if",
"any",
"source",
"files",
"are",
"in",
"the",
"git",
"modified",
"files",
"list",
"."
] | 59a9d6d87e6c58d5c6aadc96fae99555f7ea297b | https://github.com/samsao/danger-samsao/blob/59a9d6d87e6c58d5c6aadc96fae99555f7ea297b/lib/samsao/helpers.rb#L63-L71 | train |
samsao/danger-samsao | lib/samsao/helpers.rb | Samsao.Helpers.truncate | def truncate(input, max = 30)
return input if input.nil? || input.length <= max
input[0..max - 1].gsub(/\s\w+\s*$/, '...')
end | ruby | def truncate(input, max = 30)
return input if input.nil? || input.length <= max
input[0..max - 1].gsub(/\s\w+\s*$/, '...')
end | [
"def",
"truncate",
"(",
"input",
",",
"max",
"=",
"30",
")",
"return",
"input",
"if",
"input",
".",
"nil?",
"||",
"input",
".",
"length",
"<=",
"max",
"input",
"[",
"0",
"..",
"max",
"-",
"1",
"]",
".",
"gsub",
"(",
"/",
"\\s",
"\\w",
"\\s",
"/",
",",
"'...'",
")",
"end"
] | Truncate the string received.
@param [String] input
The string to truncate
@param [Number] max (Default: 30)
The max size of the truncated string
@return [String] | [
"Truncate",
"the",
"string",
"received",
"."
] | 59a9d6d87e6c58d5c6aadc96fae99555f7ea297b | https://github.com/samsao/danger-samsao/blob/59a9d6d87e6c58d5c6aadc96fae99555f7ea297b/lib/samsao/helpers.rb#L109-L113 | train |
hannesg/multi_git | lib/multi_git/ref.rb | MultiGit.Ref.resolve | def resolve
@leaf ||= begin
ref = self
loop do
break ref unless ref.target.kind_of? MultiGit::Ref
ref = ref.target
end
end
end | ruby | def resolve
@leaf ||= begin
ref = self
loop do
break ref unless ref.target.kind_of? MultiGit::Ref
ref = ref.target
end
end
end | [
"def",
"resolve",
"@leaf",
"||=",
"begin",
"ref",
"=",
"self",
"loop",
"do",
"break",
"ref",
"unless",
"ref",
".",
"target",
".",
"kind_of?",
"MultiGit",
"::",
"Ref",
"ref",
"=",
"ref",
".",
"target",
"end",
"end",
"end"
] | Resolves symbolic references and returns the final reference.
@return [MultGit::Ref] | [
"Resolves",
"symbolic",
"references",
"and",
"returns",
"the",
"final",
"reference",
"."
] | cb82e66be7d27c3b630610ce3f1385b30811f139 | https://github.com/hannesg/multi_git/blob/cb82e66be7d27c3b630610ce3f1385b30811f139/lib/multi_git/ref.rb#L278-L286 | train |
hannesg/multi_git | lib/multi_git/ref.rb | MultiGit.Ref.commit | def commit(options = {}, &block)
resolve.update(options.fetch(:lock, :optimistic)) do |current|
Commit::Builder.new(current, &block)
end
return reload
end | ruby | def commit(options = {}, &block)
resolve.update(options.fetch(:lock, :optimistic)) do |current|
Commit::Builder.new(current, &block)
end
return reload
end | [
"def",
"commit",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"resolve",
".",
"update",
"(",
"options",
".",
"fetch",
"(",
":lock",
",",
":optimistic",
")",
")",
"do",
"|",
"current",
"|",
"Commit",
"::",
"Builder",
".",
"new",
"(",
"current",
",",
"block",
")",
"end",
"return",
"reload",
"end"
] | Shorthand method to directly create a commit and update the given ref.
@example
# setup:
dir = `mktemp -d`
repository = MultiGit.open(dir, init: true)
# insert a commit:
repository.head.commit do
tree['a_file'] = 'some_content'
end
# check result:
repository.head['a_file'].content #=> eql 'some_content'
# teardown:
`rm -rf #{dir}`
@option options :lock [:optimistic, :pessimistic] How to lock during the commit.
@yield
@return [Ref] | [
"Shorthand",
"method",
"to",
"directly",
"create",
"a",
"commit",
"and",
"update",
"the",
"given",
"ref",
"."
] | cb82e66be7d27c3b630610ce3f1385b30811f139 | https://github.com/hannesg/multi_git/blob/cb82e66be7d27c3b630610ce3f1385b30811f139/lib/multi_git/ref.rb#L404-L409 | train |
pwnall/authpwn_rails | lib/authpwn_rails/session.rb | Authpwn.ControllerInstanceMethods.set_session_current_user | def set_session_current_user(user)
self.current_user = user
# Try to reuse existing sessions.
if session[:authpwn_suid]
token = Tokens::SessionUid.with_code(session[:authpwn_suid]).first
if token
if token.user == user
token.touch
return user
else
token.destroy
end
end
end
if user
session[:authpwn_suid] = Tokens::SessionUid.random_for(user,
request.remote_ip, request.user_agent || 'N/A').suid
else
session.delete :authpwn_suid
end
end | ruby | def set_session_current_user(user)
self.current_user = user
# Try to reuse existing sessions.
if session[:authpwn_suid]
token = Tokens::SessionUid.with_code(session[:authpwn_suid]).first
if token
if token.user == user
token.touch
return user
else
token.destroy
end
end
end
if user
session[:authpwn_suid] = Tokens::SessionUid.random_for(user,
request.remote_ip, request.user_agent || 'N/A').suid
else
session.delete :authpwn_suid
end
end | [
"def",
"set_session_current_user",
"(",
"user",
")",
"self",
".",
"current_user",
"=",
"user",
"# Try to reuse existing sessions.",
"if",
"session",
"[",
":authpwn_suid",
"]",
"token",
"=",
"Tokens",
"::",
"SessionUid",
".",
"with_code",
"(",
"session",
"[",
":authpwn_suid",
"]",
")",
".",
"first",
"if",
"token",
"if",
"token",
".",
"user",
"==",
"user",
"token",
".",
"touch",
"return",
"user",
"else",
"token",
".",
"destroy",
"end",
"end",
"end",
"if",
"user",
"session",
"[",
":authpwn_suid",
"]",
"=",
"Tokens",
"::",
"SessionUid",
".",
"random_for",
"(",
"user",
",",
"request",
".",
"remote_ip",
",",
"request",
".",
"user_agent",
"||",
"'N/A'",
")",
".",
"suid",
"else",
"session",
".",
"delete",
":authpwn_suid",
"end",
"end"
] | Sets up the session so that it will authenticate the given user. | [
"Sets",
"up",
"the",
"session",
"so",
"that",
"it",
"will",
"authenticate",
"the",
"given",
"user",
"."
] | de3bd612a00025e8dc8296a73abe3acba948db17 | https://github.com/pwnall/authpwn_rails/blob/de3bd612a00025e8dc8296a73abe3acba948db17/lib/authpwn_rails/session.rb#L41-L61 | train |
pwnall/authpwn_rails | lib/authpwn_rails/session.rb | Authpwn.ControllerInstanceMethods.authenticate_using_session | def authenticate_using_session
return if current_user
session_uid = session[:authpwn_suid]
user = session_uid && Tokens::SessionUid.authenticate(session_uid)
self.current_user = user if user && !user.instance_of?(Symbol)
end | ruby | def authenticate_using_session
return if current_user
session_uid = session[:authpwn_suid]
user = session_uid && Tokens::SessionUid.authenticate(session_uid)
self.current_user = user if user && !user.instance_of?(Symbol)
end | [
"def",
"authenticate_using_session",
"return",
"if",
"current_user",
"session_uid",
"=",
"session",
"[",
":authpwn_suid",
"]",
"user",
"=",
"session_uid",
"&&",
"Tokens",
"::",
"SessionUid",
".",
"authenticate",
"(",
"session_uid",
")",
"self",
".",
"current_user",
"=",
"user",
"if",
"user",
"&&",
"!",
"user",
".",
"instance_of?",
"(",
"Symbol",
")",
"end"
] | The before_action that implements authenticates_using_session.
If your ApplicationController contains authenticates_using_session, you
can opt out in individual controllers using skip_before_action.
skip_before_action :authenticate_using_session | [
"The",
"before_action",
"that",
"implements",
"authenticates_using_session",
"."
] | de3bd612a00025e8dc8296a73abe3acba948db17 | https://github.com/pwnall/authpwn_rails/blob/de3bd612a00025e8dc8296a73abe3acba948db17/lib/authpwn_rails/session.rb#L69-L74 | train |
vjoel/tkar | lib/tkar/canvas.rb | Tkar.Canvas.del | def del tkar_id
tkaroid = @objects[tkar_id]
if tkaroid
if @follow_id == tkar_id
follow nil
end
delete tkaroid.tag
@objects.delete tkar_id
@changed.delete tkar_id
get_objects_by_layer(tkaroid.layer).delete tkaroid
end
end | ruby | def del tkar_id
tkaroid = @objects[tkar_id]
if tkaroid
if @follow_id == tkar_id
follow nil
end
delete tkaroid.tag
@objects.delete tkar_id
@changed.delete tkar_id
get_objects_by_layer(tkaroid.layer).delete tkaroid
end
end | [
"def",
"del",
"tkar_id",
"tkaroid",
"=",
"@objects",
"[",
"tkar_id",
"]",
"if",
"tkaroid",
"if",
"@follow_id",
"==",
"tkar_id",
"follow",
"nil",
"end",
"delete",
"tkaroid",
".",
"tag",
"@objects",
".",
"delete",
"tkar_id",
"@changed",
".",
"delete",
"tkar_id",
"get_objects_by_layer",
"(",
"tkaroid",
".",
"layer",
")",
".",
"delete",
"tkaroid",
"end",
"end"
] | Not "delete"! That already exists in tk. | [
"Not",
"delete",
"!",
"That",
"already",
"exists",
"in",
"tk",
"."
] | 4c446bdcc028c0ec2fb858ea882717bd9908d9d0 | https://github.com/vjoel/tkar/blob/4c446bdcc028c0ec2fb858ea882717bd9908d9d0/lib/tkar/canvas.rb#L193-L204 | train |
ryanuber/ruby-aptly | lib/aptly/repo.rb | Aptly.Repo.add | def add path, kwargs={}
remove_files = kwargs.arg :remove_files, false
cmd = 'aptly repo add'
cmd += ' -remove-files' if remove_files
cmd += " #{@name.quote} #{path}"
Aptly::runcmd cmd
end | ruby | def add path, kwargs={}
remove_files = kwargs.arg :remove_files, false
cmd = 'aptly repo add'
cmd += ' -remove-files' if remove_files
cmd += " #{@name.quote} #{path}"
Aptly::runcmd cmd
end | [
"def",
"add",
"path",
",",
"kwargs",
"=",
"{",
"}",
"remove_files",
"=",
"kwargs",
".",
"arg",
":remove_files",
",",
"false",
"cmd",
"=",
"'aptly repo add'",
"cmd",
"+=",
"' -remove-files'",
"if",
"remove_files",
"cmd",
"+=",
"\" #{@name.quote} #{path}\"",
"Aptly",
"::",
"runcmd",
"cmd",
"end"
] | Add debian packages to a repo
== Parameters:
path::
The path to the file or directory source
remove_files::
When true, deletes source after import | [
"Add",
"debian",
"packages",
"to",
"a",
"repo"
] | 9581c38da30119d6a61b7ddac6334ab17fc67164 | https://github.com/ryanuber/ruby-aptly/blob/9581c38da30119d6a61b7ddac6334ab17fc67164/lib/aptly/repo.rb#L125-L133 | train |
ryanuber/ruby-aptly | lib/aptly/repo.rb | Aptly.Repo.import | def import from_mirror, kwargs={}
deps = kwargs.arg :deps, false
packages = kwargs.arg :packages, []
if packages.length == 0
raise AptlyError.new '1 or more packages are required'
end
cmd = 'aptly repo import'
cmd += ' -with-deps' if deps
cmd += " #{from_mirror.quote} #{@name.quote}"
packages.each {|p| cmd += " #{p.quote}"}
Aptly::runcmd cmd
end | ruby | def import from_mirror, kwargs={}
deps = kwargs.arg :deps, false
packages = kwargs.arg :packages, []
if packages.length == 0
raise AptlyError.new '1 or more packages are required'
end
cmd = 'aptly repo import'
cmd += ' -with-deps' if deps
cmd += " #{from_mirror.quote} #{@name.quote}"
packages.each {|p| cmd += " #{p.quote}"}
Aptly::runcmd cmd
end | [
"def",
"import",
"from_mirror",
",",
"kwargs",
"=",
"{",
"}",
"deps",
"=",
"kwargs",
".",
"arg",
":deps",
",",
"false",
"packages",
"=",
"kwargs",
".",
"arg",
":packages",
",",
"[",
"]",
"if",
"packages",
".",
"length",
"==",
"0",
"raise",
"AptlyError",
".",
"new",
"'1 or more packages are required'",
"end",
"cmd",
"=",
"'aptly repo import'",
"cmd",
"+=",
"' -with-deps'",
"if",
"deps",
"cmd",
"+=",
"\" #{from_mirror.quote} #{@name.quote}\"",
"packages",
".",
"each",
"{",
"|",
"p",
"|",
"cmd",
"+=",
"\" #{p.quote}\"",
"}",
"Aptly",
"::",
"runcmd",
"cmd",
"end"
] | Imports package resources from existing mirrors
== Parameters:
from_mirror::
The name of the mirror to import from
packages::
A list of debian pkg_spec strings (e.g. "libc6 (>= 2.7-1)")
deps::
When true, follows package dependencies and adds them | [
"Imports",
"package",
"resources",
"from",
"existing",
"mirrors"
] | 9581c38da30119d6a61b7ddac6334ab17fc67164 | https://github.com/ryanuber/ruby-aptly/blob/9581c38da30119d6a61b7ddac6334ab17fc67164/lib/aptly/repo.rb#L145-L159 | train |
ryanuber/ruby-aptly | lib/aptly/repo.rb | Aptly.Repo.copy | def copy from_repo, to_repo, kwargs={}
deps = kwargs.arg :deps, false
packages = kwargs.arg :packages, []
if packages.length == 0
raise AptlyError.new '1 or more packages are required'
end
cmd = 'aptly repo copy'
cmd += ' -with-deps' if deps
cmd += " #{from_repo.quote} #{to_repo.quote}"
packages.each {|p| cmd += " #{p.quote}"}
Aptly::runcmd cmd
end | ruby | def copy from_repo, to_repo, kwargs={}
deps = kwargs.arg :deps, false
packages = kwargs.arg :packages, []
if packages.length == 0
raise AptlyError.new '1 or more packages are required'
end
cmd = 'aptly repo copy'
cmd += ' -with-deps' if deps
cmd += " #{from_repo.quote} #{to_repo.quote}"
packages.each {|p| cmd += " #{p.quote}"}
Aptly::runcmd cmd
end | [
"def",
"copy",
"from_repo",
",",
"to_repo",
",",
"kwargs",
"=",
"{",
"}",
"deps",
"=",
"kwargs",
".",
"arg",
":deps",
",",
"false",
"packages",
"=",
"kwargs",
".",
"arg",
":packages",
",",
"[",
"]",
"if",
"packages",
".",
"length",
"==",
"0",
"raise",
"AptlyError",
".",
"new",
"'1 or more packages are required'",
"end",
"cmd",
"=",
"'aptly repo copy'",
"cmd",
"+=",
"' -with-deps'",
"if",
"deps",
"cmd",
"+=",
"\" #{from_repo.quote} #{to_repo.quote}\"",
"packages",
".",
"each",
"{",
"|",
"p",
"|",
"cmd",
"+=",
"\" #{p.quote}\"",
"}",
"Aptly",
"::",
"runcmd",
"cmd",
"end"
] | Copy package resources from one repository to another
== Parameters:
from_repo::
The source repository name
to_repo::
The destination repository name
packages::
A list of debian pkg_spec strings
deps::
When true, follow deps and copy them | [
"Copy",
"package",
"resources",
"from",
"one",
"repository",
"to",
"another"
] | 9581c38da30119d6a61b7ddac6334ab17fc67164 | https://github.com/ryanuber/ruby-aptly/blob/9581c38da30119d6a61b7ddac6334ab17fc67164/lib/aptly/repo.rb#L173-L187 | train |
ondra-m/google_api | lib/google_api/session/session.rb | GoogleApi.Session.login | def login(code = nil)
@client = Google::APIClient.new
@client.authorization.client_id = c('client_id')
@client.authorization.client_secret = c('client_secret')
@client.authorization.scope = @scope
@client.authorization.redirect_uri = c('redirect_uri')
@api = @client.discovered_api(@name_api, @version_api)
unless code
return @client.authorization.authorization_uri.to_s
end
begin
@client.authorization.code = code
@client.authorization.fetch_access_token!
rescue
return false
end
return true
end | ruby | def login(code = nil)
@client = Google::APIClient.new
@client.authorization.client_id = c('client_id')
@client.authorization.client_secret = c('client_secret')
@client.authorization.scope = @scope
@client.authorization.redirect_uri = c('redirect_uri')
@api = @client.discovered_api(@name_api, @version_api)
unless code
return @client.authorization.authorization_uri.to_s
end
begin
@client.authorization.code = code
@client.authorization.fetch_access_token!
rescue
return false
end
return true
end | [
"def",
"login",
"(",
"code",
"=",
"nil",
")",
"@client",
"=",
"Google",
"::",
"APIClient",
".",
"new",
"@client",
".",
"authorization",
".",
"client_id",
"=",
"c",
"(",
"'client_id'",
")",
"@client",
".",
"authorization",
".",
"client_secret",
"=",
"c",
"(",
"'client_secret'",
")",
"@client",
".",
"authorization",
".",
"scope",
"=",
"@scope",
"@client",
".",
"authorization",
".",
"redirect_uri",
"=",
"c",
"(",
"'redirect_uri'",
")",
"@api",
"=",
"@client",
".",
"discovered_api",
"(",
"@name_api",
",",
"@version_api",
")",
"unless",
"code",
"return",
"@client",
".",
"authorization",
".",
"authorization_uri",
".",
"to_s",
"end",
"begin",
"@client",
".",
"authorization",
".",
"code",
"=",
"code",
"@client",
".",
"authorization",
".",
"fetch_access_token!",
"rescue",
"return",
"false",
"end",
"return",
"true",
"end"
] | Classic oauth 2 login
login() -> return autorization url
login(code) -> try login, return true false | [
"Classic",
"oauth",
"2",
"login"
] | 258ac9958f47e8d4151e944910d649c2b372828f | https://github.com/ondra-m/google_api/blob/258ac9958f47e8d4151e944910d649c2b372828f/lib/google_api/session/session.rb#L63-L84 | train |
ondra-m/google_api | lib/google_api/session/session.rb | GoogleApi.Session.login_by_line | def login_by_line(server = 'http://localhost/oauth2callback', port = 0)
begin
require "launchy" # open browser
rescue
raise GoogleApi::RequireError, "You don't have launchy gem. Firt install it: gem install launchy."
end
require "socket" # make tcp server
require "uri" # parse uri
uri = URI(server)
# Start webserver.
webserver = TCPServer.new(uri.host, port)
# By default port is 0. It means that TCPServer will get first free port.
# Port is required for redirect_uri.
uri.port = webserver.addr[1]
# Add redirect_uri for google oauth 2 callback.
_config.send(@config_name).redirect_uri = uri.to_s
# Open browser.
Launchy.open(login)
# Wait for new session.
session = webserver.accept
# Parse header for query.
request = session.gets.gsub(/GET\ \//, '').gsub(/\ HTTP.*/, '')
request = Hash[URI.decode_www_form(URI(request).query)]
# Failure login
to_return = false
message = "You have not been logged. Please try again."
if login(request['code'])
message = "You have been successfully logged. Now you can close the browser."
to_return = true
end
session.write(message)
# Close session and webserver.
session.close
return to_return
end | ruby | def login_by_line(server = 'http://localhost/oauth2callback', port = 0)
begin
require "launchy" # open browser
rescue
raise GoogleApi::RequireError, "You don't have launchy gem. Firt install it: gem install launchy."
end
require "socket" # make tcp server
require "uri" # parse uri
uri = URI(server)
# Start webserver.
webserver = TCPServer.new(uri.host, port)
# By default port is 0. It means that TCPServer will get first free port.
# Port is required for redirect_uri.
uri.port = webserver.addr[1]
# Add redirect_uri for google oauth 2 callback.
_config.send(@config_name).redirect_uri = uri.to_s
# Open browser.
Launchy.open(login)
# Wait for new session.
session = webserver.accept
# Parse header for query.
request = session.gets.gsub(/GET\ \//, '').gsub(/\ HTTP.*/, '')
request = Hash[URI.decode_www_form(URI(request).query)]
# Failure login
to_return = false
message = "You have not been logged. Please try again."
if login(request['code'])
message = "You have been successfully logged. Now you can close the browser."
to_return = true
end
session.write(message)
# Close session and webserver.
session.close
return to_return
end | [
"def",
"login_by_line",
"(",
"server",
"=",
"'http://localhost/oauth2callback'",
",",
"port",
"=",
"0",
")",
"begin",
"require",
"\"launchy\"",
"# open browser",
"rescue",
"raise",
"GoogleApi",
"::",
"RequireError",
",",
"\"You don't have launchy gem. Firt install it: gem install launchy.\"",
"end",
"require",
"\"socket\"",
"# make tcp server ",
"require",
"\"uri\"",
"# parse uri",
"uri",
"=",
"URI",
"(",
"server",
")",
"# Start webserver.",
"webserver",
"=",
"TCPServer",
".",
"new",
"(",
"uri",
".",
"host",
",",
"port",
")",
"# By default port is 0. It means that TCPServer will get first free port.",
"# Port is required for redirect_uri.",
"uri",
".",
"port",
"=",
"webserver",
".",
"addr",
"[",
"1",
"]",
"# Add redirect_uri for google oauth 2 callback.",
"_config",
".",
"send",
"(",
"@config_name",
")",
".",
"redirect_uri",
"=",
"uri",
".",
"to_s",
"# Open browser.",
"Launchy",
".",
"open",
"(",
"login",
")",
"# Wait for new session.",
"session",
"=",
"webserver",
".",
"accept",
"# Parse header for query.",
"request",
"=",
"session",
".",
"gets",
".",
"gsub",
"(",
"/",
"\\ ",
"\\/",
"/",
",",
"''",
")",
".",
"gsub",
"(",
"/",
"\\ ",
"/",
",",
"''",
")",
"request",
"=",
"Hash",
"[",
"URI",
".",
"decode_www_form",
"(",
"URI",
"(",
"request",
")",
".",
"query",
")",
"]",
"# Failure login",
"to_return",
"=",
"false",
"message",
"=",
"\"You have not been logged. Please try again.\"",
"if",
"login",
"(",
"request",
"[",
"'code'",
"]",
")",
"message",
"=",
"\"You have been successfully logged. Now you can close the browser.\"",
"to_return",
"=",
"true",
"end",
"session",
".",
"write",
"(",
"message",
")",
"# Close session and webserver.",
"session",
".",
"close",
"return",
"to_return",
"end"
] | Automaticaly open autorization url a waiting for callback.
Launchy gem is required
Parameters:
server:: server will be on this addres, its alson address for oatuh 2 callback
port:: listening port for server
port=0:: server will be on first free port
Steps:
1) create server
2) launch browser and redirect to google api
3) confirm and google api redirect to localhost
4) server get code and start session
5) close server - you are login | [
"Automaticaly",
"open",
"autorization",
"url",
"a",
"waiting",
"for",
"callback",
".",
"Launchy",
"gem",
"is",
"required"
] | 258ac9958f47e8d4151e944910d649c2b372828f | https://github.com/ondra-m/google_api/blob/258ac9958f47e8d4151e944910d649c2b372828f/lib/google_api/session/session.rb#L101-L149 | train |
vladgh/vtasks | lib/vtasks/docker.rb | Vtasks.Docker.add_namespace | def add_namespace(image, path)
namespace path.to_sym do |_args|
require 'rspec/core/rake_task'
::RSpec::Core::RakeTask.new(:spec) do |task|
task.pattern = "#{path}/spec/*_spec.rb"
end
docker_image = Vtasks::Docker::Image.new(image, path, args)
lint_image(path)
desc 'Build and tag docker image'
task :build do
docker_image.build_with_tags
end
desc 'Publish docker image'
task :push do
docker_image.push
end
end
end | ruby | def add_namespace(image, path)
namespace path.to_sym do |_args|
require 'rspec/core/rake_task'
::RSpec::Core::RakeTask.new(:spec) do |task|
task.pattern = "#{path}/spec/*_spec.rb"
end
docker_image = Vtasks::Docker::Image.new(image, path, args)
lint_image(path)
desc 'Build and tag docker image'
task :build do
docker_image.build_with_tags
end
desc 'Publish docker image'
task :push do
docker_image.push
end
end
end | [
"def",
"add_namespace",
"(",
"image",
",",
"path",
")",
"namespace",
"path",
".",
"to_sym",
"do",
"|",
"_args",
"|",
"require",
"'rspec/core/rake_task'",
"::",
"RSpec",
"::",
"Core",
"::",
"RakeTask",
".",
"new",
"(",
":spec",
")",
"do",
"|",
"task",
"|",
"task",
".",
"pattern",
"=",
"\"#{path}/spec/*_spec.rb\"",
"end",
"docker_image",
"=",
"Vtasks",
"::",
"Docker",
"::",
"Image",
".",
"new",
"(",
"image",
",",
"path",
",",
"args",
")",
"lint_image",
"(",
"path",
")",
"desc",
"'Build and tag docker image'",
"task",
":build",
"do",
"docker_image",
".",
"build_with_tags",
"end",
"desc",
"'Publish docker image'",
"task",
":push",
"do",
"docker_image",
".",
"push",
"end",
"end",
"end"
] | def define_tasks
Image namespace | [
"def",
"define_tasks",
"Image",
"namespace"
] | 46eff1d2ee6b6f4c906096105ed66aae658cad3c | https://github.com/vladgh/vtasks/blob/46eff1d2ee6b6f4c906096105ed66aae658cad3c/lib/vtasks/docker.rb#L39-L60 | train |
vladgh/vtasks | lib/vtasks/docker.rb | Vtasks.Docker.dockerfiles | def dockerfiles
@dockerfiles = Dir.glob('*').select do |dir|
File.directory?(dir) && File.exist?("#{dir}/Dockerfile")
end
end | ruby | def dockerfiles
@dockerfiles = Dir.glob('*').select do |dir|
File.directory?(dir) && File.exist?("#{dir}/Dockerfile")
end
end | [
"def",
"dockerfiles",
"@dockerfiles",
"=",
"Dir",
".",
"glob",
"(",
"'*'",
")",
".",
"select",
"do",
"|",
"dir",
"|",
"File",
".",
"directory?",
"(",
"dir",
")",
"&&",
"File",
".",
"exist?",
"(",
"\"#{dir}/Dockerfile\"",
")",
"end",
"end"
] | List all folders containing Dockerfiles | [
"List",
"all",
"folders",
"containing",
"Dockerfiles"
] | 46eff1d2ee6b6f4c906096105ed66aae658cad3c | https://github.com/vladgh/vtasks/blob/46eff1d2ee6b6f4c906096105ed66aae658cad3c/lib/vtasks/docker.rb#L85-L89 | train |
vladgh/vtasks | lib/vtasks/docker.rb | Vtasks.Docker.list_images | def list_images
desc 'List all Docker images'
task :list do
info dockerfiles.map { |image| File.basename(image) }
end
end | ruby | def list_images
desc 'List all Docker images'
task :list do
info dockerfiles.map { |image| File.basename(image) }
end
end | [
"def",
"list_images",
"desc",
"'List all Docker images'",
"task",
":list",
"do",
"info",
"dockerfiles",
".",
"map",
"{",
"|",
"image",
"|",
"File",
".",
"basename",
"(",
"image",
")",
"}",
"end",
"end"
] | List all images | [
"List",
"all",
"images"
] | 46eff1d2ee6b6f4c906096105ed66aae658cad3c | https://github.com/vladgh/vtasks/blob/46eff1d2ee6b6f4c906096105ed66aae658cad3c/lib/vtasks/docker.rb#L99-L104 | train |
demersus/return_hook | lib/return_hook/form_tag_helper.rb | ReturnHook.FormTagHelper.html_options_for_form | def html_options_for_form(url_for_options, options)
options.stringify_keys.tap do |html_options|
html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart")
# The following URL is unescaped, this is just a hash of options, and it is the
# responsibility of the caller to escape all the values.
## OVERRIDDEN HERE:
html_options["action"] = forward_return_hook(url_for(url_for_options))
html_options["accept-charset"] = "UTF-8"
html_options["data-remote"] = true if html_options.delete("remote")
if html_options["data-remote"] &&
!embed_authenticity_token_in_remote_forms &&
html_options["authenticity_token"].blank?
# The authenticity token is taken from the meta tag in this case
html_options["authenticity_token"] = false
elsif html_options["authenticity_token"] == true
# Include the default authenticity_token, which is only generated when its set to nil,
# but we needed the true value to override the default of no authenticity_token on data-remote.
html_options["authenticity_token"] = nil
end
end
end | ruby | def html_options_for_form(url_for_options, options)
options.stringify_keys.tap do |html_options|
html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart")
# The following URL is unescaped, this is just a hash of options, and it is the
# responsibility of the caller to escape all the values.
## OVERRIDDEN HERE:
html_options["action"] = forward_return_hook(url_for(url_for_options))
html_options["accept-charset"] = "UTF-8"
html_options["data-remote"] = true if html_options.delete("remote")
if html_options["data-remote"] &&
!embed_authenticity_token_in_remote_forms &&
html_options["authenticity_token"].blank?
# The authenticity token is taken from the meta tag in this case
html_options["authenticity_token"] = false
elsif html_options["authenticity_token"] == true
# Include the default authenticity_token, which is only generated when its set to nil,
# but we needed the true value to override the default of no authenticity_token on data-remote.
html_options["authenticity_token"] = nil
end
end
end | [
"def",
"html_options_for_form",
"(",
"url_for_options",
",",
"options",
")",
"options",
".",
"stringify_keys",
".",
"tap",
"do",
"|",
"html_options",
"|",
"html_options",
"[",
"\"enctype\"",
"]",
"=",
"\"multipart/form-data\"",
"if",
"html_options",
".",
"delete",
"(",
"\"multipart\"",
")",
"# The following URL is unescaped, this is just a hash of options, and it is the",
"# responsibility of the caller to escape all the values.",
"## OVERRIDDEN HERE:",
"html_options",
"[",
"\"action\"",
"]",
"=",
"forward_return_hook",
"(",
"url_for",
"(",
"url_for_options",
")",
")",
"html_options",
"[",
"\"accept-charset\"",
"]",
"=",
"\"UTF-8\"",
"html_options",
"[",
"\"data-remote\"",
"]",
"=",
"true",
"if",
"html_options",
".",
"delete",
"(",
"\"remote\"",
")",
"if",
"html_options",
"[",
"\"data-remote\"",
"]",
"&&",
"!",
"embed_authenticity_token_in_remote_forms",
"&&",
"html_options",
"[",
"\"authenticity_token\"",
"]",
".",
"blank?",
"# The authenticity token is taken from the meta tag in this case",
"html_options",
"[",
"\"authenticity_token\"",
"]",
"=",
"false",
"elsif",
"html_options",
"[",
"\"authenticity_token\"",
"]",
"==",
"true",
"# Include the default authenticity_token, which is only generated when its set to nil,",
"# but we needed the true value to override the default of no authenticity_token on data-remote.",
"html_options",
"[",
"\"authenticity_token\"",
"]",
"=",
"nil",
"end",
"end",
"end"
] | This method overrides the rails built in form helper's action setting code
to inject a return path | [
"This",
"method",
"overrides",
"the",
"rails",
"built",
"in",
"form",
"helper",
"s",
"action",
"setting",
"code",
"to",
"inject",
"a",
"return",
"path"
] | f5c95bc0bc709cfe1e89a717706dc7e5ea492382 | https://github.com/demersus/return_hook/blob/f5c95bc0bc709cfe1e89a717706dc7e5ea492382/lib/return_hook/form_tag_helper.rb#L6-L30 | train |
pranavraja/beanstalkify | lib/beanstalkify/environment.rb | Beanstalkify.Environment.deploy! | def deploy!(app, settings=[])
@beanstalk.update_environment({
version_label: app.version,
environment_name: self.name,
option_settings: settings
})
end | ruby | def deploy!(app, settings=[])
@beanstalk.update_environment({
version_label: app.version,
environment_name: self.name,
option_settings: settings
})
end | [
"def",
"deploy!",
"(",
"app",
",",
"settings",
"=",
"[",
"]",
")",
"@beanstalk",
".",
"update_environment",
"(",
"{",
"version_label",
":",
"app",
".",
"version",
",",
"environment_name",
":",
"self",
".",
"name",
",",
"option_settings",
":",
"settings",
"}",
")",
"end"
] | Assuming the provided app has already been uploaded,
update this environment to the app's version
Optionally pass in a bunch of settings to override | [
"Assuming",
"the",
"provided",
"app",
"has",
"already",
"been",
"uploaded",
"update",
"this",
"environment",
"to",
"the",
"app",
"s",
"version",
"Optionally",
"pass",
"in",
"a",
"bunch",
"of",
"settings",
"to",
"override"
] | adb739b0ae8c6cb003378bc9098a8d1cfd17e06b | https://github.com/pranavraja/beanstalkify/blob/adb739b0ae8c6cb003378bc9098a8d1cfd17e06b/lib/beanstalkify/environment.rb#L19-L25 | train |
pranavraja/beanstalkify | lib/beanstalkify/environment.rb | Beanstalkify.Environment.create! | def create!(archive, stack, cnames, settings=[])
params = {
application_name: archive.app_name,
version_label: archive.version,
environment_name: self.name,
solution_stack_name: stack,
option_settings: settings
}
cnames.each do |c|
if dns_available(c)
params[:cname_prefix] = c
break
else
puts "CNAME #{c} is unavailable."
end
end
@beanstalk.create_environment(params)
end | ruby | def create!(archive, stack, cnames, settings=[])
params = {
application_name: archive.app_name,
version_label: archive.version,
environment_name: self.name,
solution_stack_name: stack,
option_settings: settings
}
cnames.each do |c|
if dns_available(c)
params[:cname_prefix] = c
break
else
puts "CNAME #{c} is unavailable."
end
end
@beanstalk.create_environment(params)
end | [
"def",
"create!",
"(",
"archive",
",",
"stack",
",",
"cnames",
",",
"settings",
"=",
"[",
"]",
")",
"params",
"=",
"{",
"application_name",
":",
"archive",
".",
"app_name",
",",
"version_label",
":",
"archive",
".",
"version",
",",
"environment_name",
":",
"self",
".",
"name",
",",
"solution_stack_name",
":",
"stack",
",",
"option_settings",
":",
"settings",
"}",
"cnames",
".",
"each",
"do",
"|",
"c",
"|",
"if",
"dns_available",
"(",
"c",
")",
"params",
"[",
":cname_prefix",
"]",
"=",
"c",
"break",
"else",
"puts",
"\"CNAME #{c} is unavailable.\"",
"end",
"end",
"@beanstalk",
".",
"create_environment",
"(",
"params",
")",
"end"
] | Assuming the archive has already been uploaded,
create a new environment with the app deployed onto the provided stack.
Attempts to use the first available cname in the cnames array. | [
"Assuming",
"the",
"archive",
"has",
"already",
"been",
"uploaded",
"create",
"a",
"new",
"environment",
"with",
"the",
"app",
"deployed",
"onto",
"the",
"provided",
"stack",
".",
"Attempts",
"to",
"use",
"the",
"first",
"available",
"cname",
"in",
"the",
"cnames",
"array",
"."
] | adb739b0ae8c6cb003378bc9098a8d1cfd17e06b | https://github.com/pranavraja/beanstalkify/blob/adb739b0ae8c6cb003378bc9098a8d1cfd17e06b/lib/beanstalkify/environment.rb#L30-L47 | train |
DamienRobert/drain | lib/dr/base/encoding.rb | DR.Encoding.fix_utf8 | def fix_utf8(s=nil)
s=self if s.nil? #if we are included
if String.method_defined?(:scrub)
#Ruby 2.1
#cf http://ruby-doc.org/core-2.1.0/String.html#method-i-scrub
return s.scrub {|bytes| '<'+bytes.unpack('H*')[0]+'>' }
else
return DR::Encoding.to_utf8(s)
end
end | ruby | def fix_utf8(s=nil)
s=self if s.nil? #if we are included
if String.method_defined?(:scrub)
#Ruby 2.1
#cf http://ruby-doc.org/core-2.1.0/String.html#method-i-scrub
return s.scrub {|bytes| '<'+bytes.unpack('H*')[0]+'>' }
else
return DR::Encoding.to_utf8(s)
end
end | [
"def",
"fix_utf8",
"(",
"s",
"=",
"nil",
")",
"s",
"=",
"self",
"if",
"s",
".",
"nil?",
"#if we are included",
"if",
"String",
".",
"method_defined?",
"(",
":scrub",
")",
"#Ruby 2.1",
"#cf http://ruby-doc.org/core-2.1.0/String.html#method-i-scrub",
"return",
"s",
".",
"scrub",
"{",
"|",
"bytes",
"|",
"'<'",
"+",
"bytes",
".",
"unpack",
"(",
"'H*'",
")",
"[",
"0",
"]",
"+",
"'>'",
"}",
"else",
"return",
"DR",
"::",
"Encoding",
".",
"to_utf8",
"(",
"s",
")",
"end",
"end"
] | if a mostly utf8 has some mixed in latin1 characters, replace the
invalid characters | [
"if",
"a",
"mostly",
"utf8",
"has",
"some",
"mixed",
"in",
"latin1",
"characters",
"replace",
"the",
"invalid",
"characters"
] | d6e5c928821501ad2ebdf2f988558e9690973778 | https://github.com/DamienRobert/drain/blob/d6e5c928821501ad2ebdf2f988558e9690973778/lib/dr/base/encoding.rb#L8-L17 | train |
DamienRobert/drain | lib/dr/base/encoding.rb | DR.Encoding.to_utf8! | def to_utf8!(s=nil,from:nil)
s=self if s.nil? #if we are included
from=s.encoding if from.nil?
return s.encode!('UTF-8',from, :invalid => :replace, :undef => :replace,
:fallback => Proc.new { |bytes| '<'+bytes.unpack('H*')[0]+'>' }
)
end | ruby | def to_utf8!(s=nil,from:nil)
s=self if s.nil? #if we are included
from=s.encoding if from.nil?
return s.encode!('UTF-8',from, :invalid => :replace, :undef => :replace,
:fallback => Proc.new { |bytes| '<'+bytes.unpack('H*')[0]+'>' }
)
end | [
"def",
"to_utf8!",
"(",
"s",
"=",
"nil",
",",
"from",
":",
"nil",
")",
"s",
"=",
"self",
"if",
"s",
".",
"nil?",
"#if we are included",
"from",
"=",
"s",
".",
"encoding",
"if",
"from",
".",
"nil?",
"return",
"s",
".",
"encode!",
"(",
"'UTF-8'",
",",
"from",
",",
":invalid",
"=>",
":replace",
",",
":undef",
"=>",
":replace",
",",
":fallback",
"=>",
"Proc",
".",
"new",
"{",
"|",
"bytes",
"|",
"'<'",
"+",
"bytes",
".",
"unpack",
"(",
"'H*'",
")",
"[",
"0",
"]",
"+",
"'>'",
"}",
")",
"end"
] | assume ruby>=1.9 here | [
"assume",
"ruby",
">",
"=",
"1",
".",
"9",
"here"
] | d6e5c928821501ad2ebdf2f988558e9690973778 | https://github.com/DamienRobert/drain/blob/d6e5c928821501ad2ebdf2f988558e9690973778/lib/dr/base/encoding.rb#L35-L41 | train |
godfat/muack | lib/muack/spy.rb | Muack.Spy.__mock_dispatch_spy | def __mock_dispatch_spy
@stub.__mock_disps.values.flatten.each do |disp|
next unless __mock_defis.key?(disp.msg) # ignore undefined spies
defis = __mock_defis[disp.msg]
if idx = __mock_find_checked_difi(defis, disp.args, :index)
__mock_disps_push(defis.delete_at(idx)) # found, dispatch it
elsif defis.empty? # show called candidates
__mock_failed(disp.msg, disp.args)
else # show expected candidates
__mock_failed(disp.msg, disp.args, defis)
end
end
end | ruby | def __mock_dispatch_spy
@stub.__mock_disps.values.flatten.each do |disp|
next unless __mock_defis.key?(disp.msg) # ignore undefined spies
defis = __mock_defis[disp.msg]
if idx = __mock_find_checked_difi(defis, disp.args, :index)
__mock_disps_push(defis.delete_at(idx)) # found, dispatch it
elsif defis.empty? # show called candidates
__mock_failed(disp.msg, disp.args)
else # show expected candidates
__mock_failed(disp.msg, disp.args, defis)
end
end
end | [
"def",
"__mock_dispatch_spy",
"@stub",
".",
"__mock_disps",
".",
"values",
".",
"flatten",
".",
"each",
"do",
"|",
"disp",
"|",
"next",
"unless",
"__mock_defis",
".",
"key?",
"(",
"disp",
".",
"msg",
")",
"# ignore undefined spies",
"defis",
"=",
"__mock_defis",
"[",
"disp",
".",
"msg",
"]",
"if",
"idx",
"=",
"__mock_find_checked_difi",
"(",
"defis",
",",
"disp",
".",
"args",
",",
":index",
")",
"__mock_disps_push",
"(",
"defis",
".",
"delete_at",
"(",
"idx",
")",
")",
"# found, dispatch it",
"elsif",
"defis",
".",
"empty?",
"# show called candidates",
"__mock_failed",
"(",
"disp",
".",
"msg",
",",
"disp",
".",
"args",
")",
"else",
"# show expected candidates",
"__mock_failed",
"(",
"disp",
".",
"msg",
",",
"disp",
".",
"args",
",",
"defis",
")",
"end",
"end",
"end"
] | spies don't leave any track
simulate dispatching before passing to mock to verify | [
"spies",
"don",
"t",
"leave",
"any",
"track",
"simulate",
"dispatching",
"before",
"passing",
"to",
"mock",
"to",
"verify"
] | 3b46287a5a45622f7c3458fb1350c64e105ce2b2 | https://github.com/godfat/muack/blob/3b46287a5a45622f7c3458fb1350c64e105ce2b2/lib/muack/spy.rb#L24-L37 | train |
samsao/danger-samsao | lib/samsao/actions.rb | Samsao.Actions.check_non_single_commit_feature | def check_non_single_commit_feature(level = :fail)
commit_count = git.commits.size
message = "Your feature branch should have a single commit but found #{commit_count}, squash them together!"
report(level, message) if feature_branch? && commit_count > 1
end | ruby | def check_non_single_commit_feature(level = :fail)
commit_count = git.commits.size
message = "Your feature branch should have a single commit but found #{commit_count}, squash them together!"
report(level, message) if feature_branch? && commit_count > 1
end | [
"def",
"check_non_single_commit_feature",
"(",
"level",
"=",
":fail",
")",
"commit_count",
"=",
"git",
".",
"commits",
".",
"size",
"message",
"=",
"\"Your feature branch should have a single commit but found #{commit_count}, squash them together!\"",
"report",
"(",
"level",
",",
"message",
")",
"if",
"feature_branch?",
"&&",
"commit_count",
">",
"1",
"end"
] | Check if a feature branch have more than one commit.
@param [Symbol] level (Default: :fail)
The report level (:fail, :warn, :message) if the check fails [report](#report)
@return [void] | [
"Check",
"if",
"a",
"feature",
"branch",
"have",
"more",
"than",
"one",
"commit",
"."
] | 59a9d6d87e6c58d5c6aadc96fae99555f7ea297b | https://github.com/samsao/danger-samsao/blob/59a9d6d87e6c58d5c6aadc96fae99555f7ea297b/lib/samsao/actions.rb#L22-L27 | train |
samsao/danger-samsao | lib/samsao/actions.rb | Samsao.Actions.check_feature_jira_issue_number | def check_feature_jira_issue_number(level = :fail)
return if samsao.trivial_change? || !samsao.feature_branch?
return report(:fail, 'Your Danger config is missing a `jira_project_key` value.') unless jira_project_key?
message = 'The PR title must starts with JIRA issue number between square brackets'\
" (i.e. [#{config.jira_project_key}-XXX])."
report(level, message) unless contains_jira_issue_number?(github.pr_title)
end | ruby | def check_feature_jira_issue_number(level = :fail)
return if samsao.trivial_change? || !samsao.feature_branch?
return report(:fail, 'Your Danger config is missing a `jira_project_key` value.') unless jira_project_key?
message = 'The PR title must starts with JIRA issue number between square brackets'\
" (i.e. [#{config.jira_project_key}-XXX])."
report(level, message) unless contains_jira_issue_number?(github.pr_title)
end | [
"def",
"check_feature_jira_issue_number",
"(",
"level",
"=",
":fail",
")",
"return",
"if",
"samsao",
".",
"trivial_change?",
"||",
"!",
"samsao",
".",
"feature_branch?",
"return",
"report",
"(",
":fail",
",",
"'Your Danger config is missing a `jira_project_key` value.'",
")",
"unless",
"jira_project_key?",
"message",
"=",
"'The PR title must starts with JIRA issue number between square brackets'",
"\" (i.e. [#{config.jira_project_key}-XXX]).\"",
"report",
"(",
"level",
",",
"message",
")",
"unless",
"contains_jira_issue_number?",
"(",
"github",
".",
"pr_title",
")",
"end"
] | Check if a feature branch contains a single JIRA issue number matching the jira project key.
@param [Symbol] level (Default: :fail)
The report level (:fail, :warn, :message) if the check fails [report](#report)
@return [void] | [
"Check",
"if",
"a",
"feature",
"branch",
"contains",
"a",
"single",
"JIRA",
"issue",
"number",
"matching",
"the",
"jira",
"project",
"key",
"."
] | 59a9d6d87e6c58d5c6aadc96fae99555f7ea297b | https://github.com/samsao/danger-samsao/blob/59a9d6d87e6c58d5c6aadc96fae99555f7ea297b/lib/samsao/actions.rb#L71-L79 | train |
samsao/danger-samsao | lib/samsao/actions.rb | Samsao.Actions.check_fix_jira_issue_number | def check_fix_jira_issue_number(level = :warn)
return if samsao.trivial_change? || !samsao.fix_branch?
return report(:fail, 'Your Danger config is missing a `jira_project_key` value.') unless jira_project_key?
git.commits.each do |commit|
check_commit_contains_jira_issue_number(commit, level)
end
end | ruby | def check_fix_jira_issue_number(level = :warn)
return if samsao.trivial_change? || !samsao.fix_branch?
return report(:fail, 'Your Danger config is missing a `jira_project_key` value.') unless jira_project_key?
git.commits.each do |commit|
check_commit_contains_jira_issue_number(commit, level)
end
end | [
"def",
"check_fix_jira_issue_number",
"(",
"level",
"=",
":warn",
")",
"return",
"if",
"samsao",
".",
"trivial_change?",
"||",
"!",
"samsao",
".",
"fix_branch?",
"return",
"report",
"(",
":fail",
",",
"'Your Danger config is missing a `jira_project_key` value.'",
")",
"unless",
"jira_project_key?",
"git",
".",
"commits",
".",
"each",
"do",
"|",
"commit",
"|",
"check_commit_contains_jira_issue_number",
"(",
"commit",
",",
"level",
")",
"end",
"end"
] | Check if all fix branch commit's message contains any JIRA issue number matching the jira project key.
@param [Symbol] level (Default: :warn)
The report level (:fail, :warn, :message) if the check fails [report](#report)
@return [void] | [
"Check",
"if",
"all",
"fix",
"branch",
"commit",
"s",
"message",
"contains",
"any",
"JIRA",
"issue",
"number",
"matching",
"the",
"jira",
"project",
"key",
"."
] | 59a9d6d87e6c58d5c6aadc96fae99555f7ea297b | https://github.com/samsao/danger-samsao/blob/59a9d6d87e6c58d5c6aadc96fae99555f7ea297b/lib/samsao/actions.rb#L87-L94 | train |
samsao/danger-samsao | lib/samsao/actions.rb | Samsao.Actions.check_acceptance_criteria | def check_acceptance_criteria(level = :warn)
return unless samsao.feature_branch?
message = 'The PR description should have the acceptance criteria in the body.'
report(level, message) if (/acceptance criteria/i =~ github.pr_body).nil?
end | ruby | def check_acceptance_criteria(level = :warn)
return unless samsao.feature_branch?
message = 'The PR description should have the acceptance criteria in the body.'
report(level, message) if (/acceptance criteria/i =~ github.pr_body).nil?
end | [
"def",
"check_acceptance_criteria",
"(",
"level",
"=",
":warn",
")",
"return",
"unless",
"samsao",
".",
"feature_branch?",
"message",
"=",
"'The PR description should have the acceptance criteria in the body.'",
"report",
"(",
"level",
",",
"message",
")",
"if",
"(",
"/",
"/i",
"=~",
"github",
".",
"pr_body",
")",
".",
"nil?",
"end"
] | Check if it's a feature branch and if the PR body contains acceptance criteria.
@param [Symbol] level (Default: :warn)
The report level (:fail, :warn, :message) if the check fails [report](#report)
@return [void] | [
"Check",
"if",
"it",
"s",
"a",
"feature",
"branch",
"and",
"if",
"the",
"PR",
"body",
"contains",
"acceptance",
"criteria",
"."
] | 59a9d6d87e6c58d5c6aadc96fae99555f7ea297b | https://github.com/samsao/danger-samsao/blob/59a9d6d87e6c58d5c6aadc96fae99555f7ea297b/lib/samsao/actions.rb#L102-L108 | train |
samsao/danger-samsao | lib/samsao/actions.rb | Samsao.Actions.check_label_pr | def check_label_pr(level = :fail)
message = 'The PR should have at least one label added to it.'
report(level, message) if github.pr_labels.nil? || github.pr_labels.empty?
end | ruby | def check_label_pr(level = :fail)
message = 'The PR should have at least one label added to it.'
report(level, message) if github.pr_labels.nil? || github.pr_labels.empty?
end | [
"def",
"check_label_pr",
"(",
"level",
"=",
":fail",
")",
"message",
"=",
"'The PR should have at least one label added to it.'",
"report",
"(",
"level",
",",
"message",
")",
"if",
"github",
".",
"pr_labels",
".",
"nil?",
"||",
"github",
".",
"pr_labels",
".",
"empty?",
"end"
] | Check if the PR has at least one label added to it.
@param [Symbol] level (Default: :fail)
The report level (:fail, :warn, :message) if the check fails [report](#report)
@return [void] | [
"Check",
"if",
"the",
"PR",
"has",
"at",
"least",
"one",
"label",
"added",
"to",
"it",
"."
] | 59a9d6d87e6c58d5c6aadc96fae99555f7ea297b | https://github.com/samsao/danger-samsao/blob/59a9d6d87e6c58d5c6aadc96fae99555f7ea297b/lib/samsao/actions.rb#L116-L120 | train |
samsao/danger-samsao | lib/samsao/actions.rb | Samsao.Actions.report | def report(level, content)
case level
when :warn
warn content
when :fail
fail content
when :message
message content
else
raise "Report level '#{level}' is invalid."
end
end | ruby | def report(level, content)
case level
when :warn
warn content
when :fail
fail content
when :message
message content
else
raise "Report level '#{level}' is invalid."
end
end | [
"def",
"report",
"(",
"level",
",",
"content",
")",
"case",
"level",
"when",
":warn",
"warn",
"content",
"when",
":fail",
"fail",
"content",
"when",
":message",
"message",
"content",
"else",
"raise",
"\"Report level '#{level}' is invalid.\"",
"end",
"end"
] | Send report to danger depending on the level.
@param [Symbol] level
The report level sent to Danger :
:message > Comment a message to the table
:warn > Declares a CI warning
:fail > Declares a CI blocking error
@param [String] content
The message of the report sent to Danger
@return [void] | [
"Send",
"report",
"to",
"danger",
"depending",
"on",
"the",
"level",
"."
] | 59a9d6d87e6c58d5c6aadc96fae99555f7ea297b | https://github.com/samsao/danger-samsao/blob/59a9d6d87e6c58d5c6aadc96fae99555f7ea297b/lib/samsao/actions.rb#L133-L144 | train |
samsao/danger-samsao | lib/samsao/actions.rb | Samsao.Actions.check_commit_contains_jira_issue_number | def check_commit_contains_jira_issue_number(commit, type)
commit_id = "#{shorten_sha(commit.sha)} ('#{truncate(commit.message)}')"
jira_project_key = config.jira_project_key
message = "The commit message #{commit_id} should contain JIRA issue number" \
" between square brackets (i.e. [#{jira_project_key}-XXX]), multiple allowed" \
" (i.e. [#{jira_project_key}-XXX, #{jira_project_key}-YYY, #{jira_project_key}-ZZZ])"
report(type, message) unless contains_jira_issue_number?(commit.message)
end | ruby | def check_commit_contains_jira_issue_number(commit, type)
commit_id = "#{shorten_sha(commit.sha)} ('#{truncate(commit.message)}')"
jira_project_key = config.jira_project_key
message = "The commit message #{commit_id} should contain JIRA issue number" \
" between square brackets (i.e. [#{jira_project_key}-XXX]), multiple allowed" \
" (i.e. [#{jira_project_key}-XXX, #{jira_project_key}-YYY, #{jira_project_key}-ZZZ])"
report(type, message) unless contains_jira_issue_number?(commit.message)
end | [
"def",
"check_commit_contains_jira_issue_number",
"(",
"commit",
",",
"type",
")",
"commit_id",
"=",
"\"#{shorten_sha(commit.sha)} ('#{truncate(commit.message)}')\"",
"jira_project_key",
"=",
"config",
".",
"jira_project_key",
"message",
"=",
"\"The commit message #{commit_id} should contain JIRA issue number\"",
"\" between square brackets (i.e. [#{jira_project_key}-XXX]), multiple allowed\"",
"\" (i.e. [#{jira_project_key}-XXX, #{jira_project_key}-YYY, #{jira_project_key}-ZZZ])\"",
"report",
"(",
"type",
",",
"message",
")",
"unless",
"contains_jira_issue_number?",
"(",
"commit",
".",
"message",
")",
"end"
] | Check if the commit's message contains any JIRA issue number matching the jira project key.
@param [Commit] commit
The git commit to check
@param [Symbol] level (Default: :warn)
The report level (:fail, :warn, :message) if the check fails [report](#report)
@return [void] | [
"Check",
"if",
"the",
"commit",
"s",
"message",
"contains",
"any",
"JIRA",
"issue",
"number",
"matching",
"the",
"jira",
"project",
"key",
"."
] | 59a9d6d87e6c58d5c6aadc96fae99555f7ea297b | https://github.com/samsao/danger-samsao/blob/59a9d6d87e6c58d5c6aadc96fae99555f7ea297b/lib/samsao/actions.rb#L156-L164 | train |
zpatten/ztk | lib/ztk/background.rb | ZTK.Background.wait | def wait
config.ui.logger.debug { "wait" }
pid, status = (Process.wait2(@pid) rescue nil)
if !pid.nil? && !status.nil?
data = (Marshal.load(Base64.decode64(@parent_reader.read.to_s)) rescue nil)
config.ui.logger.debug { "read(#{data.inspect})" }
!data.nil? and @result = data
@parent_reader.close
@parent_writer.close
return [pid, status, data]
end
nil
end | ruby | def wait
config.ui.logger.debug { "wait" }
pid, status = (Process.wait2(@pid) rescue nil)
if !pid.nil? && !status.nil?
data = (Marshal.load(Base64.decode64(@parent_reader.read.to_s)) rescue nil)
config.ui.logger.debug { "read(#{data.inspect})" }
!data.nil? and @result = data
@parent_reader.close
@parent_writer.close
return [pid, status, data]
end
nil
end | [
"def",
"wait",
"config",
".",
"ui",
".",
"logger",
".",
"debug",
"{",
"\"wait\"",
"}",
"pid",
",",
"status",
"=",
"(",
"Process",
".",
"wait2",
"(",
"@pid",
")",
"rescue",
"nil",
")",
"if",
"!",
"pid",
".",
"nil?",
"&&",
"!",
"status",
".",
"nil?",
"data",
"=",
"(",
"Marshal",
".",
"load",
"(",
"Base64",
".",
"decode64",
"(",
"@parent_reader",
".",
"read",
".",
"to_s",
")",
")",
"rescue",
"nil",
")",
"config",
".",
"ui",
".",
"logger",
".",
"debug",
"{",
"\"read(#{data.inspect})\"",
"}",
"!",
"data",
".",
"nil?",
"and",
"@result",
"=",
"data",
"@parent_reader",
".",
"close",
"@parent_writer",
".",
"close",
"return",
"[",
"pid",
",",
"status",
",",
"data",
"]",
"end",
"nil",
"end"
] | Wait for the background process to finish.
If a process successfully finished, it's return value from the *process*
block is stored into the result set.
It's advisable to use something like the *at_exit* hook to ensure you don't
leave orphaned processes. For example, in the *at_exit* hook you could
call *wait* to block until the child process finishes up.
@return [Array<pid, status, data>] An array containing the pid,
status and data returned from the process block. If wait2() fails nil
is returned. | [
"Wait",
"for",
"the",
"background",
"process",
"to",
"finish",
"."
] | 9b0f35bef36f38428e1a57b36f25a806c240b3fb | https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/background.rb#L112-L126 | train |
sugaryourcoffee/syclink | lib/syclink/formatter.rb | SycLink.Formatter.extract_columns | def extract_columns(rows, header)
columns = []
header.each do |h|
columns << rows.map do |r|
r.send(h)
end
end
columns
end | ruby | def extract_columns(rows, header)
columns = []
header.each do |h|
columns << rows.map do |r|
r.send(h)
end
end
columns
end | [
"def",
"extract_columns",
"(",
"rows",
",",
"header",
")",
"columns",
"=",
"[",
"]",
"header",
".",
"each",
"do",
"|",
"h",
"|",
"columns",
"<<",
"rows",
".",
"map",
"do",
"|",
"r",
"|",
"r",
".",
"send",
"(",
"h",
")",
"end",
"end",
"columns",
"end"
] | Extracts the columns to display in the table based on the header column
names | [
"Extracts",
"the",
"columns",
"to",
"display",
"in",
"the",
"table",
"based",
"on",
"the",
"header",
"column",
"names"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/formatter.rb#L59-L67 | train |
sugaryourcoffee/syclink | lib/syclink/formatter.rb | SycLink.Formatter.max_column_widths | def max_column_widths(columns, header, opts = {})
row_column_widths = columns.map do |c|
c.reduce(0) { |m, v| [m, v.nil? ? 0 : v.length].max }
end
header_column_widths = header.map { |h| h.length }
row_column_widths = header_column_widths if row_column_widths.empty?
widths = row_column_widths.zip(header_column_widths).map do |column|
column.reduce(0) { |m, v| [m, v].max }
end
widths.empty? ? [] : scale_widths(widths, opts)
end | ruby | def max_column_widths(columns, header, opts = {})
row_column_widths = columns.map do |c|
c.reduce(0) { |m, v| [m, v.nil? ? 0 : v.length].max }
end
header_column_widths = header.map { |h| h.length }
row_column_widths = header_column_widths if row_column_widths.empty?
widths = row_column_widths.zip(header_column_widths).map do |column|
column.reduce(0) { |m, v| [m, v].max }
end
widths.empty? ? [] : scale_widths(widths, opts)
end | [
"def",
"max_column_widths",
"(",
"columns",
",",
"header",
",",
"opts",
"=",
"{",
"}",
")",
"row_column_widths",
"=",
"columns",
".",
"map",
"do",
"|",
"c",
"|",
"c",
".",
"reduce",
"(",
"0",
")",
"{",
"|",
"m",
",",
"v",
"|",
"[",
"m",
",",
"v",
".",
"nil?",
"?",
"0",
":",
"v",
".",
"length",
"]",
".",
"max",
"}",
"end",
"header_column_widths",
"=",
"header",
".",
"map",
"{",
"|",
"h",
"|",
"h",
".",
"length",
"}",
"row_column_widths",
"=",
"header_column_widths",
"if",
"row_column_widths",
".",
"empty?",
"widths",
"=",
"row_column_widths",
".",
"zip",
"(",
"header_column_widths",
")",
".",
"map",
"do",
"|",
"column",
"|",
"column",
".",
"reduce",
"(",
"0",
")",
"{",
"|",
"m",
",",
"v",
"|",
"[",
"m",
",",
"v",
"]",
".",
"max",
"}",
"end",
"widths",
".",
"empty?",
"?",
"[",
"]",
":",
"scale_widths",
"(",
"widths",
",",
"opts",
")",
"end"
] | Determines max column widths for each column based on the data and header
columns. | [
"Determines",
"max",
"column",
"widths",
"for",
"each",
"column",
"based",
"on",
"the",
"data",
"and",
"header",
"columns",
"."
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/formatter.rb#L71-L85 | train |
sugaryourcoffee/syclink | lib/syclink/formatter.rb | SycLink.Formatter.print_horizontal_line | def print_horizontal_line(line, separator, widths)
puts widths.map { |width| line * width }.join(separator)
end | ruby | def print_horizontal_line(line, separator, widths)
puts widths.map { |width| line * width }.join(separator)
end | [
"def",
"print_horizontal_line",
"(",
"line",
",",
"separator",
",",
"widths",
")",
"puts",
"widths",
".",
"map",
"{",
"|",
"width",
"|",
"line",
"*",
"width",
"}",
".",
"join",
"(",
"separator",
")",
"end"
] | Prints a horizontal line below the header | [
"Prints",
"a",
"horizontal",
"line",
"below",
"the",
"header"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/formatter.rb#L100-L102 | train |
sugaryourcoffee/syclink | lib/syclink/formatter.rb | SycLink.Formatter.print_table | def print_table(columns, formatter)
columns.transpose.each { |row| puts sprintf(formatter, *row) }
end | ruby | def print_table(columns, formatter)
columns.transpose.each { |row| puts sprintf(formatter, *row) }
end | [
"def",
"print_table",
"(",
"columns",
",",
"formatter",
")",
"columns",
".",
"transpose",
".",
"each",
"{",
"|",
"row",
"|",
"puts",
"sprintf",
"(",
"formatter",
",",
"row",
")",
"}",
"end"
] | Prints columns in a table format | [
"Prints",
"columns",
"in",
"a",
"table",
"format"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/formatter.rb#L105-L107 | train |
lyrasis/collectionspace-client | lib/collectionspace/client/helpers.rb | CollectionSpace.Helpers.all | def all(path, options = {}, &block)
all = []
list_type, list_item = get_list_types(path)
result = request('GET', path, options)
raise RequestError.new result.status if result.status_code != 200 or result.parsed[list_type].nil?
total = result.parsed[list_type]['totalItems'].to_i
items = result.parsed[list_type]['itemsInPage'].to_i
return all if total == 0
pages = (total / config.page_size) + 1
(0 .. pages - 1).each do |i|
options[:query][:pgNum] = i
result = request('GET', path, options)
raise RequestError.new result.status if result.status_code != 200
list_items = result.parsed[list_type][list_item]
list_items = [ list_items ] if items == 1
list_items.each { |item| yield item if block_given? }
all.concat list_items
end
all
end | ruby | def all(path, options = {}, &block)
all = []
list_type, list_item = get_list_types(path)
result = request('GET', path, options)
raise RequestError.new result.status if result.status_code != 200 or result.parsed[list_type].nil?
total = result.parsed[list_type]['totalItems'].to_i
items = result.parsed[list_type]['itemsInPage'].to_i
return all if total == 0
pages = (total / config.page_size) + 1
(0 .. pages - 1).each do |i|
options[:query][:pgNum] = i
result = request('GET', path, options)
raise RequestError.new result.status if result.status_code != 200
list_items = result.parsed[list_type][list_item]
list_items = [ list_items ] if items == 1
list_items.each { |item| yield item if block_given? }
all.concat list_items
end
all
end | [
"def",
"all",
"(",
"path",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"all",
"=",
"[",
"]",
"list_type",
",",
"list_item",
"=",
"get_list_types",
"(",
"path",
")",
"result",
"=",
"request",
"(",
"'GET'",
",",
"path",
",",
"options",
")",
"raise",
"RequestError",
".",
"new",
"result",
".",
"status",
"if",
"result",
".",
"status_code",
"!=",
"200",
"or",
"result",
".",
"parsed",
"[",
"list_type",
"]",
".",
"nil?",
"total",
"=",
"result",
".",
"parsed",
"[",
"list_type",
"]",
"[",
"'totalItems'",
"]",
".",
"to_i",
"items",
"=",
"result",
".",
"parsed",
"[",
"list_type",
"]",
"[",
"'itemsInPage'",
"]",
".",
"to_i",
"return",
"all",
"if",
"total",
"==",
"0",
"pages",
"=",
"(",
"total",
"/",
"config",
".",
"page_size",
")",
"+",
"1",
"(",
"0",
"..",
"pages",
"-",
"1",
")",
".",
"each",
"do",
"|",
"i",
"|",
"options",
"[",
":query",
"]",
"[",
":pgNum",
"]",
"=",
"i",
"result",
"=",
"request",
"(",
"'GET'",
",",
"path",
",",
"options",
")",
"raise",
"RequestError",
".",
"new",
"result",
".",
"status",
"if",
"result",
".",
"status_code",
"!=",
"200",
"list_items",
"=",
"result",
".",
"parsed",
"[",
"list_type",
"]",
"[",
"list_item",
"]",
"list_items",
"=",
"[",
"list_items",
"]",
"if",
"items",
"==",
"1",
"list_items",
".",
"each",
"{",
"|",
"item",
"|",
"yield",
"item",
"if",
"block_given?",
"}",
"all",
".",
"concat",
"list_items",
"end",
"all",
"end"
] | get ALL records at path by paging through record set
can pass block to act on each page of results | [
"get",
"ALL",
"records",
"at",
"path",
"by",
"paging",
"through",
"record",
"set",
"can",
"pass",
"block",
"to",
"act",
"on",
"each",
"page",
"of",
"results"
] | 6db26dffb792bda2e8a5b46863a63dc1d56932a3 | https://github.com/lyrasis/collectionspace-client/blob/6db26dffb792bda2e8a5b46863a63dc1d56932a3/lib/collectionspace/client/helpers.rb#L23-L45 | train |
lyrasis/collectionspace-client | lib/collectionspace/client/helpers.rb | CollectionSpace.Helpers.post_blob_url | def post_blob_url(url)
raise ArgumentError.new("Invalid blob URL #{url}") unless URI.parse(url).scheme =~ /^https?/
request 'POST', "blobs", {
query: { "blobUri" => url },
}
end | ruby | def post_blob_url(url)
raise ArgumentError.new("Invalid blob URL #{url}") unless URI.parse(url).scheme =~ /^https?/
request 'POST', "blobs", {
query: { "blobUri" => url },
}
end | [
"def",
"post_blob_url",
"(",
"url",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Invalid blob URL #{url}\"",
")",
"unless",
"URI",
".",
"parse",
"(",
"url",
")",
".",
"scheme",
"=~",
"/",
"/",
"request",
"'POST'",
",",
"\"blobs\"",
",",
"{",
"query",
":",
"{",
"\"blobUri\"",
"=>",
"url",
"}",
",",
"}",
"end"
] | create blob record by external url | [
"create",
"blob",
"record",
"by",
"external",
"url"
] | 6db26dffb792bda2e8a5b46863a63dc1d56932a3 | https://github.com/lyrasis/collectionspace-client/blob/6db26dffb792bda2e8a5b46863a63dc1d56932a3/lib/collectionspace/client/helpers.rb#L56-L61 | train |
lyrasis/collectionspace-client | lib/collectionspace/client/helpers.rb | CollectionSpace.Helpers.to_object | def to_object(record, attribute_map, stringify_keys = false)
attributes = {}
attribute_map.each do |map|
map = map.inject({}) { |memo,(k,v)| memo[k.to_s] = v; memo} if stringify_keys
if map["with"]
as = deep_find(record, map["key"], map["nested_key"])
values = []
if as.is_a? Array
values = as.map { |a| strip_refname( deep_find(a, map["with"]) ) }
elsif as.is_a? Hash and as[ map["with"] ]
values = as[ map["with"] ].is_a?(Array) ? as[ map["with"] ].map { |a| strip_refname(a) } : [ strip_refname(as[ map["with"] ]) ]
end
attributes[map["field"]] = values
else
attributes[map["field"]] = deep_find(record, map["key"], map["nested_key"])
end
end
attributes
end | ruby | def to_object(record, attribute_map, stringify_keys = false)
attributes = {}
attribute_map.each do |map|
map = map.inject({}) { |memo,(k,v)| memo[k.to_s] = v; memo} if stringify_keys
if map["with"]
as = deep_find(record, map["key"], map["nested_key"])
values = []
if as.is_a? Array
values = as.map { |a| strip_refname( deep_find(a, map["with"]) ) }
elsif as.is_a? Hash and as[ map["with"] ]
values = as[ map["with"] ].is_a?(Array) ? as[ map["with"] ].map { |a| strip_refname(a) } : [ strip_refname(as[ map["with"] ]) ]
end
attributes[map["field"]] = values
else
attributes[map["field"]] = deep_find(record, map["key"], map["nested_key"])
end
end
attributes
end | [
"def",
"to_object",
"(",
"record",
",",
"attribute_map",
",",
"stringify_keys",
"=",
"false",
")",
"attributes",
"=",
"{",
"}",
"attribute_map",
".",
"each",
"do",
"|",
"map",
"|",
"map",
"=",
"map",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"memo",
",",
"(",
"k",
",",
"v",
")",
"|",
"memo",
"[",
"k",
".",
"to_s",
"]",
"=",
"v",
";",
"memo",
"}",
"if",
"stringify_keys",
"if",
"map",
"[",
"\"with\"",
"]",
"as",
"=",
"deep_find",
"(",
"record",
",",
"map",
"[",
"\"key\"",
"]",
",",
"map",
"[",
"\"nested_key\"",
"]",
")",
"values",
"=",
"[",
"]",
"if",
"as",
".",
"is_a?",
"Array",
"values",
"=",
"as",
".",
"map",
"{",
"|",
"a",
"|",
"strip_refname",
"(",
"deep_find",
"(",
"a",
",",
"map",
"[",
"\"with\"",
"]",
")",
")",
"}",
"elsif",
"as",
".",
"is_a?",
"Hash",
"and",
"as",
"[",
"map",
"[",
"\"with\"",
"]",
"]",
"values",
"=",
"as",
"[",
"map",
"[",
"\"with\"",
"]",
"]",
".",
"is_a?",
"(",
"Array",
")",
"?",
"as",
"[",
"map",
"[",
"\"with\"",
"]",
"]",
".",
"map",
"{",
"|",
"a",
"|",
"strip_refname",
"(",
"a",
")",
"}",
":",
"[",
"strip_refname",
"(",
"as",
"[",
"map",
"[",
"\"with\"",
"]",
"]",
")",
"]",
"end",
"attributes",
"[",
"map",
"[",
"\"field\"",
"]",
"]",
"=",
"values",
"else",
"attributes",
"[",
"map",
"[",
"\"field\"",
"]",
"]",
"=",
"deep_find",
"(",
"record",
",",
"map",
"[",
"\"key\"",
"]",
",",
"map",
"[",
"\"nested_key\"",
"]",
")",
"end",
"end",
"attributes",
"end"
] | parsed record and map to get restructured object | [
"parsed",
"record",
"and",
"map",
"to",
"get",
"restructured",
"object"
] | 6db26dffb792bda2e8a5b46863a63dc1d56932a3 | https://github.com/lyrasis/collectionspace-client/blob/6db26dffb792bda2e8a5b46863a63dc1d56932a3/lib/collectionspace/client/helpers.rb#L86-L104 | train |
tbuehlmann/ponder | lib/ponder/channel.rb | Ponder.Channel.topic | def topic
if @topic
@topic
else
connected do
fiber = Fiber.current
callbacks = {}
[331, 332, 403, 442].each do |numeric|
callbacks[numeric] = @thaum.on(numeric) do |event_data|
topic = event_data[:params].match(':(.*)').captures.first
fiber.resume topic
end
end
raw "TOPIC #{@name}"
@topic = Fiber.yield
callbacks.each do |type, callback|
@thaum.callbacks[type].delete(callback)
end
@topic
end
end
end | ruby | def topic
if @topic
@topic
else
connected do
fiber = Fiber.current
callbacks = {}
[331, 332, 403, 442].each do |numeric|
callbacks[numeric] = @thaum.on(numeric) do |event_data|
topic = event_data[:params].match(':(.*)').captures.first
fiber.resume topic
end
end
raw "TOPIC #{@name}"
@topic = Fiber.yield
callbacks.each do |type, callback|
@thaum.callbacks[type].delete(callback)
end
@topic
end
end
end | [
"def",
"topic",
"if",
"@topic",
"@topic",
"else",
"connected",
"do",
"fiber",
"=",
"Fiber",
".",
"current",
"callbacks",
"=",
"{",
"}",
"[",
"331",
",",
"332",
",",
"403",
",",
"442",
"]",
".",
"each",
"do",
"|",
"numeric",
"|",
"callbacks",
"[",
"numeric",
"]",
"=",
"@thaum",
".",
"on",
"(",
"numeric",
")",
"do",
"|",
"event_data",
"|",
"topic",
"=",
"event_data",
"[",
":params",
"]",
".",
"match",
"(",
"':(.*)'",
")",
".",
"captures",
".",
"first",
"fiber",
".",
"resume",
"topic",
"end",
"end",
"raw",
"\"TOPIC #{@name}\"",
"@topic",
"=",
"Fiber",
".",
"yield",
"callbacks",
".",
"each",
"do",
"|",
"type",
",",
"callback",
"|",
"@thaum",
".",
"callbacks",
"[",
"type",
"]",
".",
"delete",
"(",
"callback",
")",
"end",
"@topic",
"end",
"end",
"end"
] | Experimental, no tests so far. | [
"Experimental",
"no",
"tests",
"so",
"far",
"."
] | 930912e1b78b41afa1359121aca46197e9edff9c | https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/channel.rb#L21-L44 | train |
j-a-m-l/scrapula | lib/scrapula/page.rb | Scrapula.Page.search! | def search! query, operations = [], &block
result = @agent_page.search query
# FIXME on every object
result = operations.reduce(result) do |tmp, op|
tmp.__send__ op
end if result
yield result if block_given?
result
end | ruby | def search! query, operations = [], &block
result = @agent_page.search query
# FIXME on every object
result = operations.reduce(result) do |tmp, op|
tmp.__send__ op
end if result
yield result if block_given?
result
end | [
"def",
"search!",
"query",
",",
"operations",
"=",
"[",
"]",
",",
"&",
"block",
"result",
"=",
"@agent_page",
".",
"search",
"query",
"# FIXME on every object",
"result",
"=",
"operations",
".",
"reduce",
"(",
"result",
")",
"do",
"|",
"tmp",
",",
"op",
"|",
"tmp",
".",
"__send__",
"op",
"end",
"if",
"result",
"yield",
"result",
"if",
"block_given?",
"result",
"end"
] | at returns the first one only, but search returns all | [
"at",
"returns",
"the",
"first",
"one",
"only",
"but",
"search",
"returns",
"all"
] | d5df8e1f05f0bd24e2f346ac2f2c3fc3b385b211 | https://github.com/j-a-m-l/scrapula/blob/d5df8e1f05f0bd24e2f346ac2f2c3fc3b385b211/lib/scrapula/page.rb#L24-L35 | train |
ouvrages/guard-haml-coffee | lib/guard/haml-coffee.rb | Guard.HamlCoffee.get_output | def get_output(file)
file_dir = File.dirname(file)
file_name = File.basename(file).split('.')[0..-2].join('.')
file_name = "#{file_name}.js" if file_name.match("\.js").nil?
file_dir = file_dir.gsub(Regexp.new("#{@options[:input]}(\/){0,1}"), '') if @options[:input]
file_dir = File.join(@options[:output], file_dir) if @options[:output]
if file_dir == ''
file_name
else
File.join(file_dir, file_name)
end
end | ruby | def get_output(file)
file_dir = File.dirname(file)
file_name = File.basename(file).split('.')[0..-2].join('.')
file_name = "#{file_name}.js" if file_name.match("\.js").nil?
file_dir = file_dir.gsub(Regexp.new("#{@options[:input]}(\/){0,1}"), '') if @options[:input]
file_dir = File.join(@options[:output], file_dir) if @options[:output]
if file_dir == ''
file_name
else
File.join(file_dir, file_name)
end
end | [
"def",
"get_output",
"(",
"file",
")",
"file_dir",
"=",
"File",
".",
"dirname",
"(",
"file",
")",
"file_name",
"=",
"File",
".",
"basename",
"(",
"file",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"..",
"-",
"2",
"]",
".",
"join",
"(",
"'.'",
")",
"file_name",
"=",
"\"#{file_name}.js\"",
"if",
"file_name",
".",
"match",
"(",
"\"\\.js\"",
")",
".",
"nil?",
"file_dir",
"=",
"file_dir",
".",
"gsub",
"(",
"Regexp",
".",
"new",
"(",
"\"#{@options[:input]}(\\/){0,1}\"",
")",
",",
"''",
")",
"if",
"@options",
"[",
":input",
"]",
"file_dir",
"=",
"File",
".",
"join",
"(",
"@options",
"[",
":output",
"]",
",",
"file_dir",
")",
"if",
"@options",
"[",
":output",
"]",
"if",
"file_dir",
"==",
"''",
"file_name",
"else",
"File",
".",
"join",
"(",
"file_dir",
",",
"file_name",
")",
"end",
"end"
] | Get the file path to output the html based on the file being
built. The output path is relative to where guard is being run.
@param file [String] path to file being built
@return [String] path to file where output should be written | [
"Get",
"the",
"file",
"path",
"to",
"output",
"the",
"html",
"based",
"on",
"the",
"file",
"being",
"built",
".",
"The",
"output",
"path",
"is",
"relative",
"to",
"where",
"guard",
"is",
"being",
"run",
"."
] | cfa5021cf8512c4f333c345f33f4c0199a5207ae | https://github.com/ouvrages/guard-haml-coffee/blob/cfa5021cf8512c4f333c345f33f4c0199a5207ae/lib/guard/haml-coffee.rb#L41-L55 | train |
npepinpe/redstruct | lib/redstruct/sorted_set.rb | Redstruct.SortedSet.slice | def slice(**options)
defaults = {
lower: nil,
upper: nil,
exclusive: false,
lex: @lex
}
self.class::Slice.new(self, **defaults.merge(options))
end | ruby | def slice(**options)
defaults = {
lower: nil,
upper: nil,
exclusive: false,
lex: @lex
}
self.class::Slice.new(self, **defaults.merge(options))
end | [
"def",
"slice",
"(",
"**",
"options",
")",
"defaults",
"=",
"{",
"lower",
":",
"nil",
",",
"upper",
":",
"nil",
",",
"exclusive",
":",
"false",
",",
"lex",
":",
"@lex",
"}",
"self",
".",
"class",
"::",
"Slice",
".",
"new",
"(",
"self",
",",
"**",
"defaults",
".",
"merge",
"(",
"options",
")",
")",
"end"
] | Returns a slice or partial selection of the set.
@see Redstruct::SortedSet::Slice#initialize
@return [Redstruct::SortedSet::Slice] a newly created slice for this set | [
"Returns",
"a",
"slice",
"or",
"partial",
"selection",
"of",
"the",
"set",
"."
] | c97b45e7227f8ed9029f0effff352fc4d82dc3cb | https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/sorted_set.rb#L72-L81 | train |
npepinpe/redstruct | lib/redstruct/sorted_set.rb | Redstruct.SortedSet.to_enum | def to_enum(match: '*', count: 10, with_scores: false)
enumerator = self.connection.zscan_each(@key, match: match, count: count)
return enumerator if with_scores
return Enumerator.new do |yielder|
loop do
item, = enumerator.next
yielder << item
end
end
end | ruby | def to_enum(match: '*', count: 10, with_scores: false)
enumerator = self.connection.zscan_each(@key, match: match, count: count)
return enumerator if with_scores
return Enumerator.new do |yielder|
loop do
item, = enumerator.next
yielder << item
end
end
end | [
"def",
"to_enum",
"(",
"match",
":",
"'*'",
",",
"count",
":",
"10",
",",
"with_scores",
":",
"false",
")",
"enumerator",
"=",
"self",
".",
"connection",
".",
"zscan_each",
"(",
"@key",
",",
"match",
":",
"match",
",",
"count",
":",
"count",
")",
"return",
"enumerator",
"if",
"with_scores",
"return",
"Enumerator",
".",
"new",
"do",
"|",
"yielder",
"|",
"loop",
"do",
"item",
",",
"=",
"enumerator",
".",
"next",
"yielder",
"<<",
"item",
"end",
"end",
"end"
] | Use redis-rb zscan_each method to iterate over particular keys
@return [Enumerator] base enumerator to iterate of the namespaced keys | [
"Use",
"redis",
"-",
"rb",
"zscan_each",
"method",
"to",
"iterate",
"over",
"particular",
"keys"
] | c97b45e7227f8ed9029f0effff352fc4d82dc3cb | https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/sorted_set.rb#L142-L151 | train |
teodor-pripoae/scalaroid | lib/scalaroid/replicated_dht.rb | Scalaroid.ReplicatedDHT.delete | def delete(key, timeout = 2000)
result_raw = @conn.call(:delete, [key, timeout])
result = @conn.class.process_result_delete(result_raw)
@lastDeleteResult = result[:results]
if result[:success] == true
return result[:ok]
elsif result[:success] == :timeout
raise TimeoutError.new(result_raw)
else
raise UnknownError.new(result_raw)
end
end | ruby | def delete(key, timeout = 2000)
result_raw = @conn.call(:delete, [key, timeout])
result = @conn.class.process_result_delete(result_raw)
@lastDeleteResult = result[:results]
if result[:success] == true
return result[:ok]
elsif result[:success] == :timeout
raise TimeoutError.new(result_raw)
else
raise UnknownError.new(result_raw)
end
end | [
"def",
"delete",
"(",
"key",
",",
"timeout",
"=",
"2000",
")",
"result_raw",
"=",
"@conn",
".",
"call",
"(",
":delete",
",",
"[",
"key",
",",
"timeout",
"]",
")",
"result",
"=",
"@conn",
".",
"class",
".",
"process_result_delete",
"(",
"result_raw",
")",
"@lastDeleteResult",
"=",
"result",
"[",
":results",
"]",
"if",
"result",
"[",
":success",
"]",
"==",
"true",
"return",
"result",
"[",
":ok",
"]",
"elsif",
"result",
"[",
":success",
"]",
"==",
":timeout",
"raise",
"TimeoutError",
".",
"new",
"(",
"result_raw",
")",
"else",
"raise",
"UnknownError",
".",
"new",
"(",
"result_raw",
")",
"end",
"end"
] | Create a new object using the given connection.
Tries to delete the value at the given key.
WARNING: This function can lead to inconsistent data (e.g. deleted items
can re-appear). Also when re-creating an item the version before the
delete can re-appear.
returns the number of successfully deleted items
use get_last_delete_result() to get more details | [
"Create",
"a",
"new",
"object",
"using",
"the",
"given",
"connection",
".",
"Tries",
"to",
"delete",
"the",
"value",
"at",
"the",
"given",
"key",
"."
] | 4e9e90e71ce3008da79a72eae40fe2f187580be2 | https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/replicated_dht.rb#L17-L28 | train |
vast/rokko | lib/rokko.rb | Rokko.Rokko.prettify | def prettify(blocks)
docs_blocks, code_blocks = blocks
# Combine all docs blocks into a single big markdown document with section
# dividers and run through the Markdown processor. Then split it back out
# into separate sections
rendered_html = self.class.renderer.render(docs_blocks.join("\n\n##### DIVIDER\n\n"))
rendered_html = ' ' if rendered_html == '' # ''.split() won't return anything useful
docs_html = rendered_html.split(/\n*<h5>DIVIDER<\/h5>\n*/m)
docs_html.zip(code_blocks)
end | ruby | def prettify(blocks)
docs_blocks, code_blocks = blocks
# Combine all docs blocks into a single big markdown document with section
# dividers and run through the Markdown processor. Then split it back out
# into separate sections
rendered_html = self.class.renderer.render(docs_blocks.join("\n\n##### DIVIDER\n\n"))
rendered_html = ' ' if rendered_html == '' # ''.split() won't return anything useful
docs_html = rendered_html.split(/\n*<h5>DIVIDER<\/h5>\n*/m)
docs_html.zip(code_blocks)
end | [
"def",
"prettify",
"(",
"blocks",
")",
"docs_blocks",
",",
"code_blocks",
"=",
"blocks",
"# Combine all docs blocks into a single big markdown document with section",
"# dividers and run through the Markdown processor. Then split it back out",
"# into separate sections",
"rendered_html",
"=",
"self",
".",
"class",
".",
"renderer",
".",
"render",
"(",
"docs_blocks",
".",
"join",
"(",
"\"\\n\\n##### DIVIDER\\n\\n\"",
")",
")",
"rendered_html",
"=",
"' '",
"if",
"rendered_html",
"==",
"''",
"# ''.split() won't return anything useful",
"docs_html",
"=",
"rendered_html",
".",
"split",
"(",
"/",
"\\n",
"\\/",
"\\n",
"/m",
")",
"docs_html",
".",
"zip",
"(",
"code_blocks",
")",
"end"
] | Take the result of `split` and apply Markdown formatting to comments | [
"Take",
"the",
"result",
"of",
"split",
"and",
"apply",
"Markdown",
"formatting",
"to",
"comments"
] | 37f451db3d0bd92151809fcaba5a88bb597bbcc0 | https://github.com/vast/rokko/blob/37f451db3d0bd92151809fcaba5a88bb597bbcc0/lib/rokko.rb#L150-L161 | train |
daily-scrum/domain_neutral | lib/domain_neutral/symbolized_class.rb | DomainNeutral.SymbolizedClass.method_missing | def method_missing(method, *args)
if method.to_s =~ /^(\w+)\?$/
v = self.class.find_by_symbol($1)
raise NameError unless v
other = v.to_sym
self.class.class_eval { define_method(method) { self.to_sym == other }}
return self.to_sym == other
end
super
end | ruby | def method_missing(method, *args)
if method.to_s =~ /^(\w+)\?$/
v = self.class.find_by_symbol($1)
raise NameError unless v
other = v.to_sym
self.class.class_eval { define_method(method) { self.to_sym == other }}
return self.to_sym == other
end
super
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
")",
"if",
"method",
".",
"to_s",
"=~",
"/",
"\\w",
"\\?",
"/",
"v",
"=",
"self",
".",
"class",
".",
"find_by_symbol",
"(",
"$1",
")",
"raise",
"NameError",
"unless",
"v",
"other",
"=",
"v",
".",
"to_sym",
"self",
".",
"class",
".",
"class_eval",
"{",
"define_method",
"(",
"method",
")",
"{",
"self",
".",
"to_sym",
"==",
"other",
"}",
"}",
"return",
"self",
".",
"to_sym",
"==",
"other",
"end",
"super",
"end"
] | Allow to test for a specific role or similar like Role.accountant? | [
"Allow",
"to",
"test",
"for",
"a",
"specific",
"role",
"or",
"similar",
"like",
"Role",
".",
"accountant?"
] | 9176915226c00ef3eff782c216922ee4ab4f06c5 | https://github.com/daily-scrum/domain_neutral/blob/9176915226c00ef3eff782c216922ee4ab4f06c5/lib/domain_neutral/symbolized_class.rb#L154-L163 | train |
daily-scrum/domain_neutral | lib/domain_neutral/symbolized_class.rb | DomainNeutral.SymbolizedClass.flush_cache | def flush_cache
Rails.cache.delete([self.class.name, symbol_was.to_s])
Rails.cache.delete([self.class.name, id])
end | ruby | def flush_cache
Rails.cache.delete([self.class.name, symbol_was.to_s])
Rails.cache.delete([self.class.name, id])
end | [
"def",
"flush_cache",
"Rails",
".",
"cache",
".",
"delete",
"(",
"[",
"self",
".",
"class",
".",
"name",
",",
"symbol_was",
".",
"to_s",
"]",
")",
"Rails",
".",
"cache",
".",
"delete",
"(",
"[",
"self",
".",
"class",
".",
"name",
",",
"id",
"]",
")",
"end"
] | Flushes cache if record is saved | [
"Flushes",
"cache",
"if",
"record",
"is",
"saved"
] | 9176915226c00ef3eff782c216922ee4ab4f06c5 | https://github.com/daily-scrum/domain_neutral/blob/9176915226c00ef3eff782c216922ee4ab4f06c5/lib/domain_neutral/symbolized_class.rb#L173-L176 | train |
koffeinfrei/technologist | lib/technologist/git_repository.rb | Technologist.GitRepository.find_blob | def find_blob(blob_name, current_tree = root_tree, &block)
blob = current_tree[blob_name]
if blob
blob = repository.lookup(blob[:oid])
if !block_given? || yield(blob)
return blob
end
end
# recurse
current_tree.each_tree do |sub_tree|
blob = find_blob(blob_name, repository.lookup(sub_tree[:oid]), &block)
break blob if blob
end
end | ruby | def find_blob(blob_name, current_tree = root_tree, &block)
blob = current_tree[blob_name]
if blob
blob = repository.lookup(blob[:oid])
if !block_given? || yield(blob)
return blob
end
end
# recurse
current_tree.each_tree do |sub_tree|
blob = find_blob(blob_name, repository.lookup(sub_tree[:oid]), &block)
break blob if blob
end
end | [
"def",
"find_blob",
"(",
"blob_name",
",",
"current_tree",
"=",
"root_tree",
",",
"&",
"block",
")",
"blob",
"=",
"current_tree",
"[",
"blob_name",
"]",
"if",
"blob",
"blob",
"=",
"repository",
".",
"lookup",
"(",
"blob",
"[",
":oid",
"]",
")",
"if",
"!",
"block_given?",
"||",
"yield",
"(",
"blob",
")",
"return",
"blob",
"end",
"end",
"# recurse",
"current_tree",
".",
"each_tree",
"do",
"|",
"sub_tree",
"|",
"blob",
"=",
"find_blob",
"(",
"blob_name",
",",
"repository",
".",
"lookup",
"(",
"sub_tree",
"[",
":oid",
"]",
")",
",",
"block",
")",
"break",
"blob",
"if",
"blob",
"end",
"end"
] | Recursively searches for the blob identified by `blob_name`
in all subdirectories in the repository. A blob is usually either
a file or a directory.
@param blob_name [String] the blob name
@param current_tree [Rugged::Tree] the git directory tree in which to look for the blob.
Defaults to the root tree (see `#root_tree`).
@yield [Rugged::Blob] Yields the found blob to an optional block.
If the block returns `true` it means that the file is found and
recursion is stopped. If the return value is `false`, the resursion continues.
@return [Rugged::Blob] The blob blob or nil if it cannot be found. | [
"Recursively",
"searches",
"for",
"the",
"blob",
"identified",
"by",
"blob_name",
"in",
"all",
"subdirectories",
"in",
"the",
"repository",
".",
"A",
"blob",
"is",
"usually",
"either",
"a",
"file",
"or",
"a",
"directory",
"."
] | 0fd1d5c07c6d73ac5a184b26ad6db40981388573 | https://github.com/koffeinfrei/technologist/blob/0fd1d5c07c6d73ac5a184b26ad6db40981388573/lib/technologist/git_repository.rb#L28-L43 | train |
neiljohari/scram | app/models/scram/target.rb | Scram.Target.conditions_hash_validations | def conditions_hash_validations
conditions.each do |comparator, mappings|
errors.add(:conditions, "can't use undefined comparators") unless Scram::DSL::Definitions::COMPARATORS.keys.include? comparator.to_sym
errors.add(:conditions, "comparators must have values of type Hash") unless mappings.is_a? Hash
end
end | ruby | def conditions_hash_validations
conditions.each do |comparator, mappings|
errors.add(:conditions, "can't use undefined comparators") unless Scram::DSL::Definitions::COMPARATORS.keys.include? comparator.to_sym
errors.add(:conditions, "comparators must have values of type Hash") unless mappings.is_a? Hash
end
end | [
"def",
"conditions_hash_validations",
"conditions",
".",
"each",
"do",
"|",
"comparator",
",",
"mappings",
"|",
"errors",
".",
"add",
"(",
":conditions",
",",
"\"can't use undefined comparators\"",
")",
"unless",
"Scram",
"::",
"DSL",
"::",
"Definitions",
"::",
"COMPARATORS",
".",
"keys",
".",
"include?",
"comparator",
".",
"to_sym",
"errors",
".",
"add",
"(",
":conditions",
",",
"\"comparators must have values of type Hash\"",
")",
"unless",
"mappings",
".",
"is_a?",
"Hash",
"end",
"end"
] | Validates that the conditions Hash follows an expected format | [
"Validates",
"that",
"the",
"conditions",
"Hash",
"follows",
"an",
"expected",
"format"
] | df3e48e9e9cab4b363b1370df5991319d21c256d | https://github.com/neiljohari/scram/blob/df3e48e9e9cab4b363b1370df5991319d21c256d/app/models/scram/target.rb#L75-L80 | train |
postmodern/data_paths | lib/data_paths/methods.rb | DataPaths.Methods.register_data_path | def register_data_path(path)
path = File.expand_path(path)
DataPaths.register(path)
data_paths << path unless data_paths.include?(path)
return path
end | ruby | def register_data_path(path)
path = File.expand_path(path)
DataPaths.register(path)
data_paths << path unless data_paths.include?(path)
return path
end | [
"def",
"register_data_path",
"(",
"path",
")",
"path",
"=",
"File",
".",
"expand_path",
"(",
"path",
")",
"DataPaths",
".",
"register",
"(",
"path",
")",
"data_paths",
"<<",
"path",
"unless",
"data_paths",
".",
"include?",
"(",
"path",
")",
"return",
"path",
"end"
] | Registers a path as a data directory.
@param [String] path
The path to add to {DataPaths.paths}.
@return [String]
The fully qualified form of the specified path.
@example
register_data_dir File.join(File.dirname(__FILE__),'..','..','..','data')
@raise [RuntimeError]
The specified path is not a directory.
@since 0.3.0 | [
"Registers",
"a",
"path",
"as",
"a",
"data",
"directory",
"."
] | 17938884593b458b90b591a353686945884749d6 | https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/methods.rb#L30-L37 | train |
postmodern/data_paths | lib/data_paths/methods.rb | DataPaths.Methods.unregister_data_path | def unregister_data_path(path)
path = File.expand_path(path)
self.data_paths.delete(path)
return DataPaths.unregister!(path)
end | ruby | def unregister_data_path(path)
path = File.expand_path(path)
self.data_paths.delete(path)
return DataPaths.unregister!(path)
end | [
"def",
"unregister_data_path",
"(",
"path",
")",
"path",
"=",
"File",
".",
"expand_path",
"(",
"path",
")",
"self",
".",
"data_paths",
".",
"delete",
"(",
"path",
")",
"return",
"DataPaths",
".",
"unregister!",
"(",
"path",
")",
"end"
] | Unregisters any matching data directories.
@param [String] path
The path to unregister.
@return [String]
The unregistered data path.
@since 0.3.0 | [
"Unregisters",
"any",
"matching",
"data",
"directories",
"."
] | 17938884593b458b90b591a353686945884749d6 | https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/methods.rb#L60-L65 | train |
postmodern/data_paths | lib/data_paths/methods.rb | DataPaths.Methods.unregister_data_paths | def unregister_data_paths
data_paths.each { |path| DataPaths.unregister!(path) }
data_paths.clear
return true
end | ruby | def unregister_data_paths
data_paths.each { |path| DataPaths.unregister!(path) }
data_paths.clear
return true
end | [
"def",
"unregister_data_paths",
"data_paths",
".",
"each",
"{",
"|",
"path",
"|",
"DataPaths",
".",
"unregister!",
"(",
"path",
")",
"}",
"data_paths",
".",
"clear",
"return",
"true",
"end"
] | Unregisters all previously registered data directories.
@return [true]
Specifies all data paths were successfully unregistered.
@since 0.3.0 | [
"Unregisters",
"all",
"previously",
"registered",
"data",
"directories",
"."
] | 17938884593b458b90b591a353686945884749d6 | https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/methods.rb#L85-L89 | train |
ktonon/code_node | spec/fixtures/activerecord/src/active_record/identity_map.rb | ActiveRecord.IdentityMap.reinit_with | def reinit_with(coder)
@attributes_cache = {}
dirty = @changed_attributes.keys
attributes = self.class.initialize_attributes(coder['attributes'].except(*dirty))
@attributes.update(attributes)
@changed_attributes.update(coder['attributes'].slice(*dirty))
@changed_attributes.delete_if{|k,v| v.eql? @attributes[k]}
run_callbacks :find
self
end | ruby | def reinit_with(coder)
@attributes_cache = {}
dirty = @changed_attributes.keys
attributes = self.class.initialize_attributes(coder['attributes'].except(*dirty))
@attributes.update(attributes)
@changed_attributes.update(coder['attributes'].slice(*dirty))
@changed_attributes.delete_if{|k,v| v.eql? @attributes[k]}
run_callbacks :find
self
end | [
"def",
"reinit_with",
"(",
"coder",
")",
"@attributes_cache",
"=",
"{",
"}",
"dirty",
"=",
"@changed_attributes",
".",
"keys",
"attributes",
"=",
"self",
".",
"class",
".",
"initialize_attributes",
"(",
"coder",
"[",
"'attributes'",
"]",
".",
"except",
"(",
"dirty",
")",
")",
"@attributes",
".",
"update",
"(",
"attributes",
")",
"@changed_attributes",
".",
"update",
"(",
"coder",
"[",
"'attributes'",
"]",
".",
"slice",
"(",
"dirty",
")",
")",
"@changed_attributes",
".",
"delete_if",
"{",
"|",
"k",
",",
"v",
"|",
"v",
".",
"eql?",
"@attributes",
"[",
"k",
"]",
"}",
"run_callbacks",
":find",
"self",
"end"
] | Reinitialize an Identity Map model object from +coder+.
+coder+ must contain the attributes necessary for initializing an empty
model object. | [
"Reinitialize",
"an",
"Identity",
"Map",
"model",
"object",
"from",
"+",
"coder",
"+",
".",
"+",
"coder",
"+",
"must",
"contain",
"the",
"attributes",
"necessary",
"for",
"initializing",
"an",
"empty",
"model",
"object",
"."
] | 48d5d1a7442d9cade602be4fb782a1b56c7677f5 | https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/identity_map.rb#L118-L129 | train |
m-nasser/discourse_mountable_sso | app/controllers/discourse_mountable_sso/discourse_sso_controller.rb | DiscourseMountableSso.DiscourseSsoController.sso | def sso
require "discourse_mountable_sso/single_sign_on"
sso = DiscourseMountableSso::SingleSignOn.parse(
((session[:discourse_mountable_sso] || {}).delete(:query_string).presence || request.query_string),
@config.secret
)
discourse_data = send @config.discourse_data_method
discourse_data.each_pair {|k,v| sso.send("#{ k }=", v) }
sso.sso_secret = @config.secret
yield sso if block_given?
redirect_to sso.to_url("#{@config.discourse_url}/session/sso_login")
end | ruby | def sso
require "discourse_mountable_sso/single_sign_on"
sso = DiscourseMountableSso::SingleSignOn.parse(
((session[:discourse_mountable_sso] || {}).delete(:query_string).presence || request.query_string),
@config.secret
)
discourse_data = send @config.discourse_data_method
discourse_data.each_pair {|k,v| sso.send("#{ k }=", v) }
sso.sso_secret = @config.secret
yield sso if block_given?
redirect_to sso.to_url("#{@config.discourse_url}/session/sso_login")
end | [
"def",
"sso",
"require",
"\"discourse_mountable_sso/single_sign_on\"",
"sso",
"=",
"DiscourseMountableSso",
"::",
"SingleSignOn",
".",
"parse",
"(",
"(",
"(",
"session",
"[",
":discourse_mountable_sso",
"]",
"||",
"{",
"}",
")",
".",
"delete",
"(",
":query_string",
")",
".",
"presence",
"||",
"request",
".",
"query_string",
")",
",",
"@config",
".",
"secret",
")",
"discourse_data",
"=",
"send",
"@config",
".",
"discourse_data_method",
"discourse_data",
".",
"each_pair",
"{",
"|",
"k",
",",
"v",
"|",
"sso",
".",
"send",
"(",
"\"#{ k }=\"",
",",
"v",
")",
"}",
"sso",
".",
"sso_secret",
"=",
"@config",
".",
"secret",
"yield",
"sso",
"if",
"block_given?",
"redirect_to",
"sso",
".",
"to_url",
"(",
"\"#{@config.discourse_url}/session/sso_login\"",
")",
"end"
] | ensures user must login | [
"ensures",
"user",
"must",
"login"
] | 0adb568ea0ec4c06a4dc65abb95a9badce460bf1 | https://github.com/m-nasser/discourse_mountable_sso/blob/0adb568ea0ec4c06a4dc65abb95a9badce460bf1/app/controllers/discourse_mountable_sso/discourse_sso_controller.rb#L6-L20 | train |
jtadeulopes/meme | lib/meme/info.rb | Meme.Info.followers | def followers(count=10)
count = 0 if count.is_a?(Symbol) && count == :all
query = "SELECT * FROM meme.followers(#{count}) WHERE owner_guid='#{self.guid}'"
parse = Request.parse(query)
if parse
results = parse['query']['results']
results.nil? ? nil : results['meme'].map {|m| Info.new(m)}
else
parse.error!
end
end | ruby | def followers(count=10)
count = 0 if count.is_a?(Symbol) && count == :all
query = "SELECT * FROM meme.followers(#{count}) WHERE owner_guid='#{self.guid}'"
parse = Request.parse(query)
if parse
results = parse['query']['results']
results.nil? ? nil : results['meme'].map {|m| Info.new(m)}
else
parse.error!
end
end | [
"def",
"followers",
"(",
"count",
"=",
"10",
")",
"count",
"=",
"0",
"if",
"count",
".",
"is_a?",
"(",
"Symbol",
")",
"&&",
"count",
"==",
":all",
"query",
"=",
"\"SELECT * FROM meme.followers(#{count}) WHERE owner_guid='#{self.guid}'\"",
"parse",
"=",
"Request",
".",
"parse",
"(",
"query",
")",
"if",
"parse",
"results",
"=",
"parse",
"[",
"'query'",
"]",
"[",
"'results'",
"]",
"results",
".",
"nil?",
"?",
"nil",
":",
"results",
"[",
"'meme'",
"]",
".",
"map",
"{",
"|",
"m",
"|",
"Info",
".",
"new",
"(",
"m",
")",
"}",
"else",
"parse",
".",
"error!",
"end",
"end"
] | Return user followers
Example:
# Search user
user = Meme::Info.find('jtadeulopes')
# Default
followers = user.followers
followers.count
=> 10
# Specify a count
followers = user.followers(100)
followers.count
=> 100
# All followers
followers = user.followers(:all)
followers.count
follower = followers.first
follower.name
=> "zigotto"
follower.url
=> "http://meme.yahoo.com/zigotto/" | [
"Return",
"user",
"followers"
] | dc3888c4af3c30d49053ec53f328187cb9255e88 | https://github.com/jtadeulopes/meme/blob/dc3888c4af3c30d49053ec53f328187cb9255e88/lib/meme/info.rb#L81-L91 | train |
jtadeulopes/meme | lib/meme/info.rb | Meme.Info.posts | def posts(quantity=0)
query = "SELECT * FROM meme.posts(#{quantity}) WHERE owner_guid='#{self.guid}';"
parse = Request.parse(query)
if parse
results = parse['query']['results']
results.nil? ? nil : results['post'].map {|m| Post.new(m)}
else
parse.error!
end
end | ruby | def posts(quantity=0)
query = "SELECT * FROM meme.posts(#{quantity}) WHERE owner_guid='#{self.guid}';"
parse = Request.parse(query)
if parse
results = parse['query']['results']
results.nil? ? nil : results['post'].map {|m| Post.new(m)}
else
parse.error!
end
end | [
"def",
"posts",
"(",
"quantity",
"=",
"0",
")",
"query",
"=",
"\"SELECT * FROM meme.posts(#{quantity}) WHERE owner_guid='#{self.guid}';\"",
"parse",
"=",
"Request",
".",
"parse",
"(",
"query",
")",
"if",
"parse",
"results",
"=",
"parse",
"[",
"'query'",
"]",
"[",
"'results'",
"]",
"results",
".",
"nil?",
"?",
"nil",
":",
"results",
"[",
"'post'",
"]",
".",
"map",
"{",
"|",
"m",
"|",
"Post",
".",
"new",
"(",
"m",
")",
"}",
"else",
"parse",
".",
"error!",
"end",
"end"
] | Retrieves all posts of an user | [
"Retrieves",
"all",
"posts",
"of",
"an",
"user"
] | dc3888c4af3c30d49053ec53f328187cb9255e88 | https://github.com/jtadeulopes/meme/blob/dc3888c4af3c30d49053ec53f328187cb9255e88/lib/meme/info.rb#L128-L137 | train |
sugaryourcoffee/syclink | lib/syclink/designer.rb | SycLink.Designer.add_links_from_file | def add_links_from_file(file)
File.foreach(file) do |line|
next if line.chomp.empty?
url, name, description, tag = line.chomp.split(';')
website.add_link(Link.new(url, { name: name,
description: description,
tag: tag }))
end
end | ruby | def add_links_from_file(file)
File.foreach(file) do |line|
next if line.chomp.empty?
url, name, description, tag = line.chomp.split(';')
website.add_link(Link.new(url, { name: name,
description: description,
tag: tag }))
end
end | [
"def",
"add_links_from_file",
"(",
"file",
")",
"File",
".",
"foreach",
"(",
"file",
")",
"do",
"|",
"line",
"|",
"next",
"if",
"line",
".",
"chomp",
".",
"empty?",
"url",
",",
"name",
",",
"description",
",",
"tag",
"=",
"line",
".",
"chomp",
".",
"split",
"(",
"';'",
")",
"website",
".",
"add_link",
"(",
"Link",
".",
"new",
"(",
"url",
",",
"{",
"name",
":",
"name",
",",
"description",
":",
"description",
",",
"tag",
":",
"tag",
"}",
")",
")",
"end",
"end"
] | Reads arguments from a CSV file and creates links accordingly. The links
are added to the websie | [
"Reads",
"arguments",
"from",
"a",
"CSV",
"file",
"and",
"creates",
"links",
"accordingly",
".",
"The",
"links",
"are",
"added",
"to",
"the",
"websie"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L33-L41 | train |
sugaryourcoffee/syclink | lib/syclink/designer.rb | SycLink.Designer.export | def export(format)
message = "to_#{format.downcase}"
if website.respond_to? message
website.send(message)
else
raise "cannot export to #{format}"
end
end | ruby | def export(format)
message = "to_#{format.downcase}"
if website.respond_to? message
website.send(message)
else
raise "cannot export to #{format}"
end
end | [
"def",
"export",
"(",
"format",
")",
"message",
"=",
"\"to_#{format.downcase}\"",
"if",
"website",
".",
"respond_to?",
"message",
"website",
".",
"send",
"(",
"message",
")",
"else",
"raise",
"\"cannot export to #{format}\"",
"end",
"end"
] | Export links to specified format | [
"Export",
"links",
"to",
"specified",
"format"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L51-L58 | train |
sugaryourcoffee/syclink | lib/syclink/designer.rb | SycLink.Designer.update_links_from_file | def update_links_from_file(file)
File.foreach(file) do |line|
next if line.chomp.empty?
url, name, description, tag = line.chomp.split(';')
website.find_links(url).first.update({ name: name,
description: description,
tag: tag })
end
end | ruby | def update_links_from_file(file)
File.foreach(file) do |line|
next if line.chomp.empty?
url, name, description, tag = line.chomp.split(';')
website.find_links(url).first.update({ name: name,
description: description,
tag: tag })
end
end | [
"def",
"update_links_from_file",
"(",
"file",
")",
"File",
".",
"foreach",
"(",
"file",
")",
"do",
"|",
"line",
"|",
"next",
"if",
"line",
".",
"chomp",
".",
"empty?",
"url",
",",
"name",
",",
"description",
",",
"tag",
"=",
"line",
".",
"chomp",
".",
"split",
"(",
"';'",
")",
"website",
".",
"find_links",
"(",
"url",
")",
".",
"first",
".",
"update",
"(",
"{",
"name",
":",
"name",
",",
"description",
":",
"description",
",",
"tag",
":",
"tag",
"}",
")",
"end",
"end"
] | Updates links read from a file | [
"Updates",
"links",
"read",
"from",
"a",
"file"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L97-L105 | train |
sugaryourcoffee/syclink | lib/syclink/designer.rb | SycLink.Designer.remove_links | def remove_links(urls)
urls.map { |url| list_links({ url: url }) }.flatten.compact.each do |link|
website.remove_link(link)
end
end | ruby | def remove_links(urls)
urls.map { |url| list_links({ url: url }) }.flatten.compact.each do |link|
website.remove_link(link)
end
end | [
"def",
"remove_links",
"(",
"urls",
")",
"urls",
".",
"map",
"{",
"|",
"url",
"|",
"list_links",
"(",
"{",
"url",
":",
"url",
"}",
")",
"}",
".",
"flatten",
".",
"compact",
".",
"each",
"do",
"|",
"link",
"|",
"website",
".",
"remove_link",
"(",
"link",
")",
"end",
"end"
] | Deletes one or more links from the website. Returns the deleted links.
Expects the links provided in an array | [
"Deletes",
"one",
"or",
"more",
"links",
"from",
"the",
"website",
".",
"Returns",
"the",
"deleted",
"links",
".",
"Expects",
"the",
"links",
"provided",
"in",
"an",
"array"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L114-L118 | train |
sugaryourcoffee/syclink | lib/syclink/designer.rb | SycLink.Designer.remove_links_from_file | def remove_links_from_file(file)
urls = File.foreach(file).map { |url| url.chomp unless url.empty? }
remove_links(urls)
end | ruby | def remove_links_from_file(file)
urls = File.foreach(file).map { |url| url.chomp unless url.empty? }
remove_links(urls)
end | [
"def",
"remove_links_from_file",
"(",
"file",
")",
"urls",
"=",
"File",
".",
"foreach",
"(",
"file",
")",
".",
"map",
"{",
"|",
"url",
"|",
"url",
".",
"chomp",
"unless",
"url",
".",
"empty?",
"}",
"remove_links",
"(",
"urls",
")",
"end"
] | Deletes links based on URLs that are provided in a file. Each URL has to
be in one line | [
"Deletes",
"links",
"based",
"on",
"URLs",
"that",
"are",
"provided",
"in",
"a",
"file",
".",
"Each",
"URL",
"has",
"to",
"be",
"in",
"one",
"line"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L122-L125 | train |
sugaryourcoffee/syclink | lib/syclink/designer.rb | SycLink.Designer.save_website | def save_website(directory)
File.open(yaml_file(directory, website.title), 'w') do |f|
YAML.dump(website, f)
end
end | ruby | def save_website(directory)
File.open(yaml_file(directory, website.title), 'w') do |f|
YAML.dump(website, f)
end
end | [
"def",
"save_website",
"(",
"directory",
")",
"File",
".",
"open",
"(",
"yaml_file",
"(",
"directory",
",",
"website",
".",
"title",
")",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"YAML",
".",
"dump",
"(",
"website",
",",
"f",
")",
"end",
"end"
] | Saves the website to the specified directory with the downcased name of
the website and the extension 'website'. The website is save as YAML | [
"Saves",
"the",
"website",
"to",
"the",
"specified",
"directory",
"with",
"the",
"downcased",
"name",
"of",
"the",
"website",
"and",
"the",
"extension",
"website",
".",
"The",
"website",
"is",
"save",
"as",
"YAML"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L129-L133 | train |
sugaryourcoffee/syclink | lib/syclink/designer.rb | SycLink.Designer.delete_website | def delete_website(directory)
if File.exists? yaml_file(directory, website.title)
FileUtils.rm(yaml_file(directory, website.title))
end
end | ruby | def delete_website(directory)
if File.exists? yaml_file(directory, website.title)
FileUtils.rm(yaml_file(directory, website.title))
end
end | [
"def",
"delete_website",
"(",
"directory",
")",
"if",
"File",
".",
"exists?",
"yaml_file",
"(",
"directory",
",",
"website",
".",
"title",
")",
"FileUtils",
".",
"rm",
"(",
"yaml_file",
"(",
"directory",
",",
"website",
".",
"title",
")",
")",
"end",
"end"
] | Deletes the website if it already exists | [
"Deletes",
"the",
"website",
"if",
"it",
"already",
"exists"
] | 941ee2045c946daa1e0db394eb643aa82c1254cc | https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L142-L146 | train |
cbrumelle/blueprintr | lib/blueprint-css/lib/blueprint/css_parser.rb | Blueprint.CSSParser.parse | def parse(data = nil)
data ||= @raw_data
# wrapper array holding hashes of css tags/rules
css_out = []
# clear initial spaces
data.strip_side_space!.strip_space!
# split on end of assignments
data.split('}').each_with_index do |assignments, index|
# split again to separate tags from rules
tags, styles = assignments.split('{').map{|a| a.strip_side_space!}
unless styles.blank?
# clean up tags and apply namespaces as needed
tags.strip_selector_space!
tags.gsub!(/\./, ".#{namespace}") unless namespace.blank?
# split on semicolon to iterate through each rule
rules = []
styles.split(';').each do |key_val_pair|
unless key_val_pair.nil?
# split by property/val and append to rules array with correct declaration
property, value = key_val_pair.split(':', 2).map{|kv| kv.strip_side_space!}
break unless property && value
rules << "#{property}:#{value};"
end
end
# now keeps track of index as hashes don't keep track of position (which will be fixed in Ruby 1.9)
css_out << {:tags => tags, :rules => rules.join, :idx => index} unless tags.blank? || rules.to_s.blank?
end
end
css_out
end | ruby | def parse(data = nil)
data ||= @raw_data
# wrapper array holding hashes of css tags/rules
css_out = []
# clear initial spaces
data.strip_side_space!.strip_space!
# split on end of assignments
data.split('}').each_with_index do |assignments, index|
# split again to separate tags from rules
tags, styles = assignments.split('{').map{|a| a.strip_side_space!}
unless styles.blank?
# clean up tags and apply namespaces as needed
tags.strip_selector_space!
tags.gsub!(/\./, ".#{namespace}") unless namespace.blank?
# split on semicolon to iterate through each rule
rules = []
styles.split(';').each do |key_val_pair|
unless key_val_pair.nil?
# split by property/val and append to rules array with correct declaration
property, value = key_val_pair.split(':', 2).map{|kv| kv.strip_side_space!}
break unless property && value
rules << "#{property}:#{value};"
end
end
# now keeps track of index as hashes don't keep track of position (which will be fixed in Ruby 1.9)
css_out << {:tags => tags, :rules => rules.join, :idx => index} unless tags.blank? || rules.to_s.blank?
end
end
css_out
end | [
"def",
"parse",
"(",
"data",
"=",
"nil",
")",
"data",
"||=",
"@raw_data",
"# wrapper array holding hashes of css tags/rules",
"css_out",
"=",
"[",
"]",
"# clear initial spaces",
"data",
".",
"strip_side_space!",
".",
"strip_space!",
"# split on end of assignments",
"data",
".",
"split",
"(",
"'}'",
")",
".",
"each_with_index",
"do",
"|",
"assignments",
",",
"index",
"|",
"# split again to separate tags from rules",
"tags",
",",
"styles",
"=",
"assignments",
".",
"split",
"(",
"'{'",
")",
".",
"map",
"{",
"|",
"a",
"|",
"a",
".",
"strip_side_space!",
"}",
"unless",
"styles",
".",
"blank?",
"# clean up tags and apply namespaces as needed",
"tags",
".",
"strip_selector_space!",
"tags",
".",
"gsub!",
"(",
"/",
"\\.",
"/",
",",
"\".#{namespace}\"",
")",
"unless",
"namespace",
".",
"blank?",
"# split on semicolon to iterate through each rule",
"rules",
"=",
"[",
"]",
"styles",
".",
"split",
"(",
"';'",
")",
".",
"each",
"do",
"|",
"key_val_pair",
"|",
"unless",
"key_val_pair",
".",
"nil?",
"# split by property/val and append to rules array with correct declaration",
"property",
",",
"value",
"=",
"key_val_pair",
".",
"split",
"(",
"':'",
",",
"2",
")",
".",
"map",
"{",
"|",
"kv",
"|",
"kv",
".",
"strip_side_space!",
"}",
"break",
"unless",
"property",
"&&",
"value",
"rules",
"<<",
"\"#{property}:#{value};\"",
"end",
"end",
"# now keeps track of index as hashes don't keep track of position (which will be fixed in Ruby 1.9)",
"css_out",
"<<",
"{",
":tags",
"=>",
"tags",
",",
":rules",
"=>",
"rules",
".",
"join",
",",
":idx",
"=>",
"index",
"}",
"unless",
"tags",
".",
"blank?",
"||",
"rules",
".",
"to_s",
".",
"blank?",
"end",
"end",
"css_out",
"end"
] | returns a hash of all CSS data passed
==== Options
* <tt>data</tt> -- CSS string; defaults to string passed into the constructor | [
"returns",
"a",
"hash",
"of",
"all",
"CSS",
"data",
"passed"
] | b414436f614a8d97d77b47b588ddcf3f5e61b6bd | https://github.com/cbrumelle/blueprintr/blob/b414436f614a8d97d77b47b588ddcf3f5e61b6bd/lib/blueprint-css/lib/blueprint/css_parser.rb#L26-L58 | train |
aleak/bender | lib/bender/cli.rb | Bender.CLI.load_enviroment | def load_enviroment(file = nil)
file ||= "."
if File.directory?(file) && File.exists?(File.expand_path("#{file}/config/environment.rb"))
require 'rails'
require File.expand_path("#{file}/config/environment.rb")
if defined?(::Rails) && ::Rails.respond_to?(:application)
# Rails 3
::Rails.application.eager_load!
elsif defined?(::Rails::Initializer)
# Rails 2.3
$rails_rake_task = false
::Rails::Initializer.run :load_application_classes
end
elsif File.file?(file)
require File.expand_path(file)
end
end | ruby | def load_enviroment(file = nil)
file ||= "."
if File.directory?(file) && File.exists?(File.expand_path("#{file}/config/environment.rb"))
require 'rails'
require File.expand_path("#{file}/config/environment.rb")
if defined?(::Rails) && ::Rails.respond_to?(:application)
# Rails 3
::Rails.application.eager_load!
elsif defined?(::Rails::Initializer)
# Rails 2.3
$rails_rake_task = false
::Rails::Initializer.run :load_application_classes
end
elsif File.file?(file)
require File.expand_path(file)
end
end | [
"def",
"load_enviroment",
"(",
"file",
"=",
"nil",
")",
"file",
"||=",
"\".\"",
"if",
"File",
".",
"directory?",
"(",
"file",
")",
"&&",
"File",
".",
"exists?",
"(",
"File",
".",
"expand_path",
"(",
"\"#{file}/config/environment.rb\"",
")",
")",
"require",
"'rails'",
"require",
"File",
".",
"expand_path",
"(",
"\"#{file}/config/environment.rb\"",
")",
"if",
"defined?",
"(",
"::",
"Rails",
")",
"&&",
"::",
"Rails",
".",
"respond_to?",
"(",
":application",
")",
"# Rails 3",
"::",
"Rails",
".",
"application",
".",
"eager_load!",
"elsif",
"defined?",
"(",
"::",
"Rails",
"::",
"Initializer",
")",
"# Rails 2.3",
"$rails_rake_task",
"=",
"false",
"::",
"Rails",
"::",
"Initializer",
".",
"run",
":load_application_classes",
"end",
"elsif",
"File",
".",
"file?",
"(",
"file",
")",
"require",
"File",
".",
"expand_path",
"(",
"file",
")",
"end",
"end"
] | Loads the environment from the given configuration file.
@api private | [
"Loads",
"the",
"environment",
"from",
"the",
"given",
"configuration",
"file",
"."
] | 5892e6ffce84fc531d8cbf452b2676b4d012ab09 | https://github.com/aleak/bender/blob/5892e6ffce84fc531d8cbf452b2676b4d012ab09/lib/bender/cli.rb#L56-L73 | train |
michaeledgar/amp-front | lib/amp-front/third_party/maruku/structures_iterators.rb | MaRuKu.MDElement.each_element | def each_element(e_node_type=nil, &block)
@children.each do |c|
if c.kind_of? MDElement
if (not e_node_type) || (e_node_type == c.node_type)
block.call c
end
c.each_element(e_node_type, &block)
end
end
end | ruby | def each_element(e_node_type=nil, &block)
@children.each do |c|
if c.kind_of? MDElement
if (not e_node_type) || (e_node_type == c.node_type)
block.call c
end
c.each_element(e_node_type, &block)
end
end
end | [
"def",
"each_element",
"(",
"e_node_type",
"=",
"nil",
",",
"&",
"block",
")",
"@children",
".",
"each",
"do",
"|",
"c",
"|",
"if",
"c",
".",
"kind_of?",
"MDElement",
"if",
"(",
"not",
"e_node_type",
")",
"||",
"(",
"e_node_type",
"==",
"c",
".",
"node_type",
")",
"block",
".",
"call",
"c",
"end",
"c",
".",
"each_element",
"(",
"e_node_type",
",",
"block",
")",
"end",
"end",
"end"
] | Yields to each element of specified node_type
All elements if e_node_type is nil. | [
"Yields",
"to",
"each",
"element",
"of",
"specified",
"node_type",
"All",
"elements",
"if",
"e_node_type",
"is",
"nil",
"."
] | d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9 | https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/structures_iterators.rb#L28-L37 | train |
michaeledgar/amp-front | lib/amp-front/third_party/maruku/structures_iterators.rb | MaRuKu.MDElement.replace_each_string | def replace_each_string(&block)
for c in @children
if c.kind_of? MDElement
c.replace_each_string(&block)
end
end
processed = []
until @children.empty?
c = @children.shift
if c.kind_of? String
result = block.call(c)
[*result].each do |e| processed << e end
else
processed << c
end
end
@children = processed
end | ruby | def replace_each_string(&block)
for c in @children
if c.kind_of? MDElement
c.replace_each_string(&block)
end
end
processed = []
until @children.empty?
c = @children.shift
if c.kind_of? String
result = block.call(c)
[*result].each do |e| processed << e end
else
processed << c
end
end
@children = processed
end | [
"def",
"replace_each_string",
"(",
"&",
"block",
")",
"for",
"c",
"in",
"@children",
"if",
"c",
".",
"kind_of?",
"MDElement",
"c",
".",
"replace_each_string",
"(",
"block",
")",
"end",
"end",
"processed",
"=",
"[",
"]",
"until",
"@children",
".",
"empty?",
"c",
"=",
"@children",
".",
"shift",
"if",
"c",
".",
"kind_of?",
"String",
"result",
"=",
"block",
".",
"call",
"(",
"c",
")",
"[",
"result",
"]",
".",
"each",
"do",
"|",
"e",
"|",
"processed",
"<<",
"e",
"end",
"else",
"processed",
"<<",
"c",
"end",
"end",
"@children",
"=",
"processed",
"end"
] | Apply passed block to each String in the hierarchy. | [
"Apply",
"passed",
"block",
"to",
"each",
"String",
"in",
"the",
"hierarchy",
"."
] | d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9 | https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/structures_iterators.rb#L40-L58 | train |
philou/rspecproxies | lib/rspecproxies/proxies.rb | RSpecProxies.Proxies.and_before_calling_original | def and_before_calling_original
self.and_wrap_original do |m, *args, &block|
yield *args
m.call(*args, &block)
end
end | ruby | def and_before_calling_original
self.and_wrap_original do |m, *args, &block|
yield *args
m.call(*args, &block)
end
end | [
"def",
"and_before_calling_original",
"self",
".",
"and_wrap_original",
"do",
"|",
"m",
",",
"*",
"args",
",",
"&",
"block",
"|",
"yield",
"args",
"m",
".",
"call",
"(",
"args",
",",
"block",
")",
"end",
"end"
] | Will call the given block with all the actual arguments every time
the method is called | [
"Will",
"call",
"the",
"given",
"block",
"with",
"all",
"the",
"actual",
"arguments",
"every",
"time",
"the",
"method",
"is",
"called"
] | 7bb32654f1c4d0316e9f89161a95583333a3a66f | https://github.com/philou/rspecproxies/blob/7bb32654f1c4d0316e9f89161a95583333a3a66f/lib/rspecproxies/proxies.rb#L8-L13 | train |
philou/rspecproxies | lib/rspecproxies/proxies.rb | RSpecProxies.Proxies.and_after_calling_original | def and_after_calling_original
self.and_wrap_original do |m, *args, &block|
result = m.call(*args, &block)
yield result
result
end
end | ruby | def and_after_calling_original
self.and_wrap_original do |m, *args, &block|
result = m.call(*args, &block)
yield result
result
end
end | [
"def",
"and_after_calling_original",
"self",
".",
"and_wrap_original",
"do",
"|",
"m",
",",
"*",
"args",
",",
"&",
"block",
"|",
"result",
"=",
"m",
".",
"call",
"(",
"args",
",",
"block",
")",
"yield",
"result",
"result",
"end",
"end"
] | Will call the given block with it's result every time the method
returns | [
"Will",
"call",
"the",
"given",
"block",
"with",
"it",
"s",
"result",
"every",
"time",
"the",
"method",
"returns"
] | 7bb32654f1c4d0316e9f89161a95583333a3a66f | https://github.com/philou/rspecproxies/blob/7bb32654f1c4d0316e9f89161a95583333a3a66f/lib/rspecproxies/proxies.rb#L17-L23 | train |
pablogonzalezalba/acts_as_integer_infinitable | lib/acts_as_integer_infinitable.rb | ActsAsIntegerInfinitable.ClassMethods.acts_as_integer_infinitable | def acts_as_integer_infinitable(fields, options = {})
options[:infinity_value] = -1 unless options.key? :infinity_value
fields.each do |field|
define_method("#{field}=") do |value|
int_value = value == Float::INFINITY ? options[:infinity_value] : value
write_attribute(field, int_value)
end
define_method("#{field}") do
value = read_attribute(field)
value == options[:infinity_value] ? Float::INFINITY : value
end
end
end | ruby | def acts_as_integer_infinitable(fields, options = {})
options[:infinity_value] = -1 unless options.key? :infinity_value
fields.each do |field|
define_method("#{field}=") do |value|
int_value = value == Float::INFINITY ? options[:infinity_value] : value
write_attribute(field, int_value)
end
define_method("#{field}") do
value = read_attribute(field)
value == options[:infinity_value] ? Float::INFINITY : value
end
end
end | [
"def",
"acts_as_integer_infinitable",
"(",
"fields",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":infinity_value",
"]",
"=",
"-",
"1",
"unless",
"options",
".",
"key?",
":infinity_value",
"fields",
".",
"each",
"do",
"|",
"field",
"|",
"define_method",
"(",
"\"#{field}=\"",
")",
"do",
"|",
"value",
"|",
"int_value",
"=",
"value",
"==",
"Float",
"::",
"INFINITY",
"?",
"options",
"[",
":infinity_value",
"]",
":",
"value",
"write_attribute",
"(",
"field",
",",
"int_value",
")",
"end",
"define_method",
"(",
"\"#{field}\"",
")",
"do",
"value",
"=",
"read_attribute",
"(",
"field",
")",
"value",
"==",
"options",
"[",
":infinity_value",
"]",
"?",
"Float",
"::",
"INFINITY",
":",
"value",
"end",
"end",
"end"
] | Allows the fields to store an Infinity value.
Overrides the setter and getter of those fields in order to capture
and return Infinity when appropiate.
Then you can use it as any other value and get the desired result, like
decrementing, incrementing, comparing with <, >, ==, etc.
Example:
class LibrarySubscription < ActiveRecord::Base
acts_as_integer_infinitable [:available_books]
def rent_book
# Do other things...
self.available_books -= 1
save
end
end
> simple_subscription = LibrarySubscription.new(available_books: 5)
> simple_subscription.available_books
=> 5
> simple_subscription.rent_book
> simple_subscription.available_books
=> 4
> complete_subscription = LibrarySubscription.new(available_books: Float::INFINITY)
> long_subscription.available_books
=> Infinity
> long_subscription.rent_book
> long_subscription.available_books
=> Infinity
== Parameters
* +fields+ - An Array with the fields that will be infinitable. They have
to be integers in the database.
== Options
* +:infinity_value+ - The value that will be converted to Infinity.
Default: -1. Another popular value is `nil`. | [
"Allows",
"the",
"fields",
"to",
"store",
"an",
"Infinity",
"value",
"."
] | 09dc8025a27524ce81fba2dca8a9263056e39cda | https://github.com/pablogonzalezalba/acts_as_integer_infinitable/blob/09dc8025a27524ce81fba2dca8a9263056e39cda/lib/acts_as_integer_infinitable.rb#L48-L62 | train |
caruby/core | lib/caruby/database/persistence_service.rb | CaRuby.PersistenceService.query | def query(template_or_hql, *path)
String === template_or_hql ? query_hql(template_or_hql) : query_template(template_or_hql, path)
end | ruby | def query(template_or_hql, *path)
String === template_or_hql ? query_hql(template_or_hql) : query_template(template_or_hql, path)
end | [
"def",
"query",
"(",
"template_or_hql",
",",
"*",
"path",
")",
"String",
"===",
"template_or_hql",
"?",
"query_hql",
"(",
"template_or_hql",
")",
":",
"query_template",
"(",
"template_or_hql",
",",
"path",
")",
"end"
] | Creates a new PersistenceService with the specified application service name and options.
@param [String] the caBIG application service name
@param [{Symbol => Object}] opts the options
@option opts [String] :host the service host (default +localhost+)
@option opts [String] :version the caTissue version identifier
Database access methods
Returns an array of objects fetched from the database which match the given template_or_hql.
If template_or_hql is a String, then the HQL is submitted to the service.
Otherwise, the template_or_hql is a query template domain
object following the given attribute path. The query condition is determined by the values set in the
template. Every non-nil attribute in the template is used as a select condition.
@quirk caCORE this method returns the direct result of calling the +caCORE+ application service
search method. Calling reference attributes of this result is broken by +caCORE+ design. | [
"Creates",
"a",
"new",
"PersistenceService",
"with",
"the",
"specified",
"application",
"service",
"name",
"and",
"options",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistence_service.rb#L44-L46 | train |
caruby/core | lib/caruby/database/persistence_service.rb | CaRuby.PersistenceService.query_hql | def query_hql(hql)
logger.debug { "Building HQLCriteria..." }
criteria = HQLCriteria.new(hql)
target = hql[/from\s+(\S+)/i, 1]
raise DatabaseError.new("HQL does not contain a FROM clause: #{hql}") unless target
logger.debug { "Submitting search on target class #{target} with the following HQL:\n #{hql}" }
begin
dispatch { |svc| svc.query(criteria, target) }
rescue Exception => e
logger.error("Error querying on HQL - #{$!}:\n#{hql}")
raise e
end
end | ruby | def query_hql(hql)
logger.debug { "Building HQLCriteria..." }
criteria = HQLCriteria.new(hql)
target = hql[/from\s+(\S+)/i, 1]
raise DatabaseError.new("HQL does not contain a FROM clause: #{hql}") unless target
logger.debug { "Submitting search on target class #{target} with the following HQL:\n #{hql}" }
begin
dispatch { |svc| svc.query(criteria, target) }
rescue Exception => e
logger.error("Error querying on HQL - #{$!}:\n#{hql}")
raise e
end
end | [
"def",
"query_hql",
"(",
"hql",
")",
"logger",
".",
"debug",
"{",
"\"Building HQLCriteria...\"",
"}",
"criteria",
"=",
"HQLCriteria",
".",
"new",
"(",
"hql",
")",
"target",
"=",
"hql",
"[",
"/",
"\\s",
"\\S",
"/i",
",",
"1",
"]",
"raise",
"DatabaseError",
".",
"new",
"(",
"\"HQL does not contain a FROM clause: #{hql}\"",
")",
"unless",
"target",
"logger",
".",
"debug",
"{",
"\"Submitting search on target class #{target} with the following HQL:\\n #{hql}\"",
"}",
"begin",
"dispatch",
"{",
"|",
"svc",
"|",
"svc",
".",
"query",
"(",
"criteria",
",",
"target",
")",
"}",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"(",
"\"Error querying on HQL - #{$!}:\\n#{hql}\"",
")",
"raise",
"e",
"end",
"end"
] | Dispatches the given HQL to the application service.
@quirk caCORE query target parameter is necessary for caCORE 3.x but deprecated in caCORE 4+.
@param [String] hql the HQL to submit | [
"Dispatches",
"the",
"given",
"HQL",
"to",
"the",
"application",
"service",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistence_service.rb#L105-L117 | train |
caruby/core | lib/caruby/database/persistence_service.rb | CaRuby.PersistenceService.query_association_post_caCORE_v4 | def query_association_post_caCORE_v4(obj, attribute)
assn = obj.class.association(attribute)
begin
result = dispatch { |svc| svc.association(obj, assn) }
rescue Exception => e
logger.error("Error fetching association #{obj} - #{e}")
raise
end
end | ruby | def query_association_post_caCORE_v4(obj, attribute)
assn = obj.class.association(attribute)
begin
result = dispatch { |svc| svc.association(obj, assn) }
rescue Exception => e
logger.error("Error fetching association #{obj} - #{e}")
raise
end
end | [
"def",
"query_association_post_caCORE_v4",
"(",
"obj",
",",
"attribute",
")",
"assn",
"=",
"obj",
".",
"class",
".",
"association",
"(",
"attribute",
")",
"begin",
"result",
"=",
"dispatch",
"{",
"|",
"svc",
"|",
"svc",
".",
"association",
"(",
"obj",
",",
"assn",
")",
"}",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"(",
"\"Error fetching association #{obj} - #{e}\"",
")",
"raise",
"end",
"end"
] | Returns an array of domain objects associated with obj through the specified attribute.
This method uses the +caCORE+ v. 4+ getAssociation application service method.
*Note*: this method is only available for caBIG application services which implement +getAssociation+.
Currently, this includes +caCORE+ v. 4.0 and above.
This method raises a DatabaseError if the application service does not implement +getAssociation+.
Raises DatabaseError if the attribute is not an a domain attribute or the associated objects were not fetched. | [
"Returns",
"an",
"array",
"of",
"domain",
"objects",
"associated",
"with",
"obj",
"through",
"the",
"specified",
"attribute",
".",
"This",
"method",
"uses",
"the",
"+",
"caCORE",
"+",
"v",
".",
"4",
"+",
"getAssociation",
"application",
"service",
"method",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistence_service.rb#L152-L160 | train |
X0nic/guard-yardstick | lib/guard/yardstick.rb | Guard.Yardstick.run_partially | def run_partially(paths)
return if paths.empty?
displayed_paths = paths.map { |path| smart_path(path) }
UI.info "Inspecting Yarddocs: #{displayed_paths.join(' ')}"
inspect_with_yardstick(path: paths)
end | ruby | def run_partially(paths)
return if paths.empty?
displayed_paths = paths.map { |path| smart_path(path) }
UI.info "Inspecting Yarddocs: #{displayed_paths.join(' ')}"
inspect_with_yardstick(path: paths)
end | [
"def",
"run_partially",
"(",
"paths",
")",
"return",
"if",
"paths",
".",
"empty?",
"displayed_paths",
"=",
"paths",
".",
"map",
"{",
"|",
"path",
"|",
"smart_path",
"(",
"path",
")",
"}",
"UI",
".",
"info",
"\"Inspecting Yarddocs: #{displayed_paths.join(' ')}\"",
"inspect_with_yardstick",
"(",
"path",
":",
"paths",
")",
"end"
] | Runs yardstick on a partial set of paths passed in by guard
@api private
@return [Void] | [
"Runs",
"yardstick",
"on",
"a",
"partial",
"set",
"of",
"paths",
"passed",
"in",
"by",
"guard"
] | 0a52568e1bf1458e611fad2367c41cd1728a9444 | https://github.com/X0nic/guard-yardstick/blob/0a52568e1bf1458e611fad2367c41cd1728a9444/lib/guard/yardstick.rb#L68-L75 | train |
X0nic/guard-yardstick | lib/guard/yardstick.rb | Guard.Yardstick.inspect_with_yardstick | def inspect_with_yardstick(yardstick_options = {})
config = ::Yardstick::Config.coerce(yardstick_config(yardstick_options))
measurements = ::Yardstick.measure(config)
measurements.puts
rescue StandardError => error
UI.error 'The following exception occurred while running ' \
"guard-yardstick: #{error.backtrace.first} " \
"#{error.message} (#{error.class.name})"
end | ruby | def inspect_with_yardstick(yardstick_options = {})
config = ::Yardstick::Config.coerce(yardstick_config(yardstick_options))
measurements = ::Yardstick.measure(config)
measurements.puts
rescue StandardError => error
UI.error 'The following exception occurred while running ' \
"guard-yardstick: #{error.backtrace.first} " \
"#{error.message} (#{error.class.name})"
end | [
"def",
"inspect_with_yardstick",
"(",
"yardstick_options",
"=",
"{",
"}",
")",
"config",
"=",
"::",
"Yardstick",
"::",
"Config",
".",
"coerce",
"(",
"yardstick_config",
"(",
"yardstick_options",
")",
")",
"measurements",
"=",
"::",
"Yardstick",
".",
"measure",
"(",
"config",
")",
"measurements",
".",
"puts",
"rescue",
"StandardError",
"=>",
"error",
"UI",
".",
"error",
"'The following exception occurred while running '",
"\"guard-yardstick: #{error.backtrace.first} \"",
"\"#{error.message} (#{error.class.name})\"",
"end"
] | Runs yardstick and outputs results to STDOUT
@api private
@return [Void] | [
"Runs",
"yardstick",
"and",
"outputs",
"results",
"to",
"STDOUT"
] | 0a52568e1bf1458e611fad2367c41cd1728a9444 | https://github.com/X0nic/guard-yardstick/blob/0a52568e1bf1458e611fad2367c41cd1728a9444/lib/guard/yardstick.rb#L81-L89 | train |
X0nic/guard-yardstick | lib/guard/yardstick.rb | Guard.Yardstick.yardstick_config | def yardstick_config(extra_options = {})
return options unless options[:config]
yardstick_options = YAML.load_file(options[:config])
yardstick_options.merge(extra_options)
end | ruby | def yardstick_config(extra_options = {})
return options unless options[:config]
yardstick_options = YAML.load_file(options[:config])
yardstick_options.merge(extra_options)
end | [
"def",
"yardstick_config",
"(",
"extra_options",
"=",
"{",
"}",
")",
"return",
"options",
"unless",
"options",
"[",
":config",
"]",
"yardstick_options",
"=",
"YAML",
".",
"load_file",
"(",
"options",
"[",
":config",
"]",
")",
"yardstick_options",
".",
"merge",
"(",
"extra_options",
")",
"end"
] | Merge further options with yardstick config file.
@api private
@return [Hash] Hash of options for yardstick measurement | [
"Merge",
"further",
"options",
"with",
"yardstick",
"config",
"file",
"."
] | 0a52568e1bf1458e611fad2367c41cd1728a9444 | https://github.com/X0nic/guard-yardstick/blob/0a52568e1bf1458e611fad2367c41cd1728a9444/lib/guard/yardstick.rb#L107-L112 | train |
blambeau/domain | lib/domain/api.rb | Domain.API.domain_error! | def domain_error!(first, *args)
first = [first]+args unless args.empty?
raise TypeError, "Can't convert `#{first.inspect}` into #{self}", caller
end | ruby | def domain_error!(first, *args)
first = [first]+args unless args.empty?
raise TypeError, "Can't convert `#{first.inspect}` into #{self}", caller
end | [
"def",
"domain_error!",
"(",
"first",
",",
"*",
"args",
")",
"first",
"=",
"[",
"first",
"]",
"+",
"args",
"unless",
"args",
".",
"empty?",
"raise",
"TypeError",
",",
"\"Can't convert `#{first.inspect}` into #{self}\"",
",",
"caller",
"end"
] | Raises a type error for `args`.
@param [Array] args
arguments passed to `new` or another factory method
@raise TypeError
@api protected | [
"Raises",
"a",
"type",
"error",
"for",
"args",
"."
] | 3fd010cbf2e156013e0ea9afa608ba9b44e7bc75 | https://github.com/blambeau/domain/blob/3fd010cbf2e156013e0ea9afa608ba9b44e7bc75/lib/domain/api.rb#L11-L14 | train |
checkdin/checkdin-ruby | lib/checkdin/user_bridge.rb | Checkdin.UserBridge.login_url | def login_url options
email = options.delete(:email) or raise ArgumentError.new("No :email passed for user")
user_identifier = options.delete(:user_identifier) or raise ArgumentError.new("No :user_identifier passed for user")
authenticated_parameters = build_authenticated_parameters(email, user_identifier, options)
[checkdin_landing_url, authenticated_parameters.to_query].join
end | ruby | def login_url options
email = options.delete(:email) or raise ArgumentError.new("No :email passed for user")
user_identifier = options.delete(:user_identifier) or raise ArgumentError.new("No :user_identifier passed for user")
authenticated_parameters = build_authenticated_parameters(email, user_identifier, options)
[checkdin_landing_url, authenticated_parameters.to_query].join
end | [
"def",
"login_url",
"options",
"email",
"=",
"options",
".",
"delete",
"(",
":email",
")",
"or",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"No :email passed for user\"",
")",
"user_identifier",
"=",
"options",
".",
"delete",
"(",
":user_identifier",
")",
"or",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"No :user_identifier passed for user\"",
")",
"authenticated_parameters",
"=",
"build_authenticated_parameters",
"(",
"email",
",",
"user_identifier",
",",
"options",
")",
"[",
"checkdin_landing_url",
",",
"authenticated_parameters",
".",
"to_query",
"]",
".",
"join",
"end"
] | Used to build the authenticated parameters for logging in an end-user on
checkd.in via a redirect.
options - a hash with a the following values defined:
:client_identifier - REQUIRED, the same client identifier used when accessing the regular
API methods.
:bridge_secret - REQUIRED, previously agreed upon shared secret for the user bridge.
This is NOT the shared secret used for accessing the backend API,
please do not confuse the two.
:checkdin_landing_url - OPTIONAL, the value will default to CHECKDIN_DEFAULT_LANDING
if not given. Please set this value as directed by Checkd In.
Examples
bridge = Checkdin::UserBridge.new(:client_identifier => 'YOUR_ASSIGNED_CLIENT_IDENTIFIER',
:bridge_secret => 'YOUR_ASSIGNED_BRIDGE_SECRET')
redirect_to bridge.login_url(:email => '[email protected]',
:user_identifier => '112-fixed-user-identifier')
Public: Build a full signed url for logging a specific user into checkd.in. Notice:
you MUST NOT reuse the result of this method, as it expires automatically based on time.
options - a hash with the following values defined:
email - REQUIRED, email address of the user, MAY have different values for a given
user over time.
user_identifier - REQUIRED, your unique identifier for the user, MUST NOT change over time.
authentication_action - OPTIONAL, the given action will be performed immediately,
and the user redirected back to your site afterwards.
referral_token - OPTIONAL, the referral token of the user that referred the user being created.
first_name - OPTIONAL
last_name - OPTIONAL
gender - OPTIONAL, format of male or female
birth_date - OPTIONAL, YYYY-MM-DD format
username - OPTIONAL
mobile_number - OPTIONAL, XXXYYYZZZZ format
postal_code_text - OPTIONAL, XXXXX format
classification - OPTIONAL, the internal group or classification a user belongs to
delivery_email - OPTIONAL, whether a user should receive email notifications
delivery_sms - OPTIONAL, whether a user should receive sms notifications
campaign_id - OPTIONAL, automatically join a user to this campaign, rewarding existing known actions
Returns a URL you can use for redirecting a user. Notice this will expire, so it should
be generated and used only when a user actually wants to log into checkd.in. | [
"Used",
"to",
"build",
"the",
"authenticated",
"parameters",
"for",
"logging",
"in",
"an",
"end",
"-",
"user",
"on",
"checkd",
".",
"in",
"via",
"a",
"redirect",
"."
] | c3c4b38b0f8c710e1f805100dcf3a70649215b48 | https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/user_bridge.rb#L59-L66 | train |
yogahp/meser_ongkir | lib/meser_ongkir/api.rb | MeserOngkir.Api.call | def call
url = URI(api_url)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
url.query = URI.encode_www_form(@params) if @params
request = Net::HTTP::Get.new(url)
request['key'] = ENV['MESER_ONGKIR_API_KEY']
http.request(request)
end | ruby | def call
url = URI(api_url)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
url.query = URI.encode_www_form(@params) if @params
request = Net::HTTP::Get.new(url)
request['key'] = ENV['MESER_ONGKIR_API_KEY']
http.request(request)
end | [
"def",
"call",
"url",
"=",
"URI",
"(",
"api_url",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"url",
".",
"host",
",",
"url",
".",
"port",
")",
"http",
".",
"use_ssl",
"=",
"true",
"http",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_NONE",
"url",
".",
"query",
"=",
"URI",
".",
"encode_www_form",
"(",
"@params",
")",
"if",
"@params",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"url",
")",
"request",
"[",
"'key'",
"]",
"=",
"ENV",
"[",
"'MESER_ONGKIR_API_KEY'",
"]",
"http",
".",
"request",
"(",
"request",
")",
"end"
] | Creating new object
@param
account_type [String] it could be :starter
main_path [String] it could be :city, :province
params [Hash] it could be { id: id city / id province, province: id province }
@example
MeserOngkir::Api.new(account_type, main_path, params) | [
"Creating",
"new",
"object"
] | b9fb3a925098c169793d1893ef00a0f2af222c16 | https://github.com/yogahp/meser_ongkir/blob/b9fb3a925098c169793d1893ef00a0f2af222c16/lib/meser_ongkir/api.rb#L24-L35 | train |
tomas-stefano/rspec-i18n | lib/spec-i18n/matchers/method_missing.rb | Spec.Matchers.method_missing | def method_missing(sym, *args, &block) # :nodoc:\
matchers = natural_language.keywords['matchers']
be_word = matchers['be'] if matchers
sym = be_to_english(sym, be_word)
return Matchers::BePredicate.new(sym, *args, &block) if be_predicate?(sym)
return Matchers::Has.new(sym, *args, &block) if have_predicate?(sym)
end | ruby | def method_missing(sym, *args, &block) # :nodoc:\
matchers = natural_language.keywords['matchers']
be_word = matchers['be'] if matchers
sym = be_to_english(sym, be_word)
return Matchers::BePredicate.new(sym, *args, &block) if be_predicate?(sym)
return Matchers::Has.new(sym, *args, &block) if have_predicate?(sym)
end | [
"def",
"method_missing",
"(",
"sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"# :nodoc:\\",
"matchers",
"=",
"natural_language",
".",
"keywords",
"[",
"'matchers'",
"]",
"be_word",
"=",
"matchers",
"[",
"'be'",
"]",
"if",
"matchers",
"sym",
"=",
"be_to_english",
"(",
"sym",
",",
"be_word",
")",
"return",
"Matchers",
"::",
"BePredicate",
".",
"new",
"(",
"sym",
",",
"args",
",",
"block",
")",
"if",
"be_predicate?",
"(",
"sym",
")",
"return",
"Matchers",
"::",
"Has",
".",
"new",
"(",
"sym",
",",
"args",
",",
"block",
")",
"if",
"have_predicate?",
"(",
"sym",
")",
"end"
] | Method Missing that returns Predicate for the respective sym word
Search the translate be word in the languages.yml for the rspec-i18n try
to comunicate with the Rspec | [
"Method",
"Missing",
"that",
"returns",
"Predicate",
"for",
"the",
"respective",
"sym",
"word",
"Search",
"the",
"translate",
"be",
"word",
"in",
"the",
"languages",
".",
"yml",
"for",
"the",
"rspec",
"-",
"i18n",
"try",
"to",
"comunicate",
"with",
"the",
"Rspec"
] | 4383293c4c45ccbb02f42d79bf0fe208d1f913fb | https://github.com/tomas-stefano/rspec-i18n/blob/4383293c4c45ccbb02f42d79bf0fe208d1f913fb/lib/spec-i18n/matchers/method_missing.rb#L8-L14 | train |
Subsets and Splits