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 |
---|---|---|---|---|---|---|---|---|---|---|---|
rubiojr/yumrepo | lib/yumrepo.rb | YumRepo.Repomd.filelists | def filelists
fl = []
@repomd.xpath("/xmlns:repomd/xmlns:data[@type=\"filelists\"]/xmlns:location").each do |f|
fl << File.join(@url, f['href'])
end
fl
end | ruby | def filelists
fl = []
@repomd.xpath("/xmlns:repomd/xmlns:data[@type=\"filelists\"]/xmlns:location").each do |f|
fl << File.join(@url, f['href'])
end
fl
end | [
"def",
"filelists",
"fl",
"=",
"[",
"]",
"@repomd",
".",
"xpath",
"(",
"\"/xmlns:repomd/xmlns:data[@type=\\\"filelists\\\"]/xmlns:location\"",
")",
".",
"each",
"do",
"|",
"f",
"|",
"fl",
"<<",
"File",
".",
"join",
"(",
"@url",
",",
"f",
"[",
"'href'",
"]",
")",
"end",
"fl",
"end"
] | Rasises exception if can't retrieve repomd.xml | [
"Rasises",
"exception",
"if",
"can",
"t",
"retrieve",
"repomd",
".",
"xml"
] | 9fd44835a6160ef0959823a3e3d91963ce61456e | https://github.com/rubiojr/yumrepo/blob/9fd44835a6160ef0959823a3e3d91963ce61456e/lib/yumrepo.rb#L107-L113 | train |
vpacher/xpay | lib/xpay/payment.rb | Xpay.Payment.rewrite_request_block | def rewrite_request_block(auth_type="ST3DAUTH")
# set the required AUTH type
REXML::XPath.first(@request_xml, "//Request").attributes["Type"] = auth_type
# delete term url and merchant name
ops = REXML::XPath.first(@request_xml, "//Operation")
["TermUrl", "MerchantName"].each { |e| ops.delete_element e }
# delete accept and user agent in customer info
customer_info = REXML::XPath.first(@request_xml, "//CustomerInfo")
["Accept", "UserAgent"].each { |e| customer_info.delete_element e }
# delete credit card details and add TransactionVerifier and TransactionReference from response xml
# CC details are not needed anymore as verifier and reference are sufficient
cc_details = REXML::XPath.first(@request_xml, "//CreditCard")
["Number", "Type", "SecurityCode", "StartDate", "ExpiryDate", "Issue"].each { |e| cc_details.delete_element e }
cc_details.add_element("TransactionVerifier").text = REXML::XPath.first(@response_xml, "//TransactionVerifier").text
cc_details.add_element("ParentTransactionReference").text = REXML::XPath.first(@response_xml, "//TransactionReference").text
# unless it is an AUTH request, add additional required info for a 3DAUTH request
unless auth_type == "AUTH"
pm_method = REXML::XPath.first(@request_xml, "//PaymentMethod")
threedsecure = pm_method.add_element("ThreeDSecure")
threedsecure.add_element("Enrolled").text = REXML::XPath.first(@response_xml, "//Enrolled").text
threedsecure.add_element("MD").text = REXML::XPath.first(@response_xml, "//MD").text rescue ""
end
true
end | ruby | def rewrite_request_block(auth_type="ST3DAUTH")
# set the required AUTH type
REXML::XPath.first(@request_xml, "//Request").attributes["Type"] = auth_type
# delete term url and merchant name
ops = REXML::XPath.first(@request_xml, "//Operation")
["TermUrl", "MerchantName"].each { |e| ops.delete_element e }
# delete accept and user agent in customer info
customer_info = REXML::XPath.first(@request_xml, "//CustomerInfo")
["Accept", "UserAgent"].each { |e| customer_info.delete_element e }
# delete credit card details and add TransactionVerifier and TransactionReference from response xml
# CC details are not needed anymore as verifier and reference are sufficient
cc_details = REXML::XPath.first(@request_xml, "//CreditCard")
["Number", "Type", "SecurityCode", "StartDate", "ExpiryDate", "Issue"].each { |e| cc_details.delete_element e }
cc_details.add_element("TransactionVerifier").text = REXML::XPath.first(@response_xml, "//TransactionVerifier").text
cc_details.add_element("ParentTransactionReference").text = REXML::XPath.first(@response_xml, "//TransactionReference").text
# unless it is an AUTH request, add additional required info for a 3DAUTH request
unless auth_type == "AUTH"
pm_method = REXML::XPath.first(@request_xml, "//PaymentMethod")
threedsecure = pm_method.add_element("ThreeDSecure")
threedsecure.add_element("Enrolled").text = REXML::XPath.first(@response_xml, "//Enrolled").text
threedsecure.add_element("MD").text = REXML::XPath.first(@response_xml, "//MD").text rescue ""
end
true
end | [
"def",
"rewrite_request_block",
"(",
"auth_type",
"=",
"\"ST3DAUTH\"",
")",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"@request_xml",
",",
"\"//Request\"",
")",
".",
"attributes",
"[",
"\"Type\"",
"]",
"=",
"auth_type",
"ops",
"=",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"@request_xml",
",",
"\"//Operation\"",
")",
"[",
"\"TermUrl\"",
",",
"\"MerchantName\"",
"]",
".",
"each",
"{",
"|",
"e",
"|",
"ops",
".",
"delete_element",
"e",
"}",
"customer_info",
"=",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"@request_xml",
",",
"\"//CustomerInfo\"",
")",
"[",
"\"Accept\"",
",",
"\"UserAgent\"",
"]",
".",
"each",
"{",
"|",
"e",
"|",
"customer_info",
".",
"delete_element",
"e",
"}",
"cc_details",
"=",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"@request_xml",
",",
"\"//CreditCard\"",
")",
"[",
"\"Number\"",
",",
"\"Type\"",
",",
"\"SecurityCode\"",
",",
"\"StartDate\"",
",",
"\"ExpiryDate\"",
",",
"\"Issue\"",
"]",
".",
"each",
"{",
"|",
"e",
"|",
"cc_details",
".",
"delete_element",
"e",
"}",
"cc_details",
".",
"add_element",
"(",
"\"TransactionVerifier\"",
")",
".",
"text",
"=",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"@response_xml",
",",
"\"//TransactionVerifier\"",
")",
".",
"text",
"cc_details",
".",
"add_element",
"(",
"\"ParentTransactionReference\"",
")",
".",
"text",
"=",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"@response_xml",
",",
"\"//TransactionReference\"",
")",
".",
"text",
"unless",
"auth_type",
"==",
"\"AUTH\"",
"pm_method",
"=",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"@request_xml",
",",
"\"//PaymentMethod\"",
")",
"threedsecure",
"=",
"pm_method",
".",
"add_element",
"(",
"\"ThreeDSecure\"",
")",
"threedsecure",
".",
"add_element",
"(",
"\"Enrolled\"",
")",
".",
"text",
"=",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"@response_xml",
",",
"\"//Enrolled\"",
")",
".",
"text",
"threedsecure",
".",
"add_element",
"(",
"\"MD\"",
")",
".",
"text",
"=",
"REXML",
"::",
"XPath",
".",
"first",
"(",
"@response_xml",
",",
"\"//MD\"",
")",
".",
"text",
"rescue",
"\"\"",
"end",
"true",
"end"
] | Rewrites the request according to the response coming from SecureTrading according to the required auth_type
This only applies if the inital request was a ST3DCARDQUERY
It deletes elements which are not needed for the subsequent request and
adds the required additional information if an ST3DAUTH is needed | [
"Rewrites",
"the",
"request",
"according",
"to",
"the",
"response",
"coming",
"from",
"SecureTrading",
"according",
"to",
"the",
"required",
"auth_type",
"This",
"only",
"applies",
"if",
"the",
"inital",
"request",
"was",
"a",
"ST3DCARDQUERY",
"It",
"deletes",
"elements",
"which",
"are",
"not",
"needed",
"for",
"the",
"subsequent",
"request",
"and",
"adds",
"the",
"required",
"additional",
"information",
"if",
"an",
"ST3DAUTH",
"is",
"needed"
] | 58c0b0f2600ed30ff44b84f97b96c74590474f3f | https://github.com/vpacher/xpay/blob/58c0b0f2600ed30ff44b84f97b96c74590474f3f/lib/xpay/payment.rb#L172-L200 | train |
OiNutter/skeletor | lib/skeletor/cli.rb | Skeletor.CLI.clean | def clean
print 'Are you sure you want to clean this project directory? (Y|n): '
confirm = $stdin.gets.chomp
if confirm != 'Y' && confirm != 'n'
puts 'Please enter Y or n'
elsif confirm == 'Y'
path = options[:directory] || Dir.pwd
Builder.clean path
end
end | ruby | def clean
print 'Are you sure you want to clean this project directory? (Y|n): '
confirm = $stdin.gets.chomp
if confirm != 'Y' && confirm != 'n'
puts 'Please enter Y or n'
elsif confirm == 'Y'
path = options[:directory] || Dir.pwd
Builder.clean path
end
end | [
"def",
"clean",
"print",
"'Are you sure you want to clean this project directory? (Y|n): '",
"confirm",
"=",
"$stdin",
".",
"gets",
".",
"chomp",
"if",
"confirm",
"!=",
"'Y'",
"&&",
"confirm",
"!=",
"'n'",
"puts",
"'Please enter Y or n'",
"elsif",
"confirm",
"==",
"'Y'",
"path",
"=",
"options",
"[",
":directory",
"]",
"||",
"Dir",
".",
"pwd",
"Builder",
".",
"clean",
"path",
"end",
"end"
] | Cleans out the specified directory | [
"Cleans",
"out",
"the",
"specified",
"directory"
] | c3996c346bbf8009f7135855aabfd4f411aaa2e1 | https://github.com/OiNutter/skeletor/blob/c3996c346bbf8009f7135855aabfd4f411aaa2e1/lib/skeletor/cli.rb#L32-L42 | train |
jamescook/layabout | lib/layabout/file_upload.rb | Layabout.FileUpload.wrap | def wrap(http_response)
OpenStruct.new.tap do |obj|
obj.code = http_response.code.to_i
obj.body = http_response.body
obj.headers = {}
http_response.each_header{|k,v| obj.headers[k] = v }
end
end | ruby | def wrap(http_response)
OpenStruct.new.tap do |obj|
obj.code = http_response.code.to_i
obj.body = http_response.body
obj.headers = {}
http_response.each_header{|k,v| obj.headers[k] = v }
end
end | [
"def",
"wrap",
"(",
"http_response",
")",
"OpenStruct",
".",
"new",
".",
"tap",
"do",
"|",
"obj",
"|",
"obj",
".",
"code",
"=",
"http_response",
".",
"code",
".",
"to_i",
"obj",
".",
"body",
"=",
"http_response",
".",
"body",
"obj",
".",
"headers",
"=",
"{",
"}",
"http_response",
".",
"each_header",
"{",
"|",
"k",
",",
"v",
"|",
"obj",
".",
"headers",
"[",
"k",
"]",
"=",
"v",
"}",
"end",
"end"
] | HTTPI doesn't support multipart posts. We can work around it by using another gem
and handing off something that looks like a HTTPI response | [
"HTTPI",
"doesn",
"t",
"support",
"multipart",
"posts",
".",
"We",
"can",
"work",
"around",
"it",
"by",
"using",
"another",
"gem",
"and",
"handing",
"off",
"something",
"that",
"looks",
"like",
"a",
"HTTPI",
"response"
] | 87d4cf3f03cd617fba55112ef5339a43ddf828a3 | https://github.com/jamescook/layabout/blob/87d4cf3f03cd617fba55112ef5339a43ddf828a3/lib/layabout/file_upload.rb#L30-L37 | train |
Montage-Inc/ruby-montage | lib/montage/query/order_parser.rb | Montage.OrderParser.clause_valid? | def clause_valid?
if @clause.is_a?(Hash)
@clause.flatten.find do |e|
return true unless (/\basc\b|\bdesc\b/).match(e).nil?
end
else
return true unless @clause.split.empty?
end
end | ruby | def clause_valid?
if @clause.is_a?(Hash)
@clause.flatten.find do |e|
return true unless (/\basc\b|\bdesc\b/).match(e).nil?
end
else
return true unless @clause.split.empty?
end
end | [
"def",
"clause_valid?",
"if",
"@clause",
".",
"is_a?",
"(",
"Hash",
")",
"@clause",
".",
"flatten",
".",
"find",
"do",
"|",
"e",
"|",
"return",
"true",
"unless",
"(",
"/",
"\\b",
"\\b",
"\\b",
"\\b",
"/",
")",
".",
"match",
"(",
"e",
")",
".",
"nil?",
"end",
"else",
"return",
"true",
"unless",
"@clause",
".",
"split",
".",
"empty?",
"end",
"end"
] | Creates an OrderParser instance based on a clause argument. The instance
can then be parsed into a valid ReQON string for queries
* *Args* :
- +clause+ -> A hash or string ordering value
* *Returns* :
- A Montage::OrderParser instance
* *Raises* :
- +ClauseFormatError+ -> If a blank string clause or a hash without
a valid direction is found.
Validates clause arguments by checking a hash for a full word match of
"asc" or "desc". String clauses are rejected if they are blank or
consist entirely of whitespace
* *Returns* :
- A boolean | [
"Creates",
"an",
"OrderParser",
"instance",
"based",
"on",
"a",
"clause",
"argument",
".",
"The",
"instance",
"can",
"then",
"be",
"parsed",
"into",
"a",
"valid",
"ReQON",
"string",
"for",
"queries"
] | 2e6f7e591f2f87158994c17ad9619fa29b716bad | https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/order_parser.rb#L33-L41 | train |
Montage-Inc/ruby-montage | lib/montage/query/order_parser.rb | Montage.OrderParser.parse_hash | def parse_hash
direction = clause.values.first
field = clause.keys.first.to_s
["$order_by", ["$#{direction}", field]]
end | ruby | def parse_hash
direction = clause.values.first
field = clause.keys.first.to_s
["$order_by", ["$#{direction}", field]]
end | [
"def",
"parse_hash",
"direction",
"=",
"clause",
".",
"values",
".",
"first",
"field",
"=",
"clause",
".",
"keys",
".",
"first",
".",
"to_s",
"[",
"\"$order_by\"",
",",
"[",
"\"$#{direction}\"",
",",
"field",
"]",
"]",
"end"
] | Parses a hash clause
* *Returns* :
- A ReQON formatted array
* *Examples* :
@clause = { test: "asc"}
@clause.parse
=> ["$order_by", ["$asc", "test"]] | [
"Parses",
"a",
"hash",
"clause"
] | 2e6f7e591f2f87158994c17ad9619fa29b716bad | https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/order_parser.rb#L52-L56 | train |
Montage-Inc/ruby-montage | lib/montage/query/order_parser.rb | Montage.OrderParser.parse_string | def parse_string
direction = clause.split[1]
field = clause.split[0]
direction = "asc" unless %w(asc desc).include?(direction)
["$order_by", ["$#{direction}", field]]
end | ruby | def parse_string
direction = clause.split[1]
field = clause.split[0]
direction = "asc" unless %w(asc desc).include?(direction)
["$order_by", ["$#{direction}", field]]
end | [
"def",
"parse_string",
"direction",
"=",
"clause",
".",
"split",
"[",
"1",
"]",
"field",
"=",
"clause",
".",
"split",
"[",
"0",
"]",
"direction",
"=",
"\"asc\"",
"unless",
"%w(",
"asc",
"desc",
")",
".",
"include?",
"(",
"direction",
")",
"[",
"\"$order_by\"",
",",
"[",
"\"$#{direction}\"",
",",
"field",
"]",
"]",
"end"
] | Parses a string clause, defaults direction to asc if missing or invalid
* *Returns* :
- A ReQON formatted array
* *Examples* :
@clause = "happy_trees desc"
@clause.parse
=> ["$order_by", ["$desc", "happy_trees"]] | [
"Parses",
"a",
"string",
"clause",
"defaults",
"direction",
"to",
"asc",
"if",
"missing",
"or",
"invalid"
] | 2e6f7e591f2f87158994c17ad9619fa29b716bad | https://github.com/Montage-Inc/ruby-montage/blob/2e6f7e591f2f87158994c17ad9619fa29b716bad/lib/montage/query/order_parser.rb#L67-L72 | train |
finn-no/zendesk-tools | lib/zendesk-tools/clean_suspended.rb | ZendeskTools.CleanSuspended.run | def run
@client.suspended_tickets.each do |suspended_ticket|
if should_delete?(suspended_ticket)
log.info "Deleting: #{suspended_ticket.subject}"
suspended_ticket.destroy
else
log.info "Keeping: #{suspended_ticket.subject}"
end
end
end | ruby | def run
@client.suspended_tickets.each do |suspended_ticket|
if should_delete?(suspended_ticket)
log.info "Deleting: #{suspended_ticket.subject}"
suspended_ticket.destroy
else
log.info "Keeping: #{suspended_ticket.subject}"
end
end
end | [
"def",
"run",
"@client",
".",
"suspended_tickets",
".",
"each",
"do",
"|",
"suspended_ticket",
"|",
"if",
"should_delete?",
"(",
"suspended_ticket",
")",
"log",
".",
"info",
"\"Deleting: #{suspended_ticket.subject}\"",
"suspended_ticket",
".",
"destroy",
"else",
"log",
".",
"info",
"\"Keeping: #{suspended_ticket.subject}\"",
"end",
"end",
"end"
] | Array with delete subjects. Defined in config file | [
"Array",
"with",
"delete",
"subjects",
".",
"Defined",
"in",
"config",
"file"
] | cc12d59e28e20cddb220830a47125f8b277243aa | https://github.com/finn-no/zendesk-tools/blob/cc12d59e28e20cddb220830a47125f8b277243aa/lib/zendesk-tools/clean_suspended.rb#L26-L35 | train |
beccasaurus/simplecli | simplecli3/lib/simplecli/command.rb | SimpleCLI.Command.summary | def summary
if @summary.nil?
match = Command::SummaryMatcher.match documentation
match.captures.first.strip if match
else
@summary
end
end | ruby | def summary
if @summary.nil?
match = Command::SummaryMatcher.match documentation
match.captures.first.strip if match
else
@summary
end
end | [
"def",
"summary",
"if",
"@summary",
".",
"nil?",
"match",
"=",
"Command",
"::",
"SummaryMatcher",
".",
"match",
"documentation",
"match",
".",
"captures",
".",
"first",
".",
"strip",
"if",
"match",
"else",
"@summary",
"end",
"end"
] | Returns a short summary for this Command
Typically generated by parsing #documentation for 'Summary: something',
but it can also be set manually
:api: public | [
"Returns",
"a",
"short",
"summary",
"for",
"this",
"Command"
] | e50b7adf5e77e6bc3179b3b92eaf592ad073c812 | https://github.com/beccasaurus/simplecli/blob/e50b7adf5e77e6bc3179b3b92eaf592ad073c812/simplecli3/lib/simplecli/command.rb#L115-L122 | train |
kbredemeier/hue_bridge | lib/hue_bridge/light_bulb.rb | HueBridge.LightBulb.set_color | def set_color(opts = {})
color = Color.new(opts)
response = put('state', color.to_h)
response_successful?(response)
end | ruby | def set_color(opts = {})
color = Color.new(opts)
response = put('state', color.to_h)
response_successful?(response)
end | [
"def",
"set_color",
"(",
"opts",
"=",
"{",
"}",
")",
"color",
"=",
"Color",
".",
"new",
"(",
"opts",
")",
"response",
"=",
"put",
"(",
"'state'",
",",
"color",
".",
"to_h",
")",
"response_successful?",
"(",
"response",
")",
"end"
] | Sets the color for the lightbulp.
@see Color#initialize
@return [Boolean] success of the operation | [
"Sets",
"the",
"color",
"for",
"the",
"lightbulp",
"."
] | ce6f9c93602e919d9bda81762eea03c02698f698 | https://github.com/kbredemeier/hue_bridge/blob/ce6f9c93602e919d9bda81762eea03c02698f698/lib/hue_bridge/light_bulb.rb#L64-L69 | train |
kbredemeier/hue_bridge | lib/hue_bridge/light_bulb.rb | HueBridge.LightBulb.store_state | def store_state
response = get
success = !!(response.body =~ %r(state))
data = JSON.parse(response.body) if success
@state = data.fetch('state')
delete_forbidden_stats
success
end | ruby | def store_state
response = get
success = !!(response.body =~ %r(state))
data = JSON.parse(response.body) if success
@state = data.fetch('state')
delete_forbidden_stats
success
end | [
"def",
"store_state",
"response",
"=",
"get",
"success",
"=",
"!",
"!",
"(",
"response",
".",
"body",
"=~",
"%r(",
")",
")",
"data",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"if",
"success",
"@state",
"=",
"data",
".",
"fetch",
"(",
"'state'",
")",
"delete_forbidden_stats",
"success",
"end"
] | Stores the current state of the lightbulp.
@return [Boolean] success of the operation | [
"Stores",
"the",
"current",
"state",
"of",
"the",
"lightbulp",
"."
] | ce6f9c93602e919d9bda81762eea03c02698f698 | https://github.com/kbredemeier/hue_bridge/blob/ce6f9c93602e919d9bda81762eea03c02698f698/lib/hue_bridge/light_bulb.rb#L74-L81 | train |
CruGlobal/cru_lib | lib/cru_lib/async.rb | CruLib.Async.perform | def perform(id, method, *args)
if id
begin
self.class.find(id).send(method, *args)
rescue ActiveRecord::RecordNotFound
# If the record was deleted after the job was created, swallow it
end
else
self.class.send(method, *args)
end
end | ruby | def perform(id, method, *args)
if id
begin
self.class.find(id).send(method, *args)
rescue ActiveRecord::RecordNotFound
# If the record was deleted after the job was created, swallow it
end
else
self.class.send(method, *args)
end
end | [
"def",
"perform",
"(",
"id",
",",
"method",
",",
"*",
"args",
")",
"if",
"id",
"begin",
"self",
".",
"class",
".",
"find",
"(",
"id",
")",
".",
"send",
"(",
"method",
",",
"*",
"args",
")",
"rescue",
"ActiveRecord",
"::",
"RecordNotFound",
"end",
"else",
"self",
".",
"class",
".",
"send",
"(",
"method",
",",
"*",
"args",
")",
"end",
"end"
] | This will be called by a worker when a job needs to be processed | [
"This",
"will",
"be",
"called",
"by",
"a",
"worker",
"when",
"a",
"job",
"needs",
"to",
"be",
"processed"
] | 9cc938579a479efe4e2510ccbcbe2e9b69b2b04a | https://github.com/CruGlobal/cru_lib/blob/9cc938579a479efe4e2510ccbcbe2e9b69b2b04a/lib/cru_lib/async.rb#L5-L15 | train |
rich-dtk/dtk-common | lib/gitolite/utils.rb | Gitolite.Utils.is_subset? | def is_subset?(array1, array2)
result = array1 & array2
(array2.length == result.length)
end | ruby | def is_subset?(array1, array2)
result = array1 & array2
(array2.length == result.length)
end | [
"def",
"is_subset?",
"(",
"array1",
",",
"array2",
")",
"result",
"=",
"array1",
"&",
"array2",
"(",
"array2",
".",
"length",
"==",
"result",
".",
"length",
")",
"end"
] | Checks to see if array2 is subset of array1 | [
"Checks",
"to",
"see",
"if",
"array2",
"is",
"subset",
"of",
"array1"
] | 18d312092e9060f01d271a603ad4b0c9bef318b1 | https://github.com/rich-dtk/dtk-common/blob/18d312092e9060f01d271a603ad4b0c9bef318b1/lib/gitolite/utils.rb#L36-L39 | train |
rich-dtk/dtk-common | lib/gitolite/utils.rb | Gitolite.Utils.gitolite_friendly | def gitolite_friendly(permission)
if permission.empty?
return nil
elsif permission.match(/^RWDP?/)
return "RW+"
elsif permission.match(/^RW/)
return "RW+"
elsif permission.match(/^R/)
return 'R'
else
return nil
end
end | ruby | def gitolite_friendly(permission)
if permission.empty?
return nil
elsif permission.match(/^RWDP?/)
return "RW+"
elsif permission.match(/^RW/)
return "RW+"
elsif permission.match(/^R/)
return 'R'
else
return nil
end
end | [
"def",
"gitolite_friendly",
"(",
"permission",
")",
"if",
"permission",
".",
"empty?",
"return",
"nil",
"elsif",
"permission",
".",
"match",
"(",
"/",
"/",
")",
"return",
"\"RW+\"",
"elsif",
"permission",
".",
"match",
"(",
"/",
"/",
")",
"return",
"\"RW+\"",
"elsif",
"permission",
".",
"match",
"(",
"/",
"/",
")",
"return",
"'R'",
"else",
"return",
"nil",
"end",
"end"
] | Converts permission to gitolite friendly permission | [
"Converts",
"permission",
"to",
"gitolite",
"friendly",
"permission"
] | 18d312092e9060f01d271a603ad4b0c9bef318b1 | https://github.com/rich-dtk/dtk-common/blob/18d312092e9060f01d271a603ad4b0c9bef318b1/lib/gitolite/utils.rb#L44-L56 | train |
codescrum/bebox | lib/bebox/wizards/environment_wizard.rb | Bebox.EnvironmentWizard.create_new_environment | def create_new_environment(project_root, environment_name)
# Check if the environment exist
return error(_('wizard.environment.name_exist')%{environment: environment_name}) if Bebox::Environment.environment_exists?(project_root, environment_name)
# Environment creation
environment = Bebox::Environment.new(environment_name, project_root)
output = environment.create
ok _('wizard.environment.creation_success')
return output
end | ruby | def create_new_environment(project_root, environment_name)
# Check if the environment exist
return error(_('wizard.environment.name_exist')%{environment: environment_name}) if Bebox::Environment.environment_exists?(project_root, environment_name)
# Environment creation
environment = Bebox::Environment.new(environment_name, project_root)
output = environment.create
ok _('wizard.environment.creation_success')
return output
end | [
"def",
"create_new_environment",
"(",
"project_root",
",",
"environment_name",
")",
"return",
"error",
"(",
"_",
"(",
"'wizard.environment.name_exist'",
")",
"%",
"{",
"environment",
":",
"environment_name",
"}",
")",
"if",
"Bebox",
"::",
"Environment",
".",
"environment_exists?",
"(",
"project_root",
",",
"environment_name",
")",
"environment",
"=",
"Bebox",
"::",
"Environment",
".",
"new",
"(",
"environment_name",
",",
"project_root",
")",
"output",
"=",
"environment",
".",
"create",
"ok",
"_",
"(",
"'wizard.environment.creation_success'",
")",
"return",
"output",
"end"
] | Create a new environment | [
"Create",
"a",
"new",
"environment"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/environment_wizard.rb#L8-L16 | train |
codescrum/bebox | lib/bebox/wizards/environment_wizard.rb | Bebox.EnvironmentWizard.remove_environment | def remove_environment(project_root, environment_name)
# Check if the environment exist
return error(_('wizard.environment.name_not_exist')%{environment: environment_name}) unless Bebox::Environment.environment_exists?(project_root, environment_name)
# Confirm deletion
return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.environment.confirm_deletion'))
# Environment deletion
environment = Bebox::Environment.new(environment_name, project_root)
output = environment.remove
ok _('wizard.environment.deletion_success')
return output
end | ruby | def remove_environment(project_root, environment_name)
# Check if the environment exist
return error(_('wizard.environment.name_not_exist')%{environment: environment_name}) unless Bebox::Environment.environment_exists?(project_root, environment_name)
# Confirm deletion
return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.environment.confirm_deletion'))
# Environment deletion
environment = Bebox::Environment.new(environment_name, project_root)
output = environment.remove
ok _('wizard.environment.deletion_success')
return output
end | [
"def",
"remove_environment",
"(",
"project_root",
",",
"environment_name",
")",
"return",
"error",
"(",
"_",
"(",
"'wizard.environment.name_not_exist'",
")",
"%",
"{",
"environment",
":",
"environment_name",
"}",
")",
"unless",
"Bebox",
"::",
"Environment",
".",
"environment_exists?",
"(",
"project_root",
",",
"environment_name",
")",
"return",
"warn",
"(",
"_",
"(",
"'wizard.no_changes'",
")",
")",
"unless",
"confirm_action?",
"(",
"_",
"(",
"'wizard.environment.confirm_deletion'",
")",
")",
"environment",
"=",
"Bebox",
"::",
"Environment",
".",
"new",
"(",
"environment_name",
",",
"project_root",
")",
"output",
"=",
"environment",
".",
"remove",
"ok",
"_",
"(",
"'wizard.environment.deletion_success'",
")",
"return",
"output",
"end"
] | Removes an existing environment | [
"Removes",
"an",
"existing",
"environment"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/environment_wizard.rb#L19-L29 | train |
fugroup/asset | lib/assets/item.rb | Asset.Item.write_cache | def write_cache
compressed.tap{|c| File.atomic_write(cache_path){|f| f.write(c)}}
end | ruby | def write_cache
compressed.tap{|c| File.atomic_write(cache_path){|f| f.write(c)}}
end | [
"def",
"write_cache",
"compressed",
".",
"tap",
"{",
"|",
"c",
"|",
"File",
".",
"atomic_write",
"(",
"cache_path",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"c",
")",
"}",
"}",
"end"
] | Store in cache | [
"Store",
"in",
"cache"
] | 3cc1aad0926d80653f25d5f0a8c9154d00049bc4 | https://github.com/fugroup/asset/blob/3cc1aad0926d80653f25d5f0a8c9154d00049bc4/lib/assets/item.rb#L45-L47 | train |
fugroup/asset | lib/assets/item.rb | Asset.Item.compressed | def compressed
@compressed ||= case @type
when 'css'
Sass::Engine.new(joined, :syntax => :scss, :cache => false, :style => :compressed).render rescue joined
when 'js'
Uglifier.compile(joined, :mangle => false, :comments => :none) rescue joined
end
end | ruby | def compressed
@compressed ||= case @type
when 'css'
Sass::Engine.new(joined, :syntax => :scss, :cache => false, :style => :compressed).render rescue joined
when 'js'
Uglifier.compile(joined, :mangle => false, :comments => :none) rescue joined
end
end | [
"def",
"compressed",
"@compressed",
"||=",
"case",
"@type",
"when",
"'css'",
"Sass",
"::",
"Engine",
".",
"new",
"(",
"joined",
",",
":syntax",
"=>",
":scss",
",",
":cache",
"=>",
"false",
",",
":style",
"=>",
":compressed",
")",
".",
"render",
"rescue",
"joined",
"when",
"'js'",
"Uglifier",
".",
"compile",
"(",
"joined",
",",
":mangle",
"=>",
"false",
",",
":comments",
"=>",
":none",
")",
"rescue",
"joined",
"end",
"end"
] | Compressed joined files | [
"Compressed",
"joined",
"files"
] | 3cc1aad0926d80653f25d5f0a8c9154d00049bc4 | https://github.com/fugroup/asset/blob/3cc1aad0926d80653f25d5f0a8c9154d00049bc4/lib/assets/item.rb#L60-L67 | train |
fugroup/asset | lib/assets/item.rb | Asset.Item.joined | def joined
@joined ||= files.map{|f| File.read(File.join(::Asset.path, @type, f))}.join
end | ruby | def joined
@joined ||= files.map{|f| File.read(File.join(::Asset.path, @type, f))}.join
end | [
"def",
"joined",
"@joined",
"||=",
"files",
".",
"map",
"{",
"|",
"f",
"|",
"File",
".",
"read",
"(",
"File",
".",
"join",
"(",
"::",
"Asset",
".",
"path",
",",
"@type",
",",
"f",
")",
")",
"}",
".",
"join",
"end"
] | All files joined | [
"All",
"files",
"joined"
] | 3cc1aad0926d80653f25d5f0a8c9154d00049bc4 | https://github.com/fugroup/asset/blob/3cc1aad0926d80653f25d5f0a8c9154d00049bc4/lib/assets/item.rb#L70-L72 | train |
miguelzf/zomato2 | lib/zomato2/zomato.rb | Zomato2.Zomato.locations | def locations(params={})
args = [ :query, :lat, :lon, :count ]
params.each do |k,v|
if !args.include?(k)
raise ArgumentError.new 'Search term not allowed: ' + k.to_s
end
end
if !params.include?(:query)
raise ArgumentError.new '"query" term with location name is required'
end
results = get('locations', params)
if results.key?("location_suggestions")
results["location_suggestions"].map { |l| Location.new(self, l) }
else
nil
end
end | ruby | def locations(params={})
args = [ :query, :lat, :lon, :count ]
params.each do |k,v|
if !args.include?(k)
raise ArgumentError.new 'Search term not allowed: ' + k.to_s
end
end
if !params.include?(:query)
raise ArgumentError.new '"query" term with location name is required'
end
results = get('locations', params)
if results.key?("location_suggestions")
results["location_suggestions"].map { |l| Location.new(self, l) }
else
nil
end
end | [
"def",
"locations",
"(",
"params",
"=",
"{",
"}",
")",
"args",
"=",
"[",
":query",
",",
":lat",
",",
":lon",
",",
":count",
"]",
"params",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"!",
"args",
".",
"include?",
"(",
"k",
")",
"raise",
"ArgumentError",
".",
"new",
"'Search term not allowed: '",
"+",
"k",
".",
"to_s",
"end",
"end",
"if",
"!",
"params",
".",
"include?",
"(",
":query",
")",
"raise",
"ArgumentError",
".",
"new",
"'\"query\" term with location name is required'",
"end",
"results",
"=",
"get",
"(",
"'locations'",
",",
"params",
")",
"if",
"results",
".",
"key?",
"(",
"\"location_suggestions\"",
")",
"results",
"[",
"\"location_suggestions\"",
"]",
".",
"map",
"{",
"|",
"l",
"|",
"Location",
".",
"new",
"(",
"self",
",",
"l",
")",
"}",
"else",
"nil",
"end",
"end"
] | search for locations | [
"search",
"for",
"locations"
] | 487d64af68a8b0f2735fe13edda3c4e9259504e6 | https://github.com/miguelzf/zomato2/blob/487d64af68a8b0f2735fe13edda3c4e9259504e6/lib/zomato2/zomato.rb#L44-L62 | train |
miguelzf/zomato2 | lib/zomato2/zomato.rb | Zomato2.Zomato.restaurants | def restaurants(params={})
args = [ :entity_id, :entity_type, # location
:q, :start, :count, :lat, :lon,
:radius, :cuisines, :establishment_type,
:collection_id, :category, :sort, :order,
:start, :count ]
params.each do |k,v|
if !args.include?(k)
raise ArgumentError.new 'Search term not allowed: ' + k.to_s
end
end
if params[:count] && params[:count].to_i > 20
warn 'Count maxes out at 20'
end
# these filters are already city-specific
has_sub_city = params[:establishment_type] || params[:collection_id] || params[:cuisines]
if (has_sub_city && params[:q]) ||
(has_sub_city && params[:entity_type] == 'city') ||
(params[:q] && params[:entity_type] == 'city')
warn 'More than 2 different kinds of City searches cannot be combined'
end
results = get('search', params)
results['restaurants'].map { |e| Restaurant.new(self, e['restaurant']) }
end | ruby | def restaurants(params={})
args = [ :entity_id, :entity_type, # location
:q, :start, :count, :lat, :lon,
:radius, :cuisines, :establishment_type,
:collection_id, :category, :sort, :order,
:start, :count ]
params.each do |k,v|
if !args.include?(k)
raise ArgumentError.new 'Search term not allowed: ' + k.to_s
end
end
if params[:count] && params[:count].to_i > 20
warn 'Count maxes out at 20'
end
# these filters are already city-specific
has_sub_city = params[:establishment_type] || params[:collection_id] || params[:cuisines]
if (has_sub_city && params[:q]) ||
(has_sub_city && params[:entity_type] == 'city') ||
(params[:q] && params[:entity_type] == 'city')
warn 'More than 2 different kinds of City searches cannot be combined'
end
results = get('search', params)
results['restaurants'].map { |e| Restaurant.new(self, e['restaurant']) }
end | [
"def",
"restaurants",
"(",
"params",
"=",
"{",
"}",
")",
"args",
"=",
"[",
":entity_id",
",",
":entity_type",
",",
":q",
",",
":start",
",",
":count",
",",
":lat",
",",
":lon",
",",
":radius",
",",
":cuisines",
",",
":establishment_type",
",",
":collection_id",
",",
":category",
",",
":sort",
",",
":order",
",",
":start",
",",
":count",
"]",
"params",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"!",
"args",
".",
"include?",
"(",
"k",
")",
"raise",
"ArgumentError",
".",
"new",
"'Search term not allowed: '",
"+",
"k",
".",
"to_s",
"end",
"end",
"if",
"params",
"[",
":count",
"]",
"&&",
"params",
"[",
":count",
"]",
".",
"to_i",
">",
"20",
"warn",
"'Count maxes out at 20'",
"end",
"has_sub_city",
"=",
"params",
"[",
":establishment_type",
"]",
"||",
"params",
"[",
":collection_id",
"]",
"||",
"params",
"[",
":cuisines",
"]",
"if",
"(",
"has_sub_city",
"&&",
"params",
"[",
":q",
"]",
")",
"||",
"(",
"has_sub_city",
"&&",
"params",
"[",
":entity_type",
"]",
"==",
"'city'",
")",
"||",
"(",
"params",
"[",
":q",
"]",
"&&",
"params",
"[",
":entity_type",
"]",
"==",
"'city'",
")",
"warn",
"'More than 2 different kinds of City searches cannot be combined'",
"end",
"results",
"=",
"get",
"(",
"'search'",
",",
"params",
")",
"results",
"[",
"'restaurants'",
"]",
".",
"map",
"{",
"|",
"e",
"|",
"Restaurant",
".",
"new",
"(",
"self",
",",
"e",
"[",
"'restaurant'",
"]",
")",
"}",
"end"
] | general search for restaurants | [
"general",
"search",
"for",
"restaurants"
] | 487d64af68a8b0f2735fe13edda3c4e9259504e6 | https://github.com/miguelzf/zomato2/blob/487d64af68a8b0f2735fe13edda3c4e9259504e6/lib/zomato2/zomato.rb#L65-L93 | train |
kurtisnelson/resumator | lib/resumator/client.rb | Resumator.Client.get | def get(object, options = {})
if options[:all_pages]
options.delete(:all_pages)
options[:page] = 1
out = []
begin
data = get(object, options)
out = out | data
options[:page] += 1
end while data.count >= 100
return out
else
if options[:id]
resp = @connection.get "#{object}/#{options[:id]}"
elsif options.size > 0
resp = @connection.get "#{object}#{Client.parse_options(options)}"
else
resp = @connection.get object
end
raise "Bad response: #{resp.status}" unless resp.status == 200
Client.mash(JSON.parse(resp.body))
end
end | ruby | def get(object, options = {})
if options[:all_pages]
options.delete(:all_pages)
options[:page] = 1
out = []
begin
data = get(object, options)
out = out | data
options[:page] += 1
end while data.count >= 100
return out
else
if options[:id]
resp = @connection.get "#{object}/#{options[:id]}"
elsif options.size > 0
resp = @connection.get "#{object}#{Client.parse_options(options)}"
else
resp = @connection.get object
end
raise "Bad response: #{resp.status}" unless resp.status == 200
Client.mash(JSON.parse(resp.body))
end
end | [
"def",
"get",
"(",
"object",
",",
"options",
"=",
"{",
"}",
")",
"if",
"options",
"[",
":all_pages",
"]",
"options",
".",
"delete",
"(",
":all_pages",
")",
"options",
"[",
":page",
"]",
"=",
"1",
"out",
"=",
"[",
"]",
"begin",
"data",
"=",
"get",
"(",
"object",
",",
"options",
")",
"out",
"=",
"out",
"|",
"data",
"options",
"[",
":page",
"]",
"+=",
"1",
"end",
"while",
"data",
".",
"count",
">=",
"100",
"return",
"out",
"else",
"if",
"options",
"[",
":id",
"]",
"resp",
"=",
"@connection",
".",
"get",
"\"#{object}/#{options[:id]}\"",
"elsif",
"options",
".",
"size",
">",
"0",
"resp",
"=",
"@connection",
".",
"get",
"\"#{object}#{Client.parse_options(options)}\"",
"else",
"resp",
"=",
"@connection",
".",
"get",
"object",
"end",
"raise",
"\"Bad response: #{resp.status}\"",
"unless",
"resp",
".",
"status",
"==",
"200",
"Client",
".",
"mash",
"(",
"JSON",
".",
"parse",
"(",
"resp",
".",
"body",
")",
")",
"end",
"end"
] | Sets up a client
@param [String] API key
Get any rest accessible object
@param [String] object name
@param [Hash] optional search parameters
@return [Mash] your data | [
"Sets",
"up",
"a",
"client"
] | 7b8d6a312fa3d7cb4da8e20d373b34a61d01ec31 | https://github.com/kurtisnelson/resumator/blob/7b8d6a312fa3d7cb4da8e20d373b34a61d01ec31/lib/resumator/client.rb#L29-L51 | train |
hinrik/ircsupport | lib/ircsupport/masks.rb | IRCSupport.Masks.matches_mask_array | def matches_mask_array(masks, strings, casemapping = :rfc1459)
results = {}
masks.each do |mask|
strings.each do |string|
if matches_mask(mask, string, casemapping)
results[mask] ||= []
results[mask] << string
end
end
end
return results
end | ruby | def matches_mask_array(masks, strings, casemapping = :rfc1459)
results = {}
masks.each do |mask|
strings.each do |string|
if matches_mask(mask, string, casemapping)
results[mask] ||= []
results[mask] << string
end
end
end
return results
end | [
"def",
"matches_mask_array",
"(",
"masks",
",",
"strings",
",",
"casemapping",
"=",
":rfc1459",
")",
"results",
"=",
"{",
"}",
"masks",
".",
"each",
"do",
"|",
"mask",
"|",
"strings",
".",
"each",
"do",
"|",
"string",
"|",
"if",
"matches_mask",
"(",
"mask",
",",
"string",
",",
"casemapping",
")",
"results",
"[",
"mask",
"]",
"||=",
"[",
"]",
"results",
"[",
"mask",
"]",
"<<",
"string",
"end",
"end",
"end",
"return",
"results",
"end"
] | Match strings to multiple IRC masks.
@param [Array] masks The masks to match against.
@param [Array] strings The strings to match against the masks.
@param [Symbol] casemapping The IRC casemapping to use in the match.
@return [Hash] Each mask that was matched will be present as a key,
and the values will be arrays of the strings that matched. | [
"Match",
"strings",
"to",
"multiple",
"IRC",
"masks",
"."
] | d028b7d5ccc604a6af175ee2264c18d25b1f7dff | https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/masks.rb#L36-L47 | train |
booqable/scoped_serializer | lib/scoped_serializer/scope.rb | ScopedSerializer.Scope.merge! | def merge!(scope)
@options.merge!(scope.options)
@attributes += scope.attributes
@associations.merge!(scope.associations)
@attributes.uniq!
self
end | ruby | def merge!(scope)
@options.merge!(scope.options)
@attributes += scope.attributes
@associations.merge!(scope.associations)
@attributes.uniq!
self
end | [
"def",
"merge!",
"(",
"scope",
")",
"@options",
".",
"merge!",
"(",
"scope",
".",
"options",
")",
"@attributes",
"+=",
"scope",
".",
"attributes",
"@associations",
".",
"merge!",
"(",
"scope",
".",
"associations",
")",
"@attributes",
".",
"uniq!",
"self",
"end"
] | Merges data with given scope.
@example
scope.merge!(another_scope) | [
"Merges",
"data",
"with",
"given",
"scope",
"."
] | fb163bbf61f54a5e8684e4aba3908592bdd986ac | https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/scope.rb#L47-L56 | train |
booqable/scoped_serializer | lib/scoped_serializer/scope.rb | ScopedSerializer.Scope._association | def _association(args, default_options={})
return if options.nil?
options = args.first
if options.is_a?(Hash)
options = {}.merge(options)
name = options.keys.first
properties = options.delete(name)
@associations[name] = default_options.merge({ :include => properties }).merge(options)
elsif options.is_a?(Array)
options.each do |option|
association option
end
else
@associations[options] = args[1] || {}
end
end | ruby | def _association(args, default_options={})
return if options.nil?
options = args.first
if options.is_a?(Hash)
options = {}.merge(options)
name = options.keys.first
properties = options.delete(name)
@associations[name] = default_options.merge({ :include => properties }).merge(options)
elsif options.is_a?(Array)
options.each do |option|
association option
end
else
@associations[options] = args[1] || {}
end
end | [
"def",
"_association",
"(",
"args",
",",
"default_options",
"=",
"{",
"}",
")",
"return",
"if",
"options",
".",
"nil?",
"options",
"=",
"args",
".",
"first",
"if",
"options",
".",
"is_a?",
"(",
"Hash",
")",
"options",
"=",
"{",
"}",
".",
"merge",
"(",
"options",
")",
"name",
"=",
"options",
".",
"keys",
".",
"first",
"properties",
"=",
"options",
".",
"delete",
"(",
"name",
")",
"@associations",
"[",
"name",
"]",
"=",
"default_options",
".",
"merge",
"(",
"{",
":include",
"=>",
"properties",
"}",
")",
".",
"merge",
"(",
"options",
")",
"elsif",
"options",
".",
"is_a?",
"(",
"Array",
")",
"options",
".",
"each",
"do",
"|",
"option",
"|",
"association",
"option",
"end",
"else",
"@associations",
"[",
"options",
"]",
"=",
"args",
"[",
"1",
"]",
"||",
"{",
"}",
"end",
"end"
] | Duplicates scope.
Actually defines the association but without default_options. | [
"Duplicates",
"scope",
"."
] | fb163bbf61f54a5e8684e4aba3908592bdd986ac | https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/scope.rb#L114-L132 | train |
varyonic/pocus | lib/pocus/resource.rb | Pocus.Resource.get | def get(request_path, klass)
response = session.send_request('GET', path + request_path)
data = response.fetch(klass.tag)
resource = klass.new(data.merge(parent: self))
resource.assign_errors(response)
resource
end | ruby | def get(request_path, klass)
response = session.send_request('GET', path + request_path)
data = response.fetch(klass.tag)
resource = klass.new(data.merge(parent: self))
resource.assign_errors(response)
resource
end | [
"def",
"get",
"(",
"request_path",
",",
"klass",
")",
"response",
"=",
"session",
".",
"send_request",
"(",
"'GET'",
",",
"path",
"+",
"request_path",
")",
"data",
"=",
"response",
".",
"fetch",
"(",
"klass",
".",
"tag",
")",
"resource",
"=",
"klass",
".",
"new",
"(",
"data",
".",
"merge",
"(",
"parent",
":",
"self",
")",
")",
"resource",
".",
"assign_errors",
"(",
"response",
")",
"resource",
"end"
] | Fetch and instantiate a single resource from a path. | [
"Fetch",
"and",
"instantiate",
"a",
"single",
"resource",
"from",
"a",
"path",
"."
] | 84cbbda509456fc8afaffd6916dccfc585d23b41 | https://github.com/varyonic/pocus/blob/84cbbda509456fc8afaffd6916dccfc585d23b41/lib/pocus/resource.rb#L66-L72 | train |
varyonic/pocus | lib/pocus/resource.rb | Pocus.Resource.reload | def reload
response = session.send_request('GET', path)
assign_attributes(response.fetch(self.class.tag))
assign_errors(response)
self
end | ruby | def reload
response = session.send_request('GET', path)
assign_attributes(response.fetch(self.class.tag))
assign_errors(response)
self
end | [
"def",
"reload",
"response",
"=",
"session",
".",
"send_request",
"(",
"'GET'",
",",
"path",
")",
"assign_attributes",
"(",
"response",
".",
"fetch",
"(",
"self",
".",
"class",
".",
"tag",
")",
")",
"assign_errors",
"(",
"response",
")",
"self",
"end"
] | Fetch and update this resource from a path. | [
"Fetch",
"and",
"update",
"this",
"resource",
"from",
"a",
"path",
"."
] | 84cbbda509456fc8afaffd6916dccfc585d23b41 | https://github.com/varyonic/pocus/blob/84cbbda509456fc8afaffd6916dccfc585d23b41/lib/pocus/resource.rb#L114-L119 | train |
syborg/mme_tools | lib/mme_tools/enumerable.rb | MMETools.Enumerable.compose | def compose(*enumerables)
res=[]
enumerables.map(&:size).max.times do
tupla=[]
for enumerable in enumerables
tupla << enumerable.shift
end
res << (block_given? ? yield(tupla) : tupla)
end
res
end | ruby | def compose(*enumerables)
res=[]
enumerables.map(&:size).max.times do
tupla=[]
for enumerable in enumerables
tupla << enumerable.shift
end
res << (block_given? ? yield(tupla) : tupla)
end
res
end | [
"def",
"compose",
"(",
"*",
"enumerables",
")",
"res",
"=",
"[",
"]",
"enumerables",
".",
"map",
"(",
"&",
":size",
")",
".",
"max",
".",
"times",
"do",
"tupla",
"=",
"[",
"]",
"for",
"enumerable",
"in",
"enumerables",
"tupla",
"<<",
"enumerable",
".",
"shift",
"end",
"res",
"<<",
"(",
"block_given?",
"?",
"yield",
"(",
"tupla",
")",
":",
"tupla",
")",
"end",
"res",
"end"
] | torna un array on cada element es una tupla formada per
un element de cada enumerable. Si se li passa un bloc
se li passa al bloc cada tupla i el resultat del bloc
s'emmagatzema a l'array tornat. | [
"torna",
"un",
"array",
"on",
"cada",
"element",
"es",
"una",
"tupla",
"formada",
"per",
"un",
"element",
"de",
"cada",
"enumerable",
".",
"Si",
"se",
"li",
"passa",
"un",
"bloc",
"se",
"li",
"passa",
"al",
"bloc",
"cada",
"tupla",
"i",
"el",
"resultat",
"del",
"bloc",
"s",
"emmagatzema",
"a",
"l",
"array",
"tornat",
"."
] | e93919f7fcfb408b941d6144290991a7feabaa7d | https://github.com/syborg/mme_tools/blob/e93919f7fcfb408b941d6144290991a7feabaa7d/lib/mme_tools/enumerable.rb#L15-L25 | train |
zires/micro-spider | lib/spider_core/field_dsl.rb | SpiderCore.FieldDSL.field | def field(display, pattern, opts = {}, &block)
actions << lambda {
action_for(:field, {display: display, pattern: pattern}, opts, &block)
}
end | ruby | def field(display, pattern, opts = {}, &block)
actions << lambda {
action_for(:field, {display: display, pattern: pattern}, opts, &block)
}
end | [
"def",
"field",
"(",
"display",
",",
"pattern",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"actions",
"<<",
"lambda",
"{",
"action_for",
"(",
":field",
",",
"{",
"display",
":",
"display",
",",
"pattern",
":",
"pattern",
"}",
",",
"opts",
",",
"&",
"block",
")",
"}",
"end"
] | Get a field on current page.
@param display [String] display name | [
"Get",
"a",
"field",
"on",
"current",
"page",
"."
] | bcf3f371d8f16f6b9f7de4c4f62c3d588f9ce13d | https://github.com/zires/micro-spider/blob/bcf3f371d8f16f6b9f7de4c4f62c3d588f9ce13d/lib/spider_core/field_dsl.rb#L7-L11 | train |
nikhgupta/encruby | lib/encruby/message.rb | Encruby.Message.encrypt | def encrypt(message)
raise Error, "data must not be empty" if message.to_s.strip.empty?
# 1
@cipher.reset
@cipher.encrypt
aes_key = @cipher.random_key
aes_iv = @cipher.random_iv
encrypted = @cipher.update(message) + @cipher.final
# 2
rsa_encrypted_aes_key = @rsa.public_encrypt(aes_key)
rsa_encrypted_aes_iv = @rsa.public_encrypt(aes_iv)
# 3
content = rsa_encrypted_aes_key + rsa_encrypted_aes_iv + encrypted
# 4
hmac = hmac_signature(content)
content = Base64.encode64(hmac + content)
{ signature: hmac, content: content }
rescue OpenSSL::OpenSSLError => e
raise Error.new(e.message)
end | ruby | def encrypt(message)
raise Error, "data must not be empty" if message.to_s.strip.empty?
# 1
@cipher.reset
@cipher.encrypt
aes_key = @cipher.random_key
aes_iv = @cipher.random_iv
encrypted = @cipher.update(message) + @cipher.final
# 2
rsa_encrypted_aes_key = @rsa.public_encrypt(aes_key)
rsa_encrypted_aes_iv = @rsa.public_encrypt(aes_iv)
# 3
content = rsa_encrypted_aes_key + rsa_encrypted_aes_iv + encrypted
# 4
hmac = hmac_signature(content)
content = Base64.encode64(hmac + content)
{ signature: hmac, content: content }
rescue OpenSSL::OpenSSLError => e
raise Error.new(e.message)
end | [
"def",
"encrypt",
"(",
"message",
")",
"raise",
"Error",
",",
"\"data must not be empty\"",
"if",
"message",
".",
"to_s",
".",
"strip",
".",
"empty?",
"@cipher",
".",
"reset",
"@cipher",
".",
"encrypt",
"aes_key",
"=",
"@cipher",
".",
"random_key",
"aes_iv",
"=",
"@cipher",
".",
"random_iv",
"encrypted",
"=",
"@cipher",
".",
"update",
"(",
"message",
")",
"+",
"@cipher",
".",
"final",
"rsa_encrypted_aes_key",
"=",
"@rsa",
".",
"public_encrypt",
"(",
"aes_key",
")",
"rsa_encrypted_aes_iv",
"=",
"@rsa",
".",
"public_encrypt",
"(",
"aes_iv",
")",
"content",
"=",
"rsa_encrypted_aes_key",
"+",
"rsa_encrypted_aes_iv",
"+",
"encrypted",
"hmac",
"=",
"hmac_signature",
"(",
"content",
")",
"content",
"=",
"Base64",
".",
"encode64",
"(",
"hmac",
"+",
"content",
")",
"{",
"signature",
":",
"hmac",
",",
"content",
":",
"content",
"}",
"rescue",
"OpenSSL",
"::",
"OpenSSLError",
"=>",
"e",
"raise",
"Error",
".",
"new",
"(",
"e",
".",
"message",
")",
"end"
] | 1. Generate random AES key to encrypt message
2. Use Public Key from the Private key to encrypt AES Key
3. Prepend encrypted AES key to the encrypted message
Output message format will look like the following:
{RSA Encrypted AES Key}{RSA Encrypted IV}{AES Encrypted Message} | [
"1",
".",
"Generate",
"random",
"AES",
"key",
"to",
"encrypt",
"message",
"2",
".",
"Use",
"Public",
"Key",
"from",
"the",
"Private",
"key",
"to",
"encrypt",
"AES",
"Key",
"3",
".",
"Prepend",
"encrypted",
"AES",
"key",
"to",
"the",
"encrypted",
"message"
] | ded0276001f7672594a84d403f64dcd4ab906039 | https://github.com/nikhgupta/encruby/blob/ded0276001f7672594a84d403f64dcd4ab906039/lib/encruby/message.rb#L36-L59 | train |
nikhgupta/encruby | lib/encruby/message.rb | Encruby.Message.decrypt | def decrypt(message, hash: nil)
# 0
message = Base64.decode64(message)
hmac = message[0..63] # 64 bits of hmac signature
case
when hash && hmac != hash
raise Error, "Provided hash mismatch for encrypted file!"
when hmac != hmac_signature(message[64..-1])
raise Error, "HMAC signature mismatch for encrypted file!"
end
# 1
rsa_encrypted_aes_key = message[64..319] # next 256 bits
rsa_encrypted_aes_iv = message[320..575] # next 256 bits
aes_encrypted_message = message[576..-1]
# 2
aes_key = @rsa.private_decrypt rsa_encrypted_aes_key
aes_iv = @rsa.private_decrypt rsa_encrypted_aes_iv
# 3
@cipher.reset
@cipher.decrypt
@cipher.key = aes_key
@cipher.iv = aes_iv
content = @cipher.update(aes_encrypted_message) + @cipher.final
{ signature: hmac, content: content }
rescue OpenSSL::OpenSSLError => e
raise Error.new(e.message)
end | ruby | def decrypt(message, hash: nil)
# 0
message = Base64.decode64(message)
hmac = message[0..63] # 64 bits of hmac signature
case
when hash && hmac != hash
raise Error, "Provided hash mismatch for encrypted file!"
when hmac != hmac_signature(message[64..-1])
raise Error, "HMAC signature mismatch for encrypted file!"
end
# 1
rsa_encrypted_aes_key = message[64..319] # next 256 bits
rsa_encrypted_aes_iv = message[320..575] # next 256 bits
aes_encrypted_message = message[576..-1]
# 2
aes_key = @rsa.private_decrypt rsa_encrypted_aes_key
aes_iv = @rsa.private_decrypt rsa_encrypted_aes_iv
# 3
@cipher.reset
@cipher.decrypt
@cipher.key = aes_key
@cipher.iv = aes_iv
content = @cipher.update(aes_encrypted_message) + @cipher.final
{ signature: hmac, content: content }
rescue OpenSSL::OpenSSLError => e
raise Error.new(e.message)
end | [
"def",
"decrypt",
"(",
"message",
",",
"hash",
":",
"nil",
")",
"message",
"=",
"Base64",
".",
"decode64",
"(",
"message",
")",
"hmac",
"=",
"message",
"[",
"0",
"..",
"63",
"]",
"case",
"when",
"hash",
"&&",
"hmac",
"!=",
"hash",
"raise",
"Error",
",",
"\"Provided hash mismatch for encrypted file!\"",
"when",
"hmac",
"!=",
"hmac_signature",
"(",
"message",
"[",
"64",
"..",
"-",
"1",
"]",
")",
"raise",
"Error",
",",
"\"HMAC signature mismatch for encrypted file!\"",
"end",
"rsa_encrypted_aes_key",
"=",
"message",
"[",
"64",
"..",
"319",
"]",
"rsa_encrypted_aes_iv",
"=",
"message",
"[",
"320",
"..",
"575",
"]",
"aes_encrypted_message",
"=",
"message",
"[",
"576",
"..",
"-",
"1",
"]",
"aes_key",
"=",
"@rsa",
".",
"private_decrypt",
"rsa_encrypted_aes_key",
"aes_iv",
"=",
"@rsa",
".",
"private_decrypt",
"rsa_encrypted_aes_iv",
"@cipher",
".",
"reset",
"@cipher",
".",
"decrypt",
"@cipher",
".",
"key",
"=",
"aes_key",
"@cipher",
".",
"iv",
"=",
"aes_iv",
"content",
"=",
"@cipher",
".",
"update",
"(",
"aes_encrypted_message",
")",
"+",
"@cipher",
".",
"final",
"{",
"signature",
":",
"hmac",
",",
"content",
":",
"content",
"}",
"rescue",
"OpenSSL",
"::",
"OpenSSLError",
"=>",
"e",
"raise",
"Error",
".",
"new",
"(",
"e",
".",
"message",
")",
"end"
] | 0. Base64 decode the encrypted message
1. Split the string in to the AES key and the encrypted message
2. Decrypt the AES key using the private key
3. Decrypt the message using the AES key | [
"0",
".",
"Base64",
"decode",
"the",
"encrypted",
"message",
"1",
".",
"Split",
"the",
"string",
"in",
"to",
"the",
"AES",
"key",
"and",
"the",
"encrypted",
"message",
"2",
".",
"Decrypt",
"the",
"AES",
"key",
"using",
"the",
"private",
"key",
"3",
".",
"Decrypt",
"the",
"message",
"using",
"the",
"AES",
"key"
] | ded0276001f7672594a84d403f64dcd4ab906039 | https://github.com/nikhgupta/encruby/blob/ded0276001f7672594a84d403f64dcd4ab906039/lib/encruby/message.rb#L65-L96 | train |
Rafaherrero/lpp_11 | lib/refBiblio/referencia.rb | RefBiblio.Referencia.titulo | def titulo (titulo)
tit = titulo.split(' ')
tit.each do |word|
if word.length > 3
word.capitalize!
else
word.downcase!
end
if word == tit[0]
word.capitalize!
end
@titulo = tit.join(' ')
end
# Metodo para guardar el editorial de la referencia
# @param [editorial] editorial Editorial de la referencia a introducir
def editorial(editorial)
@editorial = editorial
end
# Metodo para guardar la fecha de publicacion de la referencia
# @param [publicacion] publicacion Fecha de publicacion de la referencia a introducir
def publicacion (publicacion)
@publicacion = publicacion
end
# Metodo para obtener el titulo de la referencia
# @return Titulo de la referencia
def get_titulo
@titulo
end
# Metodo para obtener el autor/autores de la referencia
# @return Autor/autores de la referencia
def get_autor
@autor
end
# Metodo para obtener el editorial de la referencia
# @return Editorial de la referencia
def get_editorial
@editorial
end
# Metodo para obtener la fecha de publicacion de la referencia
# @return Fecha de publicacion de la referencia
def get_publicacion
@publicacion
end
# Método con el que podemos usar el modulo Enumerable
# @param otro Otro elemento a comparar
# @return Devuelve valores entre -1 y 1 segun el orden
def <=> (otro)
if(@autor == otro.get_autor)
if(@publicacion == otro.get_publicacion)
if(@titulo == otro.get_titulo)
return 0
else
arr = [@titulo, otro.get_titulo]
arr.sort_by!{|t| t.downcase}
if(arr.first == @titulo)
return 1
end
return -1
end
elsif publicacion > otro.get_publicacion
return -1
else
return 1
end
else
arr = [@autor, otro.get_autor]
arr.sort_by!{|t| t.downcase}
if(arr.first == @autor)
return -1
end
return 1
end
end
end | ruby | def titulo (titulo)
tit = titulo.split(' ')
tit.each do |word|
if word.length > 3
word.capitalize!
else
word.downcase!
end
if word == tit[0]
word.capitalize!
end
@titulo = tit.join(' ')
end
# Metodo para guardar el editorial de la referencia
# @param [editorial] editorial Editorial de la referencia a introducir
def editorial(editorial)
@editorial = editorial
end
# Metodo para guardar la fecha de publicacion de la referencia
# @param [publicacion] publicacion Fecha de publicacion de la referencia a introducir
def publicacion (publicacion)
@publicacion = publicacion
end
# Metodo para obtener el titulo de la referencia
# @return Titulo de la referencia
def get_titulo
@titulo
end
# Metodo para obtener el autor/autores de la referencia
# @return Autor/autores de la referencia
def get_autor
@autor
end
# Metodo para obtener el editorial de la referencia
# @return Editorial de la referencia
def get_editorial
@editorial
end
# Metodo para obtener la fecha de publicacion de la referencia
# @return Fecha de publicacion de la referencia
def get_publicacion
@publicacion
end
# Método con el que podemos usar el modulo Enumerable
# @param otro Otro elemento a comparar
# @return Devuelve valores entre -1 y 1 segun el orden
def <=> (otro)
if(@autor == otro.get_autor)
if(@publicacion == otro.get_publicacion)
if(@titulo == otro.get_titulo)
return 0
else
arr = [@titulo, otro.get_titulo]
arr.sort_by!{|t| t.downcase}
if(arr.first == @titulo)
return 1
end
return -1
end
elsif publicacion > otro.get_publicacion
return -1
else
return 1
end
else
arr = [@autor, otro.get_autor]
arr.sort_by!{|t| t.downcase}
if(arr.first == @autor)
return -1
end
return 1
end
end
end | [
"def",
"titulo",
"(",
"titulo",
")",
"tit",
"=",
"titulo",
".",
"split",
"(",
"' '",
")",
"tit",
".",
"each",
"do",
"|",
"word",
"|",
"if",
"word",
".",
"length",
">",
"3",
"word",
".",
"capitalize!",
"else",
"word",
".",
"downcase!",
"end",
"if",
"word",
"==",
"tit",
"[",
"0",
"]",
"word",
".",
"capitalize!",
"end",
"@titulo",
"=",
"tit",
".",
"join",
"(",
"' '",
")",
"end",
"def",
"editorial",
"(",
"editorial",
")",
"@editorial",
"=",
"editorial",
"end",
"def",
"publicacion",
"(",
"publicacion",
")",
"@publicacion",
"=",
"publicacion",
"end",
"def",
"get_titulo",
"@titulo",
"end",
"def",
"get_autor",
"@autor",
"end",
"def",
"get_editorial",
"@editorial",
"end",
"def",
"get_publicacion",
"@publicacion",
"end",
"def",
"<=>",
"(",
"otro",
")",
"if",
"(",
"@autor",
"==",
"otro",
".",
"get_autor",
")",
"if",
"(",
"@publicacion",
"==",
"otro",
".",
"get_publicacion",
")",
"if",
"(",
"@titulo",
"==",
"otro",
".",
"get_titulo",
")",
"return",
"0",
"else",
"arr",
"=",
"[",
"@titulo",
",",
"otro",
".",
"get_titulo",
"]",
"arr",
".",
"sort_by!",
"{",
"|",
"t",
"|",
"t",
".",
"downcase",
"}",
"if",
"(",
"arr",
".",
"first",
"==",
"@titulo",
")",
"return",
"1",
"end",
"return",
"-",
"1",
"end",
"elsif",
"publicacion",
">",
"otro",
".",
"get_publicacion",
"return",
"-",
"1",
"else",
"return",
"1",
"end",
"else",
"arr",
"=",
"[",
"@autor",
",",
"otro",
".",
"get_autor",
"]",
"arr",
".",
"sort_by!",
"{",
"|",
"t",
"|",
"t",
".",
"downcase",
"}",
"if",
"(",
"arr",
".",
"first",
"==",
"@autor",
")",
"return",
"-",
"1",
"end",
"return",
"1",
"end",
"end",
"end"
] | Metodo para guardar el titulo de la referencia
@param [titulo] titulo Titulo de la referencia a introducir | [
"Metodo",
"para",
"guardar",
"el",
"titulo",
"de",
"la",
"referencia"
] | 7b9a89138db96d603f1f1b1b93735feee5e4c2a2 | https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/refBiblio/referencia.rb#L34-L114 | train |
Rafaherrero/lpp_11 | lib/refBiblio/referencia.rb | RefBiblio.ArtPeriodico.to_s | def to_s
string = ""
string << @autor << " (" << Date::MONTHNAMES[get_publicacion.month] << " " << get_publicacion.day.to_s << ", " << get_publicacion.year.to_s << "). " << @titulo << ". " << @editorial << ", pp. " << @formato << ", " << @paginas.to_s << " paginas" << "."
end | ruby | def to_s
string = ""
string << @autor << " (" << Date::MONTHNAMES[get_publicacion.month] << " " << get_publicacion.day.to_s << ", " << get_publicacion.year.to_s << "). " << @titulo << ". " << @editorial << ", pp. " << @formato << ", " << @paginas.to_s << " paginas" << "."
end | [
"def",
"to_s",
"string",
"=",
"\"\"",
"string",
"<<",
"@autor",
"<<",
"\" (\"",
"<<",
"Date",
"::",
"MONTHNAMES",
"[",
"get_publicacion",
".",
"month",
"]",
"<<",
"\" \"",
"<<",
"get_publicacion",
".",
"day",
".",
"to_s",
"<<",
"\", \"",
"<<",
"get_publicacion",
".",
"year",
".",
"to_s",
"<<",
"\"). \"",
"<<",
"@titulo",
"<<",
"\". \"",
"<<",
"@editorial",
"<<",
"\", pp. \"",
"<<",
"@formato",
"<<",
"\", \"",
"<<",
"@paginas",
".",
"to_s",
"<<",
"\" paginas\"",
"<<",
"\".\"",
"end"
] | Metodo que nos devuelve la referencia del articulo periodistico formateado
@return String de la referencia del articulo periodistico formateado | [
"Metodo",
"que",
"nos",
"devuelve",
"la",
"referencia",
"del",
"articulo",
"periodistico",
"formateado"
] | 7b9a89138db96d603f1f1b1b93735feee5e4c2a2 | https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/refBiblio/referencia.rb#L189-L192 | train |
Rafaherrero/lpp_11 | lib/refBiblio/referencia.rb | RefBiblio.DocElectronico.to_s | def to_s
string = ""
string << @autor << " (" << Date::MONTHNAMES[get_publicacion.month] << " " << get_publicacion.day.to_s << ", " << get_publicacion.year.to_s << "). " << @titulo << @formato << ". " << @editorial << ": " << @edicion << ". Disponible en: " << @url << " (" << Date::MONTHNAMES[get_fechacceso.month] << " " << get_fechacceso.day.to_s << ", " << get_fechacceso.year.to_s << "). "
end | ruby | def to_s
string = ""
string << @autor << " (" << Date::MONTHNAMES[get_publicacion.month] << " " << get_publicacion.day.to_s << ", " << get_publicacion.year.to_s << "). " << @titulo << @formato << ". " << @editorial << ": " << @edicion << ". Disponible en: " << @url << " (" << Date::MONTHNAMES[get_fechacceso.month] << " " << get_fechacceso.day.to_s << ", " << get_fechacceso.year.to_s << "). "
end | [
"def",
"to_s",
"string",
"=",
"\"\"",
"string",
"<<",
"@autor",
"<<",
"\" (\"",
"<<",
"Date",
"::",
"MONTHNAMES",
"[",
"get_publicacion",
".",
"month",
"]",
"<<",
"\" \"",
"<<",
"get_publicacion",
".",
"day",
".",
"to_s",
"<<",
"\", \"",
"<<",
"get_publicacion",
".",
"year",
".",
"to_s",
"<<",
"\"). \"",
"<<",
"@titulo",
"<<",
"@formato",
"<<",
"\". \"",
"<<",
"@editorial",
"<<",
"\": \"",
"<<",
"@edicion",
"<<",
"\". Disponible en: \"",
"<<",
"@url",
"<<",
"\" (\"",
"<<",
"Date",
"::",
"MONTHNAMES",
"[",
"get_fechacceso",
".",
"month",
"]",
"<<",
"\" \"",
"<<",
"get_fechacceso",
".",
"day",
".",
"to_s",
"<<",
"\", \"",
"<<",
"get_fechacceso",
".",
"year",
".",
"to_s",
"<<",
"\"). \"",
"end"
] | Metodo que nos devuelve la referencia del documento electronico formateado
@return String de la referencia del documento electronico formateado | [
"Metodo",
"que",
"nos",
"devuelve",
"la",
"referencia",
"del",
"documento",
"electronico",
"formateado"
] | 7b9a89138db96d603f1f1b1b93735feee5e4c2a2 | https://github.com/Rafaherrero/lpp_11/blob/7b9a89138db96d603f1f1b1b93735feee5e4c2a2/lib/refBiblio/referencia.rb#L237-L240 | train |
KatanaCode/evvnt | lib/evvnt/path_helpers.rb | Evvnt.PathHelpers.nest_path_within_parent | def nest_path_within_parent(path, params)
return path unless params_include_parent_resource_id?(params)
params.symbolize_keys!
parent_resource = parent_resource_name(params)
parent_id = params.delete(parent_resource_param(params)).try(:to_s)
File.join(*[parent_resource, parent_id, path].compact).to_s
end | ruby | def nest_path_within_parent(path, params)
return path unless params_include_parent_resource_id?(params)
params.symbolize_keys!
parent_resource = parent_resource_name(params)
parent_id = params.delete(parent_resource_param(params)).try(:to_s)
File.join(*[parent_resource, parent_id, path].compact).to_s
end | [
"def",
"nest_path_within_parent",
"(",
"path",
",",
"params",
")",
"return",
"path",
"unless",
"params_include_parent_resource_id?",
"(",
"params",
")",
"params",
".",
"symbolize_keys!",
"parent_resource",
"=",
"parent_resource_name",
"(",
"params",
")",
"parent_id",
"=",
"params",
".",
"delete",
"(",
"parent_resource_param",
"(",
"params",
")",
")",
".",
"try",
"(",
":to_s",
")",
"File",
".",
"join",
"(",
"*",
"[",
"parent_resource",
",",
"parent_id",
",",
"path",
"]",
".",
"compact",
")",
".",
"to_s",
"end"
] | Nest a given resource path within a parent resource.
path - A String representing an API resource path.
params - A Hash of params to send to the API.
Examples
nest_path_within_parent("bags/1", {user_id: "123"}) # => /users/123/bags/1
Returns String | [
"Nest",
"a",
"given",
"resource",
"path",
"within",
"a",
"parent",
"resource",
"."
] | e13f6d84af09a71819356620fb25685a6cd159c9 | https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/path_helpers.rb#L60-L66 | train |
3Crowd/dynamic_registrar | lib/dynamic_registrar/registrar.rb | DynamicRegistrar.Registrar.dispatch | def dispatch name, namespace = nil
responses = Hash.new
namespaces_to_search = namespace ? [namespace] : namespaces
namespaces_to_search.each do |namespace|
responses[namespace] ||= Hash.new
responses[namespace][name] = @registered_callbacks[namespace][name].call if @registered_callbacks[namespace].has_key?(name)
end
responses
end | ruby | def dispatch name, namespace = nil
responses = Hash.new
namespaces_to_search = namespace ? [namespace] : namespaces
namespaces_to_search.each do |namespace|
responses[namespace] ||= Hash.new
responses[namespace][name] = @registered_callbacks[namespace][name].call if @registered_callbacks[namespace].has_key?(name)
end
responses
end | [
"def",
"dispatch",
"name",
",",
"namespace",
"=",
"nil",
"responses",
"=",
"Hash",
".",
"new",
"namespaces_to_search",
"=",
"namespace",
"?",
"[",
"namespace",
"]",
":",
"namespaces",
"namespaces_to_search",
".",
"each",
"do",
"|",
"namespace",
"|",
"responses",
"[",
"namespace",
"]",
"||=",
"Hash",
".",
"new",
"responses",
"[",
"namespace",
"]",
"[",
"name",
"]",
"=",
"@registered_callbacks",
"[",
"namespace",
"]",
"[",
"name",
"]",
".",
"call",
"if",
"@registered_callbacks",
"[",
"namespace",
"]",
".",
"has_key?",
"(",
"name",
")",
"end",
"responses",
"end"
] | Dispatch message to given callback. All named callbacks matching the name will
be run in all namespaces in indeterminate order
@param [ Symbol ] name The name of the callback
@param [ Symbol ] namespace The namespace in which the named callback should be found. Optional, if omitted then all matching named callbacks in all namespaces will be executed
@return [ Hash ] A hash whose keys are the namespaces in which callbacks were executed, and whose values are the results of those executions. If empty, then no callbacks were executed. | [
"Dispatch",
"message",
"to",
"given",
"callback",
".",
"All",
"named",
"callbacks",
"matching",
"the",
"name",
"will",
"be",
"run",
"in",
"all",
"namespaces",
"in",
"indeterminate",
"order"
] | e8a87b543905e764e031ae7021b58905442bc35d | https://github.com/3Crowd/dynamic_registrar/blob/e8a87b543905e764e031ae7021b58905442bc35d/lib/dynamic_registrar/registrar.rb#L46-L54 | train |
3Crowd/dynamic_registrar | lib/dynamic_registrar/registrar.rb | DynamicRegistrar.Registrar.registered? | def registered? name
registration_map = namespaces.map do |namespace|
registered_in_namespace? name, namespace
end
registration_map.any?
end | ruby | def registered? name
registration_map = namespaces.map do |namespace|
registered_in_namespace? name, namespace
end
registration_map.any?
end | [
"def",
"registered?",
"name",
"registration_map",
"=",
"namespaces",
".",
"map",
"do",
"|",
"namespace",
"|",
"registered_in_namespace?",
"name",
",",
"namespace",
"end",
"registration_map",
".",
"any?",
"end"
] | Query if a callback of given name is registered in any namespace
@param [ Symbol ] name The name of the callback to check | [
"Query",
"if",
"a",
"callback",
"of",
"given",
"name",
"is",
"registered",
"in",
"any",
"namespace"
] | e8a87b543905e764e031ae7021b58905442bc35d | https://github.com/3Crowd/dynamic_registrar/blob/e8a87b543905e764e031ae7021b58905442bc35d/lib/dynamic_registrar/registrar.rb#L58-L63 | train |
cjlucas/ruby-easytag | lib/easytag/attributes/mp3.rb | EasyTag.MP3AttributeAccessors.read_all_tags | def read_all_tags(taglib, id3v2_frames, id3v1_tag = nil, **opts)
frames = []
id3v2_frames.each { |frame_id| frames += id3v2_frames(taglib, frame_id) }
data = []
# only check id3v1 if no id3v2 frames found
if frames.empty?
data << id3v1_tag(taglib, id3v1_tag) unless id3v1_tag.nil?
else
frames.each { |frame| data << data_from_frame(frame, **opts) }
end
data.compact
end | ruby | def read_all_tags(taglib, id3v2_frames, id3v1_tag = nil, **opts)
frames = []
id3v2_frames.each { |frame_id| frames += id3v2_frames(taglib, frame_id) }
data = []
# only check id3v1 if no id3v2 frames found
if frames.empty?
data << id3v1_tag(taglib, id3v1_tag) unless id3v1_tag.nil?
else
frames.each { |frame| data << data_from_frame(frame, **opts) }
end
data.compact
end | [
"def",
"read_all_tags",
"(",
"taglib",
",",
"id3v2_frames",
",",
"id3v1_tag",
"=",
"nil",
",",
"**",
"opts",
")",
"frames",
"=",
"[",
"]",
"id3v2_frames",
".",
"each",
"{",
"|",
"frame_id",
"|",
"frames",
"+=",
"id3v2_frames",
"(",
"taglib",
",",
"frame_id",
")",
"}",
"data",
"=",
"[",
"]",
"if",
"frames",
".",
"empty?",
"data",
"<<",
"id3v1_tag",
"(",
"taglib",
",",
"id3v1_tag",
")",
"unless",
"id3v1_tag",
".",
"nil?",
"else",
"frames",
".",
"each",
"{",
"|",
"frame",
"|",
"data",
"<<",
"data_from_frame",
"(",
"frame",
",",
"**",
"opts",
")",
"}",
"end",
"data",
".",
"compact",
"end"
] | gets data from each frame id given only falls back
to the id3v1 tag if no id3v2 frames were found | [
"gets",
"data",
"from",
"each",
"frame",
"id",
"given",
"only",
"falls",
"back",
"to",
"the",
"id3v1",
"tag",
"if",
"no",
"id3v2",
"frames",
"were",
"found"
] | 7e61d2fd5450529b99bd2f817246d1741405c260 | https://github.com/cjlucas/ruby-easytag/blob/7e61d2fd5450529b99bd2f817246d1741405c260/lib/easytag/attributes/mp3.rb#L52-L65 | train |
cknadler/rcomp | lib/rcomp/runner.rb | RComp.Runner.run | def run(suite, type, options={})
@conf = Conf.instance
reporter = Reporter.new(type)
reporter.header
suite.each do |test|
case type
when :test
run_test(test) if expected_exists?(test)
when :generate
if expected_exists?(test)
run_test(test, true) if options[:overwrite]
else
run_test(test, true)
end
end
reporter.report(test)
end
reporter.summary
end | ruby | def run(suite, type, options={})
@conf = Conf.instance
reporter = Reporter.new(type)
reporter.header
suite.each do |test|
case type
when :test
run_test(test) if expected_exists?(test)
when :generate
if expected_exists?(test)
run_test(test, true) if options[:overwrite]
else
run_test(test, true)
end
end
reporter.report(test)
end
reporter.summary
end | [
"def",
"run",
"(",
"suite",
",",
"type",
",",
"options",
"=",
"{",
"}",
")",
"@conf",
"=",
"Conf",
".",
"instance",
"reporter",
"=",
"Reporter",
".",
"new",
"(",
"type",
")",
"reporter",
".",
"header",
"suite",
".",
"each",
"do",
"|",
"test",
"|",
"case",
"type",
"when",
":test",
"run_test",
"(",
"test",
")",
"if",
"expected_exists?",
"(",
"test",
")",
"when",
":generate",
"if",
"expected_exists?",
"(",
"test",
")",
"run_test",
"(",
"test",
",",
"true",
")",
"if",
"options",
"[",
":overwrite",
"]",
"else",
"run_test",
"(",
"test",
",",
"true",
")",
"end",
"end",
"reporter",
".",
"report",
"(",
"test",
")",
"end",
"reporter",
".",
"summary",
"end"
] | Run a suite of tests
suite - An Array of Test objects
type - The type (Symbol) of the suite
options - A Hash of runner options
Returns nothing | [
"Run",
"a",
"suite",
"of",
"tests"
] | 76fe71e1ef3b13923738ea6ab9cd502fe2f64f51 | https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/runner.rb#L16-L39 | train |
cknadler/rcomp | lib/rcomp/runner.rb | RComp.Runner.cmp_output | def cmp_output(test)
# test out and err
if test.expected_out_exists? && test.expected_err_exists?
cmp_out(test)
cmp_err(test)
return :success if (test.out_result && test.err_result)
# test only out
elsif test.expected_out_exists?
cmp_out(test)
return :success if test.out_result
# test only err
else
cmp_err(test)
return :success if test.err_result
end
return :failed
end | ruby | def cmp_output(test)
# test out and err
if test.expected_out_exists? && test.expected_err_exists?
cmp_out(test)
cmp_err(test)
return :success if (test.out_result && test.err_result)
# test only out
elsif test.expected_out_exists?
cmp_out(test)
return :success if test.out_result
# test only err
else
cmp_err(test)
return :success if test.err_result
end
return :failed
end | [
"def",
"cmp_output",
"(",
"test",
")",
"if",
"test",
".",
"expected_out_exists?",
"&&",
"test",
".",
"expected_err_exists?",
"cmp_out",
"(",
"test",
")",
"cmp_err",
"(",
"test",
")",
"return",
":success",
"if",
"(",
"test",
".",
"out_result",
"&&",
"test",
".",
"err_result",
")",
"elsif",
"test",
".",
"expected_out_exists?",
"cmp_out",
"(",
"test",
")",
"return",
":success",
"if",
"test",
".",
"out_result",
"else",
"cmp_err",
"(",
"test",
")",
"return",
":success",
"if",
"test",
".",
"err_result",
"end",
"return",
":failed",
"end"
] | Compare the result and expected output of a test that has been run
test - A Test object that has been run
precondition :: expected_exists?(test) is true
Returns success or failure as a symbol | [
"Compare",
"the",
"result",
"and",
"expected",
"output",
"of",
"a",
"test",
"that",
"has",
"been",
"run"
] | 76fe71e1ef3b13923738ea6ab9cd502fe2f64f51 | https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/runner.rb#L86-L105 | train |
cknadler/rcomp | lib/rcomp/runner.rb | RComp.Runner.cmp_out | def cmp_out(test)
test.out_result = FileUtils.cmp(test.expected_out_path,
test.result_out_path)
end | ruby | def cmp_out(test)
test.out_result = FileUtils.cmp(test.expected_out_path,
test.result_out_path)
end | [
"def",
"cmp_out",
"(",
"test",
")",
"test",
".",
"out_result",
"=",
"FileUtils",
".",
"cmp",
"(",
"test",
".",
"expected_out_path",
",",
"test",
".",
"result_out_path",
")",
"end"
] | Compare a tests expected and result stdout
Sets the result of the comparison to out_result in the test
test - A test object that has been run
Returns nothing | [
"Compare",
"a",
"tests",
"expected",
"and",
"result",
"stdout",
"Sets",
"the",
"result",
"of",
"the",
"comparison",
"to",
"out_result",
"in",
"the",
"test"
] | 76fe71e1ef3b13923738ea6ab9cd502fe2f64f51 | https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/runner.rb#L113-L116 | train |
cknadler/rcomp | lib/rcomp/runner.rb | RComp.Runner.cmp_err | def cmp_err(test)
test.err_result = FileUtils.cmp(test.expected_err_path,
test.result_err_path)
end | ruby | def cmp_err(test)
test.err_result = FileUtils.cmp(test.expected_err_path,
test.result_err_path)
end | [
"def",
"cmp_err",
"(",
"test",
")",
"test",
".",
"err_result",
"=",
"FileUtils",
".",
"cmp",
"(",
"test",
".",
"expected_err_path",
",",
"test",
".",
"result_err_path",
")",
"end"
] | Compare a tests expected and result stderr
Sets the result of the comparison to err_result in the test
test - A test object that has been run
Returns nothing | [
"Compare",
"a",
"tests",
"expected",
"and",
"result",
"stderr",
"Sets",
"the",
"result",
"of",
"the",
"comparison",
"to",
"err_result",
"in",
"the",
"test"
] | 76fe71e1ef3b13923738ea6ab9cd502fe2f64f51 | https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/runner.rb#L124-L127 | train |
booqable/scoped_serializer | lib/scoped_serializer/base_serializer.rb | ScopedSerializer.BaseSerializer.default_root_key | def default_root_key(object_class)
if (serializer = ScopedSerializer.find_serializer_by_class(object_class))
root_key = serializer.find_scope(:default).options[:root]
end
if root_key
root_key.to_s
elsif object_class.respond_to?(:model_name)
object_class.model_name.element
else
object_class.name
end
end | ruby | def default_root_key(object_class)
if (serializer = ScopedSerializer.find_serializer_by_class(object_class))
root_key = serializer.find_scope(:default).options[:root]
end
if root_key
root_key.to_s
elsif object_class.respond_to?(:model_name)
object_class.model_name.element
else
object_class.name
end
end | [
"def",
"default_root_key",
"(",
"object_class",
")",
"if",
"(",
"serializer",
"=",
"ScopedSerializer",
".",
"find_serializer_by_class",
"(",
"object_class",
")",
")",
"root_key",
"=",
"serializer",
".",
"find_scope",
"(",
":default",
")",
".",
"options",
"[",
":root",
"]",
"end",
"if",
"root_key",
"root_key",
".",
"to_s",
"elsif",
"object_class",
".",
"respond_to?",
"(",
":model_name",
")",
"object_class",
".",
"model_name",
".",
"element",
"else",
"object_class",
".",
"name",
"end",
"end"
] | Tries to find the default root key.
@example
default_root_key(User) # => 'user' | [
"Tries",
"to",
"find",
"the",
"default",
"root",
"key",
"."
] | fb163bbf61f54a5e8684e4aba3908592bdd986ac | https://github.com/booqable/scoped_serializer/blob/fb163bbf61f54a5e8684e4aba3908592bdd986ac/lib/scoped_serializer/base_serializer.rb#L25-L37 | train |
riddopic/garcun | lib/garcon/task/timer_set.rb | Garcon.TimerSet.post | def post(delay, *args, &task)
raise ArgumentError, 'no block given' unless block_given?
delay = TimerSet.calculate_delay!(delay)
mutex.synchronize do
return false unless running?
if (delay) <= 0.01
@task_executor.post(*args, &task)
else
@queue.push(Task.new(Garcon.monotonic_time + delay, args, task))
@timer_executor.post(&method(:process_tasks))
end
end
@condition.signal
true
end | ruby | def post(delay, *args, &task)
raise ArgumentError, 'no block given' unless block_given?
delay = TimerSet.calculate_delay!(delay)
mutex.synchronize do
return false unless running?
if (delay) <= 0.01
@task_executor.post(*args, &task)
else
@queue.push(Task.new(Garcon.monotonic_time + delay, args, task))
@timer_executor.post(&method(:process_tasks))
end
end
@condition.signal
true
end | [
"def",
"post",
"(",
"delay",
",",
"*",
"args",
",",
"&",
"task",
")",
"raise",
"ArgumentError",
",",
"'no block given'",
"unless",
"block_given?",
"delay",
"=",
"TimerSet",
".",
"calculate_delay!",
"(",
"delay",
")",
"mutex",
".",
"synchronize",
"do",
"return",
"false",
"unless",
"running?",
"if",
"(",
"delay",
")",
"<=",
"0.01",
"@task_executor",
".",
"post",
"(",
"*",
"args",
",",
"&",
"task",
")",
"else",
"@queue",
".",
"push",
"(",
"Task",
".",
"new",
"(",
"Garcon",
".",
"monotonic_time",
"+",
"delay",
",",
"args",
",",
"task",
")",
")",
"@timer_executor",
".",
"post",
"(",
"&",
"method",
"(",
":process_tasks",
")",
")",
"end",
"end",
"@condition",
".",
"signal",
"true",
"end"
] | Create a new set of timed tasks.
@!macro [attach] executor_options
@param [Hash] opts
The options used to specify the executor on which to perform actions.
@option opts [Executor] :executor
When set use the given `Executor` instance. Three special values are
also supported: `:task` returns the global task pool, `:operation`
returns the global operation pool, and `:immediate` returns a new
`ImmediateExecutor` object.
Post a task to be execute run after a given delay (in seconds). If the
delay is less than 1/100th of a second the task will be immediately post
to the executor.
@param [Float] delay
The number of seconds to wait for before executing the task.
@yield the task to be performed.
@raise [ArgumentError] f the intended execution time is not in the future.
@raise [ArgumentError] if no block is given.
@return [Boolean]
True if the message is post, false after shutdown. | [
"Create",
"a",
"new",
"set",
"of",
"timed",
"tasks",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/timer_set.rb#L76-L93 | train |
riddopic/garcun | lib/garcon/task/timer_set.rb | Garcon.TimerSet.process_tasks | def process_tasks
loop do
task = mutex.synchronize { @queue.peek }
break unless task
now = Garcon.monotonic_time
diff = task.time - now
if diff <= 0
# We need to remove the task from the queue before passing it to the
# executor, to avoid race conditions where we pass the peek'ed task
# to the executor and then pop a different one that's been added in
# the meantime.
#
# Note that there's no race condition between the peek and this pop -
# this pop could retrieve a different task from the peek, but that
# task would be due to fire now anyway (because @queue is a priority
# queue, and this thread is the only reader, so whatever timer is at
# the head of the queue now must have the same pop time, or a closer
# one, as when we peeked).
#
task = mutex.synchronize { @queue.pop }
@task_executor.post(*task.args, &task.op)
else
mutex.synchronize do
@condition.wait(mutex, [diff, 60].min)
end
end
end
end | ruby | def process_tasks
loop do
task = mutex.synchronize { @queue.peek }
break unless task
now = Garcon.monotonic_time
diff = task.time - now
if diff <= 0
# We need to remove the task from the queue before passing it to the
# executor, to avoid race conditions where we pass the peek'ed task
# to the executor and then pop a different one that's been added in
# the meantime.
#
# Note that there's no race condition between the peek and this pop -
# this pop could retrieve a different task from the peek, but that
# task would be due to fire now anyway (because @queue is a priority
# queue, and this thread is the only reader, so whatever timer is at
# the head of the queue now must have the same pop time, or a closer
# one, as when we peeked).
#
task = mutex.synchronize { @queue.pop }
@task_executor.post(*task.args, &task.op)
else
mutex.synchronize do
@condition.wait(mutex, [diff, 60].min)
end
end
end
end | [
"def",
"process_tasks",
"loop",
"do",
"task",
"=",
"mutex",
".",
"synchronize",
"{",
"@queue",
".",
"peek",
"}",
"break",
"unless",
"task",
"now",
"=",
"Garcon",
".",
"monotonic_time",
"diff",
"=",
"task",
".",
"time",
"-",
"now",
"if",
"diff",
"<=",
"0",
"task",
"=",
"mutex",
".",
"synchronize",
"{",
"@queue",
".",
"pop",
"}",
"@task_executor",
".",
"post",
"(",
"*",
"task",
".",
"args",
",",
"&",
"task",
".",
"op",
")",
"else",
"mutex",
".",
"synchronize",
"do",
"@condition",
".",
"wait",
"(",
"mutex",
",",
"[",
"diff",
",",
"60",
"]",
".",
"min",
")",
"end",
"end",
"end",
"end"
] | Run a loop and execute tasks in the scheduled order and at the approximate
scheduled time. If no tasks remain the thread will exit gracefully so that
garbage collection can occur. If there are no ready tasks it will sleep
for up to 60 seconds waiting for the next scheduled task.
@!visibility private | [
"Run",
"a",
"loop",
"and",
"execute",
"tasks",
"in",
"the",
"scheduled",
"order",
"and",
"at",
"the",
"approximate",
"scheduled",
"time",
".",
"If",
"no",
"tasks",
"remain",
"the",
"thread",
"will",
"exit",
"gracefully",
"so",
"that",
"garbage",
"collection",
"can",
"occur",
".",
"If",
"there",
"are",
"no",
"ready",
"tasks",
"it",
"will",
"sleep",
"for",
"up",
"to",
"60",
"seconds",
"waiting",
"for",
"the",
"next",
"scheduled",
"task",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/timer_set.rb#L163-L192 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/administrators_controller.rb | Roroacms.Admin::AdministratorsController.create | def create
@admin = Admin.new(administrator_params)
respond_to do |format|
if @admin.save
profile_images(params, @admin)
Emailer.profile(@admin).deliver
format.html { redirect_to admin_administrators_path, notice: I18n.t("controllers.admin.administrators.create.flash.success") }
else
format.html {
# add breadcrumb and set title
add_breadcrumb I18n.t("generic.add_new_user")
@action = 'create'
flash[:error] = I18n.t('generic.validation.no_passed')
render action: "new"
}
end
end
end | ruby | def create
@admin = Admin.new(administrator_params)
respond_to do |format|
if @admin.save
profile_images(params, @admin)
Emailer.profile(@admin).deliver
format.html { redirect_to admin_administrators_path, notice: I18n.t("controllers.admin.administrators.create.flash.success") }
else
format.html {
# add breadcrumb and set title
add_breadcrumb I18n.t("generic.add_new_user")
@action = 'create'
flash[:error] = I18n.t('generic.validation.no_passed')
render action: "new"
}
end
end
end | [
"def",
"create",
"@admin",
"=",
"Admin",
".",
"new",
"(",
"administrator_params",
")",
"respond_to",
"do",
"|",
"format",
"|",
"if",
"@admin",
".",
"save",
"profile_images",
"(",
"params",
",",
"@admin",
")",
"Emailer",
".",
"profile",
"(",
"@admin",
")",
".",
"deliver",
"format",
".",
"html",
"{",
"redirect_to",
"admin_administrators_path",
",",
"notice",
":",
"I18n",
".",
"t",
"(",
"\"controllers.admin.administrators.create.flash.success\"",
")",
"}",
"else",
"format",
".",
"html",
"{",
"add_breadcrumb",
"I18n",
".",
"t",
"(",
"\"generic.add_new_user\"",
")",
"@action",
"=",
"'create'",
"flash",
"[",
":error",
"]",
"=",
"I18n",
".",
"t",
"(",
"'generic.validation.no_passed'",
")",
"render",
"action",
":",
"\"new\"",
"}",
"end",
"end",
"end"
] | actually create the new admin with the given param data | [
"actually",
"create",
"the",
"new",
"admin",
"with",
"the",
"given",
"param",
"data"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/administrators_controller.rb#L34-L57 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/administrators_controller.rb | Roroacms.Admin::AdministratorsController.edit | def edit
@admin = current_admin.id == params[:id].to_i ? @current_admin : Admin.find(params[:id])
# add breadcrumb and set title
set_title(I18n.t("controllers.admin.administrators.edit.title", username: @admin.username))
add_breadcrumb I18n.t("controllers.admin.administrators.edit.breadcrumb")
# action for the form as both edit/new are using the same form.
@action = 'update'
# only allowed to edit the super user if you are the super user.
if @admin.overlord == 'Y' && @admin.id != session[:admin_id]
respond_to do |format|
flash[:error] = I18n.t("controllers.admin.administrators.edit.flash.error")
format.html { redirect_to admin_administrators_path }
end
end
end | ruby | def edit
@admin = current_admin.id == params[:id].to_i ? @current_admin : Admin.find(params[:id])
# add breadcrumb and set title
set_title(I18n.t("controllers.admin.administrators.edit.title", username: @admin.username))
add_breadcrumb I18n.t("controllers.admin.administrators.edit.breadcrumb")
# action for the form as both edit/new are using the same form.
@action = 'update'
# only allowed to edit the super user if you are the super user.
if @admin.overlord == 'Y' && @admin.id != session[:admin_id]
respond_to do |format|
flash[:error] = I18n.t("controllers.admin.administrators.edit.flash.error")
format.html { redirect_to admin_administrators_path }
end
end
end | [
"def",
"edit",
"@admin",
"=",
"current_admin",
".",
"id",
"==",
"params",
"[",
":id",
"]",
".",
"to_i",
"?",
"@current_admin",
":",
"Admin",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"set_title",
"(",
"I18n",
".",
"t",
"(",
"\"controllers.admin.administrators.edit.title\"",
",",
"username",
":",
"@admin",
".",
"username",
")",
")",
"add_breadcrumb",
"I18n",
".",
"t",
"(",
"\"controllers.admin.administrators.edit.breadcrumb\"",
")",
"@action",
"=",
"'update'",
"if",
"@admin",
".",
"overlord",
"==",
"'Y'",
"&&",
"@admin",
".",
"id",
"!=",
"session",
"[",
":admin_id",
"]",
"respond_to",
"do",
"|",
"format",
"|",
"flash",
"[",
":error",
"]",
"=",
"I18n",
".",
"t",
"(",
"\"controllers.admin.administrators.edit.flash.error\"",
")",
"format",
".",
"html",
"{",
"redirect_to",
"admin_administrators_path",
"}",
"end",
"end",
"end"
] | get and disply certain admin | [
"get",
"and",
"disply",
"certain",
"admin"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/administrators_controller.rb#L62-L83 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/administrators_controller.rb | Roroacms.Admin::AdministratorsController.update | def update
@admin = Admin.find(params[:id])
@admin.deal_with_cover params
respond_to do |format|
admin_passed =
if params[:admin][:password].blank?
@admin.update_without_password(administrator_params)
else
@admin.update_attributes(administrator_params)
end
if admin_passed
clear_cache
profile_images(params, @admin)
format.html { redirect_to edit_admin_administrator_path(@admin), notice: I18n.t("controllers.admin.administrators.update.flash.success") }
else
@action = 'update'
format.html {
# add breadcrumb and set title
add_breadcrumb I18n.t("controllers.admin.administrators.edit.breadcrumb")
flash[:error] = I18n.t('generic.validation.no_passed')
render action: "edit"
}
end
end
end | ruby | def update
@admin = Admin.find(params[:id])
@admin.deal_with_cover params
respond_to do |format|
admin_passed =
if params[:admin][:password].blank?
@admin.update_without_password(administrator_params)
else
@admin.update_attributes(administrator_params)
end
if admin_passed
clear_cache
profile_images(params, @admin)
format.html { redirect_to edit_admin_administrator_path(@admin), notice: I18n.t("controllers.admin.administrators.update.flash.success") }
else
@action = 'update'
format.html {
# add breadcrumb and set title
add_breadcrumb I18n.t("controllers.admin.administrators.edit.breadcrumb")
flash[:error] = I18n.t('generic.validation.no_passed')
render action: "edit"
}
end
end
end | [
"def",
"update",
"@admin",
"=",
"Admin",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@admin",
".",
"deal_with_cover",
"params",
"respond_to",
"do",
"|",
"format",
"|",
"admin_passed",
"=",
"if",
"params",
"[",
":admin",
"]",
"[",
":password",
"]",
".",
"blank?",
"@admin",
".",
"update_without_password",
"(",
"administrator_params",
")",
"else",
"@admin",
".",
"update_attributes",
"(",
"administrator_params",
")",
"end",
"if",
"admin_passed",
"clear_cache",
"profile_images",
"(",
"params",
",",
"@admin",
")",
"format",
".",
"html",
"{",
"redirect_to",
"edit_admin_administrator_path",
"(",
"@admin",
")",
",",
"notice",
":",
"I18n",
".",
"t",
"(",
"\"controllers.admin.administrators.update.flash.success\"",
")",
"}",
"else",
"@action",
"=",
"'update'",
"format",
".",
"html",
"{",
"add_breadcrumb",
"I18n",
".",
"t",
"(",
"\"controllers.admin.administrators.edit.breadcrumb\"",
")",
"flash",
"[",
":error",
"]",
"=",
"I18n",
".",
"t",
"(",
"'generic.validation.no_passed'",
")",
"render",
"action",
":",
"\"edit\"",
"}",
"end",
"end",
"end"
] | update the admins object | [
"update",
"the",
"admins",
"object"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/administrators_controller.rb#L92-L124 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/administrators_controller.rb | Roroacms.Admin::AdministratorsController.destroy | def destroy
@admin = Admin.find(params[:id])
@admin.destroy if @admin.overlord == 'N'
respond_to do |format|
format.html { redirect_to admin_administrators_path, notice: I18n.t("controllers.admin.administrators.destroy.flash.success") }
end
end | ruby | def destroy
@admin = Admin.find(params[:id])
@admin.destroy if @admin.overlord == 'N'
respond_to do |format|
format.html { redirect_to admin_administrators_path, notice: I18n.t("controllers.admin.administrators.destroy.flash.success") }
end
end | [
"def",
"destroy",
"@admin",
"=",
"Admin",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@admin",
".",
"destroy",
"if",
"@admin",
".",
"overlord",
"==",
"'N'",
"respond_to",
"do",
"|",
"format",
"|",
"format",
".",
"html",
"{",
"redirect_to",
"admin_administrators_path",
",",
"notice",
":",
"I18n",
".",
"t",
"(",
"\"controllers.admin.administrators.destroy.flash.success\"",
")",
"}",
"end",
"end"
] | Delete the admin, one thing to remember is you are not allowed to destory the overlord.
You are only allowed to destroy yourself unless you are the overlord. | [
"Delete",
"the",
"admin",
"one",
"thing",
"to",
"remember",
"is",
"you",
"are",
"not",
"allowed",
"to",
"destory",
"the",
"overlord",
".",
"You",
"are",
"only",
"allowed",
"to",
"destroy",
"yourself",
"unless",
"you",
"are",
"the",
"overlord",
"."
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/administrators_controller.rb#L130-L137 | train |
barkerest/shells | lib/shells/pf_shell_wrapper.rb | Shells.PfShellWrapper.exec | def exec(*commands)
ret = ''
commands.each { |cmd| ret += shell.exec(cmd) }
ret + shell.exec('exec')
end | ruby | def exec(*commands)
ret = ''
commands.each { |cmd| ret += shell.exec(cmd) }
ret + shell.exec('exec')
end | [
"def",
"exec",
"(",
"*",
"commands",
")",
"ret",
"=",
"''",
"commands",
".",
"each",
"{",
"|",
"cmd",
"|",
"ret",
"+=",
"shell",
".",
"exec",
"(",
"cmd",
")",
"}",
"ret",
"+",
"shell",
".",
"exec",
"(",
"'exec'",
")",
"end"
] | Creates the wrapper, executing the pfSense shell.
The provided code block is yielded this wrapper for execution.
Executes a series of commands on the pfSense shell. | [
"Creates",
"the",
"wrapper",
"executing",
"the",
"pfSense",
"shell",
"."
] | 674a0254f48cea01b0ae8979933f13892e398506 | https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/pf_shell_wrapper.rb#L72-L76 | train |
barkerest/shells | lib/shells/pf_shell_wrapper.rb | Shells.PfShellWrapper.set_config_section | def set_config_section(section_name, values, message = '')
current_values = get_config_section(section_name)
changes = generate_config_changes("$config[#{section_name.to_s.inspect}]", current_values, values)
if changes&.any?
if message.to_s.strip == ''
message = "Updating #{section_name} section."
end
changes << "write_config(#{message.inspect});"
exec(*changes)
(changes.size - 1)
else
0
end
end | ruby | def set_config_section(section_name, values, message = '')
current_values = get_config_section(section_name)
changes = generate_config_changes("$config[#{section_name.to_s.inspect}]", current_values, values)
if changes&.any?
if message.to_s.strip == ''
message = "Updating #{section_name} section."
end
changes << "write_config(#{message.inspect});"
exec(*changes)
(changes.size - 1)
else
0
end
end | [
"def",
"set_config_section",
"(",
"section_name",
",",
"values",
",",
"message",
"=",
"''",
")",
"current_values",
"=",
"get_config_section",
"(",
"section_name",
")",
"changes",
"=",
"generate_config_changes",
"(",
"\"$config[#{section_name.to_s.inspect}]\"",
",",
"current_values",
",",
"values",
")",
"if",
"changes",
"&.",
"any?",
"if",
"message",
".",
"to_s",
".",
"strip",
"==",
"''",
"message",
"=",
"\"Updating #{section_name} section.\"",
"end",
"changes",
"<<",
"\"write_config(#{message.inspect});\"",
"exec",
"(",
"*",
"changes",
")",
"(",
"changes",
".",
"size",
"-",
"1",
")",
"else",
"0",
"end",
"end"
] | Sets a configuration section to the pfSense device.
Returns the number of changes made to the configuration. | [
"Sets",
"a",
"configuration",
"section",
"to",
"the",
"pfSense",
"device",
"."
] | 674a0254f48cea01b0ae8979933f13892e398506 | https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/pf_shell_wrapper.rb#L102-L117 | train |
barkerest/shells | lib/shells/pf_shell_wrapper.rb | Shells.PfShellWrapper.enable_cert_auth | def enable_cert_auth(public_key = '~/.ssh/id_rsa.pub')
cert_regex = /^ssh-[rd]sa (?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)? \S*$/m
# get our cert unless the user provided a full cert for us.
unless public_key =~ cert_regex
public_key = File.expand_path(public_key)
if File.exist?(public_key)
public_key = File.read(public_key).to_s.strip
else
raise Shells::PfSenseCommon::PublicKeyNotFound
end
raise Shells::PfSenseCommon::PublicKeyInvalid unless public_key =~ cert_regex
end
cfg = get_config_section 'system'
user_id = nil
user_name = options[:user].downcase
cfg['user'].each_with_index do |user,index|
if user['name'].downcase == user_name
user_id = index
authkeys = Base64.decode64(user['authorizedkeys'].to_s).gsub("\r\n", "\n").strip
unless authkeys == '' || authkeys =~ cert_regex
warn "Existing authorized keys for user #{options[:user]} are invalid and are being reset."
authkeys = ''
end
if authkeys == ''
user['authorizedkeys'] = Base64.strict_encode64(public_key)
else
authkeys = authkeys.split("\n")
unless authkeys.include?(public_key)
authkeys << public_key unless authkeys.include?(public_key)
user['authorizedkeys'] = Base64.strict_encode64(authkeys.join("\n"))
end
end
break
end
end
raise Shells::PfSenseCommon::UserNotFound unless user_id
set_config_section 'system', cfg, "Enable certificate authentication for #{options[:user]}."
apply_user_config user_id
end | ruby | def enable_cert_auth(public_key = '~/.ssh/id_rsa.pub')
cert_regex = /^ssh-[rd]sa (?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)? \S*$/m
# get our cert unless the user provided a full cert for us.
unless public_key =~ cert_regex
public_key = File.expand_path(public_key)
if File.exist?(public_key)
public_key = File.read(public_key).to_s.strip
else
raise Shells::PfSenseCommon::PublicKeyNotFound
end
raise Shells::PfSenseCommon::PublicKeyInvalid unless public_key =~ cert_regex
end
cfg = get_config_section 'system'
user_id = nil
user_name = options[:user].downcase
cfg['user'].each_with_index do |user,index|
if user['name'].downcase == user_name
user_id = index
authkeys = Base64.decode64(user['authorizedkeys'].to_s).gsub("\r\n", "\n").strip
unless authkeys == '' || authkeys =~ cert_regex
warn "Existing authorized keys for user #{options[:user]} are invalid and are being reset."
authkeys = ''
end
if authkeys == ''
user['authorizedkeys'] = Base64.strict_encode64(public_key)
else
authkeys = authkeys.split("\n")
unless authkeys.include?(public_key)
authkeys << public_key unless authkeys.include?(public_key)
user['authorizedkeys'] = Base64.strict_encode64(authkeys.join("\n"))
end
end
break
end
end
raise Shells::PfSenseCommon::UserNotFound unless user_id
set_config_section 'system', cfg, "Enable certificate authentication for #{options[:user]}."
apply_user_config user_id
end | [
"def",
"enable_cert_auth",
"(",
"public_key",
"=",
"'~/.ssh/id_rsa.pub'",
")",
"cert_regex",
"=",
"/",
"\\/",
"\\/",
"\\/",
"\\S",
"/m",
"unless",
"public_key",
"=~",
"cert_regex",
"public_key",
"=",
"File",
".",
"expand_path",
"(",
"public_key",
")",
"if",
"File",
".",
"exist?",
"(",
"public_key",
")",
"public_key",
"=",
"File",
".",
"read",
"(",
"public_key",
")",
".",
"to_s",
".",
"strip",
"else",
"raise",
"Shells",
"::",
"PfSenseCommon",
"::",
"PublicKeyNotFound",
"end",
"raise",
"Shells",
"::",
"PfSenseCommon",
"::",
"PublicKeyInvalid",
"unless",
"public_key",
"=~",
"cert_regex",
"end",
"cfg",
"=",
"get_config_section",
"'system'",
"user_id",
"=",
"nil",
"user_name",
"=",
"options",
"[",
":user",
"]",
".",
"downcase",
"cfg",
"[",
"'user'",
"]",
".",
"each_with_index",
"do",
"|",
"user",
",",
"index",
"|",
"if",
"user",
"[",
"'name'",
"]",
".",
"downcase",
"==",
"user_name",
"user_id",
"=",
"index",
"authkeys",
"=",
"Base64",
".",
"decode64",
"(",
"user",
"[",
"'authorizedkeys'",
"]",
".",
"to_s",
")",
".",
"gsub",
"(",
"\"\\r\\n\"",
",",
"\"\\n\"",
")",
".",
"strip",
"unless",
"authkeys",
"==",
"''",
"||",
"authkeys",
"=~",
"cert_regex",
"warn",
"\"Existing authorized keys for user #{options[:user]} are invalid and are being reset.\"",
"authkeys",
"=",
"''",
"end",
"if",
"authkeys",
"==",
"''",
"user",
"[",
"'authorizedkeys'",
"]",
"=",
"Base64",
".",
"strict_encode64",
"(",
"public_key",
")",
"else",
"authkeys",
"=",
"authkeys",
".",
"split",
"(",
"\"\\n\"",
")",
"unless",
"authkeys",
".",
"include?",
"(",
"public_key",
")",
"authkeys",
"<<",
"public_key",
"unless",
"authkeys",
".",
"include?",
"(",
"public_key",
")",
"user",
"[",
"'authorizedkeys'",
"]",
"=",
"Base64",
".",
"strict_encode64",
"(",
"authkeys",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"end",
"end",
"break",
"end",
"end",
"raise",
"Shells",
"::",
"PfSenseCommon",
"::",
"UserNotFound",
"unless",
"user_id",
"set_config_section",
"'system'",
",",
"cfg",
",",
"\"Enable certificate authentication for #{options[:user]}.\"",
"apply_user_config",
"user_id",
"end"
] | Enabled public key authentication for the current pfSense user.
Once this has been done you should be able to connect without using a password. | [
"Enabled",
"public",
"key",
"authentication",
"for",
"the",
"current",
"pfSense",
"user",
"."
] | 674a0254f48cea01b0ae8979933f13892e398506 | https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/pf_shell_wrapper.rb#L155-L202 | train |
barkerest/barkest_core | app/helpers/barkest_core/html_helper.rb | BarkestCore.HtmlHelper.glyph | def glyph(name, size = nil)
size = size.to_s.downcase
if %w(small smaller big bigger).include?(size)
size = ' glyph-' + size
else
size = ''
end
"<i class=\"glyphicon glyphicon-#{h name}#{size}\"></i>".html_safe
end | ruby | def glyph(name, size = nil)
size = size.to_s.downcase
if %w(small smaller big bigger).include?(size)
size = ' glyph-' + size
else
size = ''
end
"<i class=\"glyphicon glyphicon-#{h name}#{size}\"></i>".html_safe
end | [
"def",
"glyph",
"(",
"name",
",",
"size",
"=",
"nil",
")",
"size",
"=",
"size",
".",
"to_s",
".",
"downcase",
"if",
"%w(",
"small",
"smaller",
"big",
"bigger",
")",
".",
"include?",
"(",
"size",
")",
"size",
"=",
"' glyph-'",
"+",
"size",
"else",
"size",
"=",
"''",
"end",
"\"<i class=\\\"glyphicon glyphicon-#{h name}#{size}\\\"></i>\"",
".",
"html_safe",
"end"
] | Creates a glyph icon using the specified +name+ and +size+.
The +size+ can be nil, :small, :smaller, :big, or :bigger.
The default size is nil. | [
"Creates",
"a",
"glyph",
"icon",
"using",
"the",
"specified",
"+",
"name",
"+",
"and",
"+",
"size",
"+",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/html_helper.rb#L11-L19 | train |
timotheeguerin/clin | lib/clin/command_mixin/options.rb | Clin::CommandMixin::Options.ClassMethods.list_option | def list_option(name, description, **config)
add_option Clin::OptionList.new(name, description, **config)
end | ruby | def list_option(name, description, **config)
add_option Clin::OptionList.new(name, description, **config)
end | [
"def",
"list_option",
"(",
"name",
",",
"description",
",",
"**",
"config",
")",
"add_option",
"Clin",
"::",
"OptionList",
".",
"new",
"(",
"name",
",",
"description",
",",
"**",
"config",
")",
"end"
] | Add a list option.
@see Clin::OptionList#initialize | [
"Add",
"a",
"list",
"option",
"."
] | 43d41c47f9c652065ab7ce636d48a9fe1754135e | https://github.com/timotheeguerin/clin/blob/43d41c47f9c652065ab7ce636d48a9fe1754135e/lib/clin/command_mixin/options.rb#L53-L55 | train |
timotheeguerin/clin | lib/clin/command_mixin/options.rb | Clin::CommandMixin::Options.ClassMethods.list_flag_option | def list_flag_option(name, description, **config)
add_option Clin::OptionList.new(name, description, **config.merge(argument: false))
end | ruby | def list_flag_option(name, description, **config)
add_option Clin::OptionList.new(name, description, **config.merge(argument: false))
end | [
"def",
"list_flag_option",
"(",
"name",
",",
"description",
",",
"**",
"config",
")",
"add_option",
"Clin",
"::",
"OptionList",
".",
"new",
"(",
"name",
",",
"description",
",",
"**",
"config",
".",
"merge",
"(",
"argument",
":",
"false",
")",
")",
"end"
] | Add a list options that don't take arguments
Same as .list_option but set +argument+ to false
@see Clin::OptionList#initialize | [
"Add",
"a",
"list",
"options",
"that",
"don",
"t",
"take",
"arguments",
"Same",
"as",
".",
"list_option",
"but",
"set",
"+",
"argument",
"+",
"to",
"false"
] | 43d41c47f9c652065ab7ce636d48a9fe1754135e | https://github.com/timotheeguerin/clin/blob/43d41c47f9c652065ab7ce636d48a9fe1754135e/lib/clin/command_mixin/options.rb#L60-L62 | train |
timotheeguerin/clin | lib/clin/command_mixin/options.rb | Clin::CommandMixin::Options.ClassMethods.general_option | def general_option(option_cls, config = {})
option_cls = option_cls.constantize if option_cls.is_a? String
@general_options[option_cls] = option_cls.new(config)
end | ruby | def general_option(option_cls, config = {})
option_cls = option_cls.constantize if option_cls.is_a? String
@general_options[option_cls] = option_cls.new(config)
end | [
"def",
"general_option",
"(",
"option_cls",
",",
"config",
"=",
"{",
"}",
")",
"option_cls",
"=",
"option_cls",
".",
"constantize",
"if",
"option_cls",
".",
"is_a?",
"String",
"@general_options",
"[",
"option_cls",
"]",
"=",
"option_cls",
".",
"new",
"(",
"config",
")",
"end"
] | Add a general option
@param option_cls [Class<GeneralOption>] Class inherited from GeneralOption
@param config [Hash] General option config. Check the general option config. | [
"Add",
"a",
"general",
"option"
] | 43d41c47f9c652065ab7ce636d48a9fe1754135e | https://github.com/timotheeguerin/clin/blob/43d41c47f9c652065ab7ce636d48a9fe1754135e/lib/clin/command_mixin/options.rb#L78-L81 | train |
timotheeguerin/clin | lib/clin/command_mixin/options.rb | Clin::CommandMixin::Options.ClassMethods.remove_general_option | def remove_general_option(option_cls)
option_cls = option_cls.constantize if option_cls.is_a? String
@general_options.delete(option_cls)
end | ruby | def remove_general_option(option_cls)
option_cls = option_cls.constantize if option_cls.is_a? String
@general_options.delete(option_cls)
end | [
"def",
"remove_general_option",
"(",
"option_cls",
")",
"option_cls",
"=",
"option_cls",
".",
"constantize",
"if",
"option_cls",
".",
"is_a?",
"String",
"@general_options",
".",
"delete",
"(",
"option_cls",
")",
"end"
] | Remove a general option
Might be useful if a parent added the option but is not needed in this child. | [
"Remove",
"a",
"general",
"option",
"Might",
"be",
"useful",
"if",
"a",
"parent",
"added",
"the",
"option",
"but",
"is",
"not",
"needed",
"in",
"this",
"child",
"."
] | 43d41c47f9c652065ab7ce636d48a9fe1754135e | https://github.com/timotheeguerin/clin/blob/43d41c47f9c652065ab7ce636d48a9fe1754135e/lib/clin/command_mixin/options.rb#L85-L88 | train |
timotheeguerin/clin | lib/clin/command_mixin/options.rb | Clin::CommandMixin::Options.ClassMethods.option_defaults | def option_defaults
out = {}
@specific_options.each do |option|
option.load_default(out)
end
@general_options.each do |_cls, option|
out.merge! option.class.option_defaults
end
out
end | ruby | def option_defaults
out = {}
@specific_options.each do |option|
option.load_default(out)
end
@general_options.each do |_cls, option|
out.merge! option.class.option_defaults
end
out
end | [
"def",
"option_defaults",
"out",
"=",
"{",
"}",
"@specific_options",
".",
"each",
"do",
"|",
"option",
"|",
"option",
".",
"load_default",
"(",
"out",
")",
"end",
"@general_options",
".",
"each",
"do",
"|",
"_cls",
",",
"option",
"|",
"out",
".",
"merge!",
"option",
".",
"class",
".",
"option_defaults",
"end",
"out",
"end"
] | To be called inside OptionParser block
Extract the option in the command line using the OptionParser and map it to the out map.
@return [Hash] Where the options shall be extracted | [
"To",
"be",
"called",
"inside",
"OptionParser",
"block",
"Extract",
"the",
"option",
"in",
"the",
"command",
"line",
"using",
"the",
"OptionParser",
"and",
"map",
"it",
"to",
"the",
"out",
"map",
"."
] | 43d41c47f9c652065ab7ce636d48a9fe1754135e | https://github.com/timotheeguerin/clin/blob/43d41c47f9c652065ab7ce636d48a9fe1754135e/lib/clin/command_mixin/options.rb#L93-L103 | train |
dmerrick/lights_app | lib/philips_hue/bridge.rb | PhilipsHue.Bridge.add_all_lights | def add_all_lights
all_lights = []
overview["lights"].each do |id, light|
all_lights << add_light(id.to_i, light["name"])
end
all_lights
end | ruby | def add_all_lights
all_lights = []
overview["lights"].each do |id, light|
all_lights << add_light(id.to_i, light["name"])
end
all_lights
end | [
"def",
"add_all_lights",
"all_lights",
"=",
"[",
"]",
"overview",
"[",
"\"lights\"",
"]",
".",
"each",
"do",
"|",
"id",
",",
"light",
"|",
"all_lights",
"<<",
"add_light",
"(",
"id",
".",
"to_i",
",",
"light",
"[",
"\"name\"",
"]",
")",
"end",
"all_lights",
"end"
] | loop through the available lights and make corresponding objects | [
"loop",
"through",
"the",
"available",
"lights",
"and",
"make",
"corresponding",
"objects"
] | 0bcbc566fa3964c74f7cfe73708d5ad1a7ce696d | https://github.com/dmerrick/lights_app/blob/0bcbc566fa3964c74f7cfe73708d5ad1a7ce696d/lib/philips_hue/bridge.rb#L143-L149 | train |
ramhoj/table_for | lib/table_for/helper.rb | TableFor.Helper.table_for | def table_for(model_class, records, html = {}, &block)
Table.new(self, model_class, records, html, block).render
end | ruby | def table_for(model_class, records, html = {}, &block)
Table.new(self, model_class, records, html, block).render
end | [
"def",
"table_for",
"(",
"model_class",
",",
"records",
",",
"html",
"=",
"{",
"}",
",",
"&",
"block",
")",
"Table",
".",
"new",
"(",
"self",
",",
"model_class",
",",
"records",
",",
"html",
",",
"block",
")",
".",
"render",
"end"
] | Create a html table for records, using model class for naming things.
Examples:
<tt>table_for Product, @products do |table|
table.head :name, :size, :description, :price
table.body do |row|
row.cell :name
row.cells :size, :description
row.cell number_to_currency(row.record.price)
end
table.foot do
link_to "Add product", new_product_path
end
end</tt>
<tt>table_for Product, @products do |table|
table.columns :name, :size, :description, :price
table.foot do
link_to "Add product", new_product_path
end
end</tt>
Returns:
A string containing the html table
(Call this method from your erb templates by wrapping each line in <%= %> or <% %>) | [
"Create",
"a",
"html",
"table",
"for",
"records",
"using",
"model",
"class",
"for",
"naming",
"things",
"."
] | be9f53834f0d2cb2e0d900d4a0340ede7302d7f1 | https://github.com/ramhoj/table_for/blob/be9f53834f0d2cb2e0d900d4a0340ede7302d7f1/lib/table_for/helper.rb#L36-L38 | train |
jinx/core | lib/jinx/resource/unique.rb | Jinx.Unique.uniquify_attributes | def uniquify_attributes(attributes)
attributes.each do |ka|
oldval = send(ka)
next unless String === oldval
newval = UniquifierCache.instance.get(self, oldval)
set_property_value(ka, newval)
logger.debug { "Reset #{qp} #{ka} from #{oldval} to unique value #{newval}." }
end
end | ruby | def uniquify_attributes(attributes)
attributes.each do |ka|
oldval = send(ka)
next unless String === oldval
newval = UniquifierCache.instance.get(self, oldval)
set_property_value(ka, newval)
logger.debug { "Reset #{qp} #{ka} from #{oldval} to unique value #{newval}." }
end
end | [
"def",
"uniquify_attributes",
"(",
"attributes",
")",
"attributes",
".",
"each",
"do",
"|",
"ka",
"|",
"oldval",
"=",
"send",
"(",
"ka",
")",
"next",
"unless",
"String",
"===",
"oldval",
"newval",
"=",
"UniquifierCache",
".",
"instance",
".",
"get",
"(",
"self",
",",
"oldval",
")",
"set_property_value",
"(",
"ka",
",",
"newval",
")",
"logger",
".",
"debug",
"{",
"\"Reset #{qp} #{ka} from #{oldval} to unique value #{newval}.\"",
"}",
"end",
"end"
] | Makes this domain object's String values for the given attributes unique.
@param [<Symbol>] the key attributes to uniquify | [
"Makes",
"this",
"domain",
"object",
"s",
"String",
"values",
"for",
"the",
"given",
"attributes",
"unique",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource/unique.rb#L22-L30 | train |
hokstadconsulting/purecdb | lib/purecdb/writer.rb | PureCDB.Writer.store | def store key,value
# In an attempt to save memory, we pack the hash data we gather into
# strings of BER compressed integers...
h = hash(key)
hi = (h % num_hashes)
@hashes[hi] ||= ""
header = build_header(key.length, value.length)
@io.syswrite(header+key+value)
size = header.size + key.size + value.size
@hashes[hi] += [h,@pos].pack("ww") # BER compressed
@pos += size
end | ruby | def store key,value
# In an attempt to save memory, we pack the hash data we gather into
# strings of BER compressed integers...
h = hash(key)
hi = (h % num_hashes)
@hashes[hi] ||= ""
header = build_header(key.length, value.length)
@io.syswrite(header+key+value)
size = header.size + key.size + value.size
@hashes[hi] += [h,@pos].pack("ww") # BER compressed
@pos += size
end | [
"def",
"store",
"key",
",",
"value",
"h",
"=",
"hash",
"(",
"key",
")",
"hi",
"=",
"(",
"h",
"%",
"num_hashes",
")",
"@hashes",
"[",
"hi",
"]",
"||=",
"\"\"",
"header",
"=",
"build_header",
"(",
"key",
".",
"length",
",",
"value",
".",
"length",
")",
"@io",
".",
"syswrite",
"(",
"header",
"+",
"key",
"+",
"value",
")",
"size",
"=",
"header",
".",
"size",
"+",
"key",
".",
"size",
"+",
"value",
".",
"size",
"@hashes",
"[",
"hi",
"]",
"+=",
"[",
"h",
",",
"@pos",
"]",
".",
"pack",
"(",
"\"ww\"",
")",
"@pos",
"+=",
"size",
"end"
] | Store 'value' under 'key'.
Multiple values can we stored for the same key by calling #store multiple times
with the same key value. | [
"Store",
"value",
"under",
"key",
"."
] | d19102e5dffbb2f0de4fab4f86c603880c3ffea8 | https://github.com/hokstadconsulting/purecdb/blob/d19102e5dffbb2f0de4fab4f86c603880c3ffea8/lib/purecdb/writer.rb#L92-L104 | train |
bordeeinc/ico | lib/ico/utils.rb | ICO.Utils.png_to_sizes | def png_to_sizes(input_filename, sizes_array, output_dirname=nil, append_filenames=APPEND_FILE_FORMAT, force_overwrite=false, clear=true, force_clear=false)
basename = File.basename(input_filename, '.*')
output_dirname ||= File.join(File.expand_path(File.dirname(input_filename)), "#{basename}_sizes")
# ensure dir exists
FileUtils.mkdir_p(output_dirname)
# ensure dir empty
if clear
filename_array = Dir.glob(File.join(output_dirname, '**/*'))
unless force_clear
# protect from destructive action
raise "more than ICO format files in #{output_dirname}" if contains_other_than_ext?(filename_array, :ico)
end
FileUtils.rm_rf(filename_array)
end
# import base image
img = ChunkyPNG::Image.from_file(input_filename)
# resize
sizes_array.each do |x,y|
y ||= x
img_attrs = {:x => x, :y => y}
bn = basename + Kernel.sprintf(append_filenames, img_attrs)
fn = File.join(output_dirname, "#{bn}.png")
img_out = img.resample_nearest_neighbor(x, y)
unless force_overwrite
raise "File exists: #{fn}" if File.exist?(fn)
end
IO.write(fn, img_out)
end
return output_dirname
end | ruby | def png_to_sizes(input_filename, sizes_array, output_dirname=nil, append_filenames=APPEND_FILE_FORMAT, force_overwrite=false, clear=true, force_clear=false)
basename = File.basename(input_filename, '.*')
output_dirname ||= File.join(File.expand_path(File.dirname(input_filename)), "#{basename}_sizes")
# ensure dir exists
FileUtils.mkdir_p(output_dirname)
# ensure dir empty
if clear
filename_array = Dir.glob(File.join(output_dirname, '**/*'))
unless force_clear
# protect from destructive action
raise "more than ICO format files in #{output_dirname}" if contains_other_than_ext?(filename_array, :ico)
end
FileUtils.rm_rf(filename_array)
end
# import base image
img = ChunkyPNG::Image.from_file(input_filename)
# resize
sizes_array.each do |x,y|
y ||= x
img_attrs = {:x => x, :y => y}
bn = basename + Kernel.sprintf(append_filenames, img_attrs)
fn = File.join(output_dirname, "#{bn}.png")
img_out = img.resample_nearest_neighbor(x, y)
unless force_overwrite
raise "File exists: #{fn}" if File.exist?(fn)
end
IO.write(fn, img_out)
end
return output_dirname
end | [
"def",
"png_to_sizes",
"(",
"input_filename",
",",
"sizes_array",
",",
"output_dirname",
"=",
"nil",
",",
"append_filenames",
"=",
"APPEND_FILE_FORMAT",
",",
"force_overwrite",
"=",
"false",
",",
"clear",
"=",
"true",
",",
"force_clear",
"=",
"false",
")",
"basename",
"=",
"File",
".",
"basename",
"(",
"input_filename",
",",
"'.*'",
")",
"output_dirname",
"||=",
"File",
".",
"join",
"(",
"File",
".",
"expand_path",
"(",
"File",
".",
"dirname",
"(",
"input_filename",
")",
")",
",",
"\"#{basename}_sizes\"",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"output_dirname",
")",
"if",
"clear",
"filename_array",
"=",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"output_dirname",
",",
"'**/*'",
")",
")",
"unless",
"force_clear",
"raise",
"\"more than ICO format files in #{output_dirname}\"",
"if",
"contains_other_than_ext?",
"(",
"filename_array",
",",
":ico",
")",
"end",
"FileUtils",
".",
"rm_rf",
"(",
"filename_array",
")",
"end",
"img",
"=",
"ChunkyPNG",
"::",
"Image",
".",
"from_file",
"(",
"input_filename",
")",
"sizes_array",
".",
"each",
"do",
"|",
"x",
",",
"y",
"|",
"y",
"||=",
"x",
"img_attrs",
"=",
"{",
":x",
"=>",
"x",
",",
":y",
"=>",
"y",
"}",
"bn",
"=",
"basename",
"+",
"Kernel",
".",
"sprintf",
"(",
"append_filenames",
",",
"img_attrs",
")",
"fn",
"=",
"File",
".",
"join",
"(",
"output_dirname",
",",
"\"#{bn}.png\"",
")",
"img_out",
"=",
"img",
".",
"resample_nearest_neighbor",
"(",
"x",
",",
"y",
")",
"unless",
"force_overwrite",
"raise",
"\"File exists: #{fn}\"",
"if",
"File",
".",
"exist?",
"(",
"fn",
")",
"end",
"IO",
".",
"write",
"(",
"fn",
",",
"img_out",
")",
"end",
"return",
"output_dirname",
"end"
] | resize PNG file and write new sizes to directory
@see https://ruby-doc.org/core-2.2.0/Kernel.html#method-i-sprintf
@param input_filename [String] input filename; required: file is PNG file format
@param sizes_array [Array<Array<Integer,Integer]>>, Array<Integer>]
rectangles use Array with XY: `[x,y]`
squares use single Integer `N`
mixed indices is valid
example: `[24, [24,24], [480,270], 888] # a[0] => 24x24; a[1] => 24x24; a[2] => 480x270; a[3] => 888x888`
@param output_dirname [String] (optional)
directory name including expanded path
default: new dir named input_filename's basename + "_sizes" in same dir as input_filename
@param append_filenames [String] (optional,required-with-supplied-default)
append resized filenames with Kernel#sprintf format_string
available args: `{:x => N, :y => N}`
default: `"-%<x>dx%<y>d"`
@param force_overwrite [Boolean] overwrite existing resized images
@param clear [Boolean] default: `true`
@param force_clear [Boolean] clear output_dirname of contents before write; default: false
@return [String] output_dirname; default: false | [
"resize",
"PNG",
"file",
"and",
"write",
"new",
"sizes",
"to",
"directory"
] | 008760fafafbb3d3e561e97e3596ffe43f4c21ef | https://github.com/bordeeinc/ico/blob/008760fafafbb3d3e561e97e3596ffe43f4c21ef/lib/ico/utils.rb#L104-L143 | train |
jinx/core | lib/jinx/helpers/pretty_print.rb | Jinx.Hasher.qp | def qp
qph = {}
each { |k, v| qph[k.qp] = v.qp }
qph.pp_s
end | ruby | def qp
qph = {}
each { |k, v| qph[k.qp] = v.qp }
qph.pp_s
end | [
"def",
"qp",
"qph",
"=",
"{",
"}",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"qph",
"[",
"k",
".",
"qp",
"]",
"=",
"v",
".",
"qp",
"}",
"qph",
".",
"pp_s",
"end"
] | qp, short for quick-print, prints this Hasher with a filter that calls qp on each key and value.
@return [String] the quick-print result | [
"qp",
"short",
"for",
"quick",
"-",
"print",
"prints",
"this",
"Hasher",
"with",
"a",
"filter",
"that",
"calls",
"qp",
"on",
"each",
"key",
"and",
"value",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/pretty_print.rb#L161-L165 | train |
subimage/cashboard-rb | lib/cashboard/base.rb | Cashboard.Base.update | def update
options = self.class.merge_options()
options.merge!({:body => self.to_xml})
response = self.class.put(self.href, options)
begin
self.class.check_status_code(response)
rescue
return false
end
return true
end | ruby | def update
options = self.class.merge_options()
options.merge!({:body => self.to_xml})
response = self.class.put(self.href, options)
begin
self.class.check_status_code(response)
rescue
return false
end
return true
end | [
"def",
"update",
"options",
"=",
"self",
".",
"class",
".",
"merge_options",
"(",
")",
"options",
".",
"merge!",
"(",
"{",
":body",
"=>",
"self",
".",
"to_xml",
"}",
")",
"response",
"=",
"self",
".",
"class",
".",
"put",
"(",
"self",
".",
"href",
",",
"options",
")",
"begin",
"self",
".",
"class",
".",
"check_status_code",
"(",
"response",
")",
"rescue",
"return",
"false",
"end",
"return",
"true",
"end"
] | Updates the object on server, after attributes have been set.
Returns boolean if successful
Example:
te = Cashboard::TimeEntry.new_from_url(time_entry_url)
te.minutes = 60
update_success = te.update | [
"Updates",
"the",
"object",
"on",
"server",
"after",
"attributes",
"have",
"been",
"set",
".",
"Returns",
"boolean",
"if",
"successful"
] | 320e311ea1549cdd0dada0f8a0a4f9942213b28f | https://github.com/subimage/cashboard-rb/blob/320e311ea1549cdd0dada0f8a0a4f9942213b28f/lib/cashboard/base.rb#L96-L106 | train |
subimage/cashboard-rb | lib/cashboard/base.rb | Cashboard.Base.delete | def delete
options = self.class.merge_options()
response = self.class.delete(self.href, options)
begin
self.class.check_status_code(response)
rescue
return false
end
return true
end | ruby | def delete
options = self.class.merge_options()
response = self.class.delete(self.href, options)
begin
self.class.check_status_code(response)
rescue
return false
end
return true
end | [
"def",
"delete",
"options",
"=",
"self",
".",
"class",
".",
"merge_options",
"(",
")",
"response",
"=",
"self",
".",
"class",
".",
"delete",
"(",
"self",
".",
"href",
",",
"options",
")",
"begin",
"self",
".",
"class",
".",
"check_status_code",
"(",
"response",
")",
"rescue",
"return",
"false",
"end",
"return",
"true",
"end"
] | Destroys Cashboard object on the server.
Returns boolean upon success. | [
"Destroys",
"Cashboard",
"object",
"on",
"the",
"server",
".",
"Returns",
"boolean",
"upon",
"success",
"."
] | 320e311ea1549cdd0dada0f8a0a4f9942213b28f | https://github.com/subimage/cashboard-rb/blob/320e311ea1549cdd0dada0f8a0a4f9942213b28f/lib/cashboard/base.rb#L110-L119 | train |
subimage/cashboard-rb | lib/cashboard/base.rb | Cashboard.Base.to_xml | def to_xml(options={})
options[:indent] ||= 2
xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
xml.instruct! unless options[:skip_instruct]
obj_name = self.class.resource_name.singularize
# Turn our OpenStruct attributes into a hash we can export to XML
obj_attrs = self.marshal_dump
xml.tag!(obj_name) do
obj_attrs.each do |key,value|
next if key.to_sym == :link # Don't feed back links to server
case value
when ::Hash
value.to_xml(
options.merge({
:root => key,
:skip_instruct => true
})
)
when ::Array
value.to_xml(
options.merge({
:root => key,
:children => key.to_s.singularize,
:skip_instruct => true
})
)
else
xml.tag!(key, value)
end
end
end
end | ruby | def to_xml(options={})
options[:indent] ||= 2
xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
xml.instruct! unless options[:skip_instruct]
obj_name = self.class.resource_name.singularize
# Turn our OpenStruct attributes into a hash we can export to XML
obj_attrs = self.marshal_dump
xml.tag!(obj_name) do
obj_attrs.each do |key,value|
next if key.to_sym == :link # Don't feed back links to server
case value
when ::Hash
value.to_xml(
options.merge({
:root => key,
:skip_instruct => true
})
)
when ::Array
value.to_xml(
options.merge({
:root => key,
:children => key.to_s.singularize,
:skip_instruct => true
})
)
else
xml.tag!(key, value)
end
end
end
end | [
"def",
"to_xml",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":indent",
"]",
"||=",
"2",
"xml",
"=",
"options",
"[",
":builder",
"]",
"||=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"(",
":indent",
"=>",
"options",
"[",
":indent",
"]",
")",
"xml",
".",
"instruct!",
"unless",
"options",
"[",
":skip_instruct",
"]",
"obj_name",
"=",
"self",
".",
"class",
".",
"resource_name",
".",
"singularize",
"obj_attrs",
"=",
"self",
".",
"marshal_dump",
"xml",
".",
"tag!",
"(",
"obj_name",
")",
"do",
"obj_attrs",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"next",
"if",
"key",
".",
"to_sym",
"==",
":link",
"case",
"value",
"when",
"::",
"Hash",
"value",
".",
"to_xml",
"(",
"options",
".",
"merge",
"(",
"{",
":root",
"=>",
"key",
",",
":skip_instruct",
"=>",
"true",
"}",
")",
")",
"when",
"::",
"Array",
"value",
".",
"to_xml",
"(",
"options",
".",
"merge",
"(",
"{",
":root",
"=>",
"key",
",",
":children",
"=>",
"key",
".",
"to_s",
".",
"singularize",
",",
":skip_instruct",
"=>",
"true",
"}",
")",
")",
"else",
"xml",
".",
"tag!",
"(",
"key",
",",
"value",
")",
"end",
"end",
"end",
"end"
] | Utilizes ActiveSupport to turn our objects into XML
that we can pass back to the server.
General concept stolen from Rails CoreExtensions::Hash::Conversions | [
"Utilizes",
"ActiveSupport",
"to",
"turn",
"our",
"objects",
"into",
"XML",
"that",
"we",
"can",
"pass",
"back",
"to",
"the",
"server",
"."
] | 320e311ea1549cdd0dada0f8a0a4f9942213b28f | https://github.com/subimage/cashboard-rb/blob/320e311ea1549cdd0dada0f8a0a4f9942213b28f/lib/cashboard/base.rb#L125-L159 | train |
tclaus/keytechkit.gem | lib/keytechKit/elements/element_handler.rb | KeytechKit.ElementHandler.delete | def delete(element_key)
parameter = { basic_auth: @auth }
response = self.class.delete("/elements/#{element_key}", parameter)
unless response.success?
puts "Could not save element: #{response.headers['x-errordescription']}"
end
response
end | ruby | def delete(element_key)
parameter = { basic_auth: @auth }
response = self.class.delete("/elements/#{element_key}", parameter)
unless response.success?
puts "Could not save element: #{response.headers['x-errordescription']}"
end
response
end | [
"def",
"delete",
"(",
"element_key",
")",
"parameter",
"=",
"{",
"basic_auth",
":",
"@auth",
"}",
"response",
"=",
"self",
".",
"class",
".",
"delete",
"(",
"\"/elements/#{element_key}\"",
",",
"parameter",
")",
"unless",
"response",
".",
"success?",
"puts",
"\"Could not save element: #{response.headers['x-errordescription']}\"",
"end",
"response",
"end"
] | Deletes an element with the key
It returns the http response. | [
"Deletes",
"an",
"element",
"with",
"the",
"key",
"It",
"returns",
"the",
"http",
"response",
"."
] | caa7a6bee32b75ec18a4004179ae10cb69d148c2 | https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_handler.rb#L76-L83 | train |
tclaus/keytechkit.gem | lib/keytechKit/elements/element_handler.rb | KeytechKit.ElementHandler.notes | def notes(element_key)
parameter = { basic_auth: @auth }
response = self.class.get("/elements/#{element_key}/notes", parameter)
if response.success?
search_response_header = SearchResponseHeader.new(response)
search_response_header.elementList
end
end | ruby | def notes(element_key)
parameter = { basic_auth: @auth }
response = self.class.get("/elements/#{element_key}/notes", parameter)
if response.success?
search_response_header = SearchResponseHeader.new(response)
search_response_header.elementList
end
end | [
"def",
"notes",
"(",
"element_key",
")",
"parameter",
"=",
"{",
"basic_auth",
":",
"@auth",
"}",
"response",
"=",
"self",
".",
"class",
".",
"get",
"(",
"\"/elements/#{element_key}/notes\"",
",",
"parameter",
")",
"if",
"response",
".",
"success?",
"search_response_header",
"=",
"SearchResponseHeader",
".",
"new",
"(",
"response",
")",
"search_response_header",
".",
"elementList",
"end",
"end"
] | It returns the notes of an element if anything are given
Notes list can be empty
It returns nil if no element with this elementKey was found | [
"It",
"returns",
"the",
"notes",
"of",
"an",
"element",
"if",
"anything",
"are",
"given",
"Notes",
"list",
"can",
"be",
"empty",
"It",
"returns",
"nil",
"if",
"no",
"element",
"with",
"this",
"elementKey",
"was",
"found"
] | caa7a6bee32b75ec18a4004179ae10cb69d148c2 | https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_handler.rb#L144-L152 | train |
tclaus/keytechkit.gem | lib/keytechKit/elements/element_handler.rb | KeytechKit.ElementHandler.note_handler | def note_handler
@_note_handler = NoteHandler.new(keytechkit.base_url, keytechkit.username, keytechkit.password) if @_note_handler.nil?
@_note_handler
end | ruby | def note_handler
@_note_handler = NoteHandler.new(keytechkit.base_url, keytechkit.username, keytechkit.password) if @_note_handler.nil?
@_note_handler
end | [
"def",
"note_handler",
"@_note_handler",
"=",
"NoteHandler",
".",
"new",
"(",
"keytechkit",
".",
"base_url",
",",
"keytechkit",
".",
"username",
",",
"keytechkit",
".",
"password",
")",
"if",
"@_note_handler",
".",
"nil?",
"@_note_handler",
"end"
] | Returns Notes resource.
Every Element can have zero, one or more notes.
You can notes only access in context of its element which ownes the notes | [
"Returns",
"Notes",
"resource",
".",
"Every",
"Element",
"can",
"have",
"zero",
"one",
"or",
"more",
"notes",
".",
"You",
"can",
"notes",
"only",
"access",
"in",
"context",
"of",
"its",
"element",
"which",
"ownes",
"the",
"notes"
] | caa7a6bee32b75ec18a4004179ae10cb69d148c2 | https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_handler.rb#L157-L160 | train |
tclaus/keytechkit.gem | lib/keytechKit/elements/element_handler.rb | KeytechKit.ElementHandler.file_handler | def file_handler
@_element_file_handler = ElementFileHandler.new(keytechkit.base_url, keytechkit.username, keytechkit.password) if @_element_file_handler.nil?
@_element_file_handler
end | ruby | def file_handler
@_element_file_handler = ElementFileHandler.new(keytechkit.base_url, keytechkit.username, keytechkit.password) if @_element_file_handler.nil?
@_element_file_handler
end | [
"def",
"file_handler",
"@_element_file_handler",
"=",
"ElementFileHandler",
".",
"new",
"(",
"keytechkit",
".",
"base_url",
",",
"keytechkit",
".",
"username",
",",
"keytechkit",
".",
"password",
")",
"if",
"@_element_file_handler",
".",
"nil?",
"@_element_file_handler",
"end"
] | Returns the file object.
Every element can have a Masterfile and one or more preview files | [
"Returns",
"the",
"file",
"object",
".",
"Every",
"element",
"can",
"have",
"a",
"Masterfile",
"and",
"one",
"or",
"more",
"preview",
"files"
] | caa7a6bee32b75ec18a4004179ae10cb69d148c2 | https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_handler.rb#L164-L167 | train |
treeder/quicky | lib/quicky/results_hash.rb | Quicky.ResultsHash.to_hash | def to_hash
ret = {}
self.each_pair do |k, v|
ret[k] = v.to_hash()
end
ret
end | ruby | def to_hash
ret = {}
self.each_pair do |k, v|
ret[k] = v.to_hash()
end
ret
end | [
"def",
"to_hash",
"ret",
"=",
"{",
"}",
"self",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"ret",
"[",
"k",
"]",
"=",
"v",
".",
"to_hash",
"(",
")",
"end",
"ret",
"end"
] | returns results in a straight up hash. | [
"returns",
"results",
"in",
"a",
"straight",
"up",
"hash",
"."
] | 4ac89408c28ca04745280a4cef2db4f97ed5b6d2 | https://github.com/treeder/quicky/blob/4ac89408c28ca04745280a4cef2db4f97ed5b6d2/lib/quicky/results_hash.rb#L6-L12 | train |
treeder/quicky | lib/quicky/results_hash.rb | Quicky.ResultsHash.merge! | def merge!(rh)
rh.each_pair do |k, v|
# v is a TimeCollector
if self.has_key?(k)
self[k].merge!(v)
else
self[k] = v
end
end
end | ruby | def merge!(rh)
rh.each_pair do |k, v|
# v is a TimeCollector
if self.has_key?(k)
self[k].merge!(v)
else
self[k] = v
end
end
end | [
"def",
"merge!",
"(",
"rh",
")",
"rh",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"self",
".",
"has_key?",
"(",
"k",
")",
"self",
"[",
"k",
"]",
".",
"merge!",
"(",
"v",
")",
"else",
"self",
"[",
"k",
"]",
"=",
"v",
"end",
"end",
"end"
] | merges multiple ResultsHash's | [
"merges",
"multiple",
"ResultsHash",
"s"
] | 4ac89408c28ca04745280a4cef2db4f97ed5b6d2 | https://github.com/treeder/quicky/blob/4ac89408c28ca04745280a4cef2db4f97ed5b6d2/lib/quicky/results_hash.rb#L24-L33 | train |
wied03/opal-factory_girl | opal/opal/active_support/inflector/methods.rb | ActiveSupport.Inflector.titleize | def titleize(word)
# negative lookbehind doesn't work in Firefox / Safari
# humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { |match| match.capitalize }
humanized = humanize(underscore(word))
humanized.reverse.gsub(/[a-z](?!['’`])\b/) { |match| match.capitalize }.reverse
end | ruby | def titleize(word)
# negative lookbehind doesn't work in Firefox / Safari
# humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { |match| match.capitalize }
humanized = humanize(underscore(word))
humanized.reverse.gsub(/[a-z](?!['’`])\b/) { |match| match.capitalize }.reverse
end | [
"def",
"titleize",
"(",
"word",
")",
"humanized",
"=",
"humanize",
"(",
"underscore",
"(",
"word",
")",
")",
"humanized",
".",
"reverse",
".",
"gsub",
"(",
"/",
"/)",
" ",
"{",
"|",
"a",
"tch| ",
"m",
"tch.c",
"a",
"pitalize }",
"r",
"e",
"verse",
"end"
] | Capitalizes all the words and replaces some characters in the string to
create a nicer looking title. +titleize+ is meant for creating pretty
output. It is not used in the Rails internals.
+titleize+ is also aliased as +titlecase+.
titleize('man from the boondocks') # => "Man From The Boondocks"
titleize('x-men: the last stand') # => "X Men: The Last Stand"
titleize('TheManWithoutAPast') # => "The Man Without A Past"
titleize('raiders_of_the_lost_ark') # => "Raiders Of The Lost Ark" | [
"Capitalizes",
"all",
"the",
"words",
"and",
"replaces",
"some",
"characters",
"in",
"the",
"string",
"to",
"create",
"a",
"nicer",
"looking",
"title",
".",
"+",
"titleize",
"+",
"is",
"meant",
"for",
"creating",
"pretty",
"output",
".",
"It",
"is",
"not",
"used",
"in",
"the",
"Rails",
"internals",
"."
] | 697114a8c63f4cba38b84d27d1f7b823c8d0bb38 | https://github.com/wied03/opal-factory_girl/blob/697114a8c63f4cba38b84d27d1f7b823c8d0bb38/opal/opal/active_support/inflector/methods.rb#L160-L165 | train |
hck/filter_factory | lib/filter_factory/filter.rb | FilterFactory.Filter.attributes | def attributes
fields.each_with_object(HashWithIndifferentAccess.new) do |field, acc|
acc[field.alias] = field.value
end
end | ruby | def attributes
fields.each_with_object(HashWithIndifferentAccess.new) do |field, acc|
acc[field.alias] = field.value
end
end | [
"def",
"attributes",
"fields",
".",
"each_with_object",
"(",
"HashWithIndifferentAccess",
".",
"new",
")",
"do",
"|",
"field",
",",
"acc",
"|",
"acc",
"[",
"field",
".",
"alias",
"]",
"=",
"field",
".",
"value",
"end",
"end"
] | Initializes new instance of Filter class.
Returns list of filter attributes.
@return [HashWithIndifferentAccess] | [
"Initializes",
"new",
"instance",
"of",
"Filter",
"class",
".",
"Returns",
"list",
"of",
"filter",
"attributes",
"."
] | 21f331ed3b1a9eae1a56727617e26407c96daebc | https://github.com/hck/filter_factory/blob/21f331ed3b1a9eae1a56727617e26407c96daebc/lib/filter_factory/filter.rb#L25-L29 | train |
mrsimonfletcher/roroacms | app/helpers/roroacms/routing_helper.rb | Roroacms.RoutingHelper.get_type_by_url | def get_type_by_url
return 'P' if params[:slug].blank?
# split the url up into segments
segments = params[:slug].split('/')
# general variables
url = params[:slug]
article_url = Setting.get('articles_slug')
category_url = Setting.get('category_slug')
tag_url = Setting.get('tag_slug')
status = "(post_status = 'Published' AND post_date <= CURRENT_TIMESTAMP AND disabled = 'N')"
# HACK: this needs to be optimised
# is it a article post or a page post
if segments[0] == article_url
if !segments[1].blank?
if segments[1] == category_url || segments[1] == tag_url
# render a category or tag page
return 'CT'
elsif segments[1].match(/\A\+?\d+(?:\.\d+)?\Z/)
# render the archive page
return 'AR'
else
# otherwise render a single article page
return 'A'
end
else
# render the overall all the articles
return 'C'
end
else
# render a page
return 'P'
end
end | ruby | def get_type_by_url
return 'P' if params[:slug].blank?
# split the url up into segments
segments = params[:slug].split('/')
# general variables
url = params[:slug]
article_url = Setting.get('articles_slug')
category_url = Setting.get('category_slug')
tag_url = Setting.get('tag_slug')
status = "(post_status = 'Published' AND post_date <= CURRENT_TIMESTAMP AND disabled = 'N')"
# HACK: this needs to be optimised
# is it a article post or a page post
if segments[0] == article_url
if !segments[1].blank?
if segments[1] == category_url || segments[1] == tag_url
# render a category or tag page
return 'CT'
elsif segments[1].match(/\A\+?\d+(?:\.\d+)?\Z/)
# render the archive page
return 'AR'
else
# otherwise render a single article page
return 'A'
end
else
# render the overall all the articles
return 'C'
end
else
# render a page
return 'P'
end
end | [
"def",
"get_type_by_url",
"return",
"'P'",
"if",
"params",
"[",
":slug",
"]",
".",
"blank?",
"segments",
"=",
"params",
"[",
":slug",
"]",
".",
"split",
"(",
"'/'",
")",
"url",
"=",
"params",
"[",
":slug",
"]",
"article_url",
"=",
"Setting",
".",
"get",
"(",
"'articles_slug'",
")",
"category_url",
"=",
"Setting",
".",
"get",
"(",
"'category_slug'",
")",
"tag_url",
"=",
"Setting",
".",
"get",
"(",
"'tag_slug'",
")",
"status",
"=",
"\"(post_status = 'Published' AND post_date <= CURRENT_TIMESTAMP AND disabled = 'N')\"",
"if",
"segments",
"[",
"0",
"]",
"==",
"article_url",
"if",
"!",
"segments",
"[",
"1",
"]",
".",
"blank?",
"if",
"segments",
"[",
"1",
"]",
"==",
"category_url",
"||",
"segments",
"[",
"1",
"]",
"==",
"tag_url",
"return",
"'CT'",
"elsif",
"segments",
"[",
"1",
"]",
".",
"match",
"(",
"/",
"\\A",
"\\+",
"\\d",
"\\.",
"\\d",
"\\Z",
"/",
")",
"return",
"'AR'",
"else",
"return",
"'A'",
"end",
"else",
"return",
"'C'",
"end",
"else",
"return",
"'P'",
"end",
"end"
] | returns that type of page that you are currenly viewing | [
"returns",
"that",
"type",
"of",
"page",
"that",
"you",
"are",
"currenly",
"viewing"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/routing_helper.rb#L96-L136 | train |
houston/houston-conversations | lib/houston/conversations.rb | Houston.Conversations.hear | def hear(message, params={})
raise ArgumentError, "`message` must respond to :channel" unless message.respond_to?(:channel)
raise ArgumentError, "`message` must respond to :sender" unless message.respond_to?(:sender)
listeners.hear(message).each do |match|
event = Houston::Conversations::Event.new(match)
if block_given?
yield event, match.listener
else
match.listener.call_async event
end
# Invoke only one listener per message
return true
end
false
end | ruby | def hear(message, params={})
raise ArgumentError, "`message` must respond to :channel" unless message.respond_to?(:channel)
raise ArgumentError, "`message` must respond to :sender" unless message.respond_to?(:sender)
listeners.hear(message).each do |match|
event = Houston::Conversations::Event.new(match)
if block_given?
yield event, match.listener
else
match.listener.call_async event
end
# Invoke only one listener per message
return true
end
false
end | [
"def",
"hear",
"(",
"message",
",",
"params",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"\"`message` must respond to :channel\"",
"unless",
"message",
".",
"respond_to?",
"(",
":channel",
")",
"raise",
"ArgumentError",
",",
"\"`message` must respond to :sender\"",
"unless",
"message",
".",
"respond_to?",
"(",
":sender",
")",
"listeners",
".",
"hear",
"(",
"message",
")",
".",
"each",
"do",
"|",
"match",
"|",
"event",
"=",
"Houston",
"::",
"Conversations",
"::",
"Event",
".",
"new",
"(",
"match",
")",
"if",
"block_given?",
"yield",
"event",
",",
"match",
".",
"listener",
"else",
"match",
".",
"listener",
".",
"call_async",
"event",
"end",
"return",
"true",
"end",
"false",
"end"
] | Matches a message against all listeners
and invokes the first listener that mathes | [
"Matches",
"a",
"message",
"against",
"all",
"listeners",
"and",
"invokes",
"the",
"first",
"listener",
"that",
"mathes"
] | b292c90c3a74c73e2a97e23e20fa640dc3e48c54 | https://github.com/houston/houston-conversations/blob/b292c90c3a74c73e2a97e23e20fa640dc3e48c54/lib/houston/conversations.rb#L30-L48 | train |
robertwahler/mutagem | lib/mutagem/mutex.rb | Mutagem.Mutex.execute | def execute(&block)
result = false
raise ArgumentError, "missing block" unless block_given?
begin
open(lockfile, 'w') do |f|
# exclusive non-blocking lock
result = lock(f, File::LOCK_EX | File::LOCK_NB) do |f|
yield
end
end
ensure
# clean up but only if we have a positive result meaning we wrote the lockfile
FileUtils.rm(lockfile) if (result && File.exists?(lockfile))
end
result
end | ruby | def execute(&block)
result = false
raise ArgumentError, "missing block" unless block_given?
begin
open(lockfile, 'w') do |f|
# exclusive non-blocking lock
result = lock(f, File::LOCK_EX | File::LOCK_NB) do |f|
yield
end
end
ensure
# clean up but only if we have a positive result meaning we wrote the lockfile
FileUtils.rm(lockfile) if (result && File.exists?(lockfile))
end
result
end | [
"def",
"execute",
"(",
"&",
"block",
")",
"result",
"=",
"false",
"raise",
"ArgumentError",
",",
"\"missing block\"",
"unless",
"block_given?",
"begin",
"open",
"(",
"lockfile",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"result",
"=",
"lock",
"(",
"f",
",",
"File",
"::",
"LOCK_EX",
"|",
"File",
"::",
"LOCK_NB",
")",
"do",
"|",
"f",
"|",
"yield",
"end",
"end",
"ensure",
"FileUtils",
".",
"rm",
"(",
"lockfile",
")",
"if",
"(",
"result",
"&&",
"File",
".",
"exists?",
"(",
"lockfile",
")",
")",
"end",
"result",
"end"
] | Creates a new Mutex
@param [String] lockfile filename
Protect a block
@example
require 'rubygems'
require 'mutagem'
mutex = Mutagem::Mutex.new("my_process_name.lck")
mutex.execute do
puts "this block is protected from recursion"
end
@param block the block of code to protect with the mutex
@return [Boolean] 0 if lock sucessful, otherwise false | [
"Creates",
"a",
"new",
"Mutex"
] | 75ac2f7fd307f575d81114b32e1a3b09c526e01d | https://github.com/robertwahler/mutagem/blob/75ac2f7fd307f575d81114b32e1a3b09c526e01d/lib/mutagem/mutex.rb#L29-L46 | train |
webmonarch/movingsign_api | lib/movingsign_api/commands/command.rb | MovingsignApi.Command.to_bytes | def to_bytes
# set defaults
self.sender ||= :pc
self.receiver ||= 1
bytes = []
bytes.concat [0x00] * 5 # start of command
bytes.concat [0x01] # <SOH>
bytes.concat self.sender.to_bytes # Sender Address
bytes.concat self.receiver.to_bytes # Reciver Address
bytes.concat [0x02] # <STX>
bytes.concat string_to_ascii_bytes(command_code) # Command Code
bytes.concat command_payload_bytes # command specific payload
bytes.concat [0x03] # <ETX>
bytes.concat generate_checksum_bytes(bytes[10..-1]) # Checksum bytes (4)
bytes.concat [0x04] # <EOT>
bytes
end | ruby | def to_bytes
# set defaults
self.sender ||= :pc
self.receiver ||= 1
bytes = []
bytes.concat [0x00] * 5 # start of command
bytes.concat [0x01] # <SOH>
bytes.concat self.sender.to_bytes # Sender Address
bytes.concat self.receiver.to_bytes # Reciver Address
bytes.concat [0x02] # <STX>
bytes.concat string_to_ascii_bytes(command_code) # Command Code
bytes.concat command_payload_bytes # command specific payload
bytes.concat [0x03] # <ETX>
bytes.concat generate_checksum_bytes(bytes[10..-1]) # Checksum bytes (4)
bytes.concat [0x04] # <EOT>
bytes
end | [
"def",
"to_bytes",
"self",
".",
"sender",
"||=",
":pc",
"self",
".",
"receiver",
"||=",
"1",
"bytes",
"=",
"[",
"]",
"bytes",
".",
"concat",
"[",
"0x00",
"]",
"*",
"5",
"bytes",
".",
"concat",
"[",
"0x01",
"]",
"bytes",
".",
"concat",
"self",
".",
"sender",
".",
"to_bytes",
"bytes",
".",
"concat",
"self",
".",
"receiver",
".",
"to_bytes",
"bytes",
".",
"concat",
"[",
"0x02",
"]",
"bytes",
".",
"concat",
"string_to_ascii_bytes",
"(",
"command_code",
")",
"bytes",
".",
"concat",
"command_payload_bytes",
"bytes",
".",
"concat",
"[",
"0x03",
"]",
"bytes",
".",
"concat",
"generate_checksum_bytes",
"(",
"bytes",
"[",
"10",
"..",
"-",
"1",
"]",
")",
"bytes",
".",
"concat",
"[",
"0x04",
"]",
"bytes",
"end"
] | Returns a byte array representing this command, appropriate for sending to the sign's serial port
@return [Array<Byte>] | [
"Returns",
"a",
"byte",
"array",
"representing",
"this",
"command",
"appropriate",
"for",
"sending",
"to",
"the",
"sign",
"s",
"serial",
"port"
] | 11c820edcb5f3a367b341257dae4f6249ae6d0a3 | https://github.com/webmonarch/movingsign_api/blob/11c820edcb5f3a367b341257dae4f6249ae6d0a3/lib/movingsign_api/commands/command.rb#L36-L55 | train |
trejkaz/futurocube | lib/futurocube/resource_file.rb | FuturoCube.ResourceFile.records | def records
if !@records
@io.seek(44, IO::SEEK_SET)
records = []
header.record_count.times do
records << ResourceRecord.read(@io)
end
@records = records
end
@records
end | ruby | def records
if !@records
@io.seek(44, IO::SEEK_SET)
records = []
header.record_count.times do
records << ResourceRecord.read(@io)
end
@records = records
end
@records
end | [
"def",
"records",
"if",
"!",
"@records",
"@io",
".",
"seek",
"(",
"44",
",",
"IO",
"::",
"SEEK_SET",
")",
"records",
"=",
"[",
"]",
"header",
".",
"record_count",
".",
"times",
"do",
"records",
"<<",
"ResourceRecord",
".",
"read",
"(",
"@io",
")",
"end",
"@records",
"=",
"records",
"end",
"@records",
"end"
] | Reads the list of records from the resource file. | [
"Reads",
"the",
"list",
"of",
"records",
"from",
"the",
"resource",
"file",
"."
] | 2000e3d9e301f27fd01a0f331045fae9d6cc1883 | https://github.com/trejkaz/futurocube/blob/2000e3d9e301f27fd01a0f331045fae9d6cc1883/lib/futurocube/resource_file.rb#L42-L52 | train |
trejkaz/futurocube | lib/futurocube/resource_file.rb | FuturoCube.ResourceFile.data | def data(rec)
@io.seek(rec.data_offset, IO::SEEK_SET)
@io.read(rec.data_length)
end | ruby | def data(rec)
@io.seek(rec.data_offset, IO::SEEK_SET)
@io.read(rec.data_length)
end | [
"def",
"data",
"(",
"rec",
")",
"@io",
".",
"seek",
"(",
"rec",
".",
"data_offset",
",",
"IO",
"::",
"SEEK_SET",
")",
"@io",
".",
"read",
"(",
"rec",
".",
"data_length",
")",
"end"
] | Reads the data for a given record.
@param rec [ResourceRecord] the record to read the data for. | [
"Reads",
"the",
"data",
"for",
"a",
"given",
"record",
"."
] | 2000e3d9e301f27fd01a0f331045fae9d6cc1883 | https://github.com/trejkaz/futurocube/blob/2000e3d9e301f27fd01a0f331045fae9d6cc1883/lib/futurocube/resource_file.rb#L57-L60 | train |
trejkaz/futurocube | lib/futurocube/resource_file.rb | FuturoCube.ResourceFile.compute_checksum | def compute_checksum(&block)
crc = CRC.new
# Have to read this first because it might change the seek position.
file_size = header.file_size
@io.seek(8, IO::SEEK_SET)
pos = 8
length = 4096-8
buf = nil
while true
buf = @io.read(length, buf)
break if !buf
crc.update(buf)
pos += buf.size
block.call(pos) if block
length = 4096
end
crc.crc
end | ruby | def compute_checksum(&block)
crc = CRC.new
# Have to read this first because it might change the seek position.
file_size = header.file_size
@io.seek(8, IO::SEEK_SET)
pos = 8
length = 4096-8
buf = nil
while true
buf = @io.read(length, buf)
break if !buf
crc.update(buf)
pos += buf.size
block.call(pos) if block
length = 4096
end
crc.crc
end | [
"def",
"compute_checksum",
"(",
"&",
"block",
")",
"crc",
"=",
"CRC",
".",
"new",
"file_size",
"=",
"header",
".",
"file_size",
"@io",
".",
"seek",
"(",
"8",
",",
"IO",
"::",
"SEEK_SET",
")",
"pos",
"=",
"8",
"length",
"=",
"4096",
"-",
"8",
"buf",
"=",
"nil",
"while",
"true",
"buf",
"=",
"@io",
".",
"read",
"(",
"length",
",",
"buf",
")",
"break",
"if",
"!",
"buf",
"crc",
".",
"update",
"(",
"buf",
")",
"pos",
"+=",
"buf",
".",
"size",
"block",
".",
"call",
"(",
"pos",
")",
"if",
"block",
"length",
"=",
"4096",
"end",
"crc",
".",
"crc",
"end"
] | Computes the checksum for the resource file.
@yield [done] Provides feedback about the progress of the operation. | [
"Computes",
"the",
"checksum",
"for",
"the",
"resource",
"file",
"."
] | 2000e3d9e301f27fd01a0f331045fae9d6cc1883 | https://github.com/trejkaz/futurocube/blob/2000e3d9e301f27fd01a0f331045fae9d6cc1883/lib/futurocube/resource_file.rb#L65-L82 | train |
Dahie/woro | lib/woro/task.rb | Woro.Task.build_task_template | def build_task_template
b = binding
ERB.new(Woro::TaskHelper.read_template_file).result(b)
end | ruby | def build_task_template
b = binding
ERB.new(Woro::TaskHelper.read_template_file).result(b)
end | [
"def",
"build_task_template",
"b",
"=",
"binding",
"ERB",
".",
"new",
"(",
"Woro",
"::",
"TaskHelper",
".",
"read_template_file",
")",
".",
"result",
"(",
"b",
")",
"end"
] | Read template and inject new name
@return [String] source code for new task | [
"Read",
"template",
"and",
"inject",
"new",
"name"
] | 796873cca145c61cd72c7363551e10d402f867c6 | https://github.com/Dahie/woro/blob/796873cca145c61cd72c7363551e10d402f867c6/lib/woro/task.rb#L48-L51 | train |
barkerest/barkest_core | app/controllers/barkest_core/application_controller_base.rb | BarkestCore.ApplicationControllerBase.authorize! | def authorize!(*group_list)
begin
# an authenticated user must exist.
unless logged_in?
store_location
raise_not_logged_in "You need to login to access '#{request.fullpath}'.",
'nobody is logged in'
end
# clean up the group list.
group_list ||= []
group_list.delete false
group_list.delete ''
if group_list.include?(true)
# group_list contains "true" so only a system admin may continue.
unless system_admin?
if show_denial_reason?
flash[:info] = 'The requested path is only available to system administrators.'
end
raise_authorize_failure "Your are not authorized to access '#{request.fullpath}'.",
'requires system administrator'
end
log_authorize_success 'user is system admin'
elsif group_list.blank?
# group_list is empty or contained nothing but empty strings and boolean false.
# everyone can continue.
log_authorize_success 'only requires authenticated user'
else
# the group list contains one or more authorized groups.
# we want them to all be uppercase strings.
group_list = group_list.map{|v| v.to_s.upcase}.sort
result = current_user.has_any_group?(*group_list)
unless result
message = group_list.join(', ')
if show_denial_reason?
flash[:info] = "The requested path requires one of these groups: #{message}"
end
raise_authorize_failure "You are not authorized to access '#{request.fullpath}'.",
"requires one of: #{message}"
end
log_authorize_success "user has '#{result}' group"
end
rescue BarkestCore::AuthorizeFailure => err
flash[:danger] = err.message
redirect_to root_url and return false
end
true
end | ruby | def authorize!(*group_list)
begin
# an authenticated user must exist.
unless logged_in?
store_location
raise_not_logged_in "You need to login to access '#{request.fullpath}'.",
'nobody is logged in'
end
# clean up the group list.
group_list ||= []
group_list.delete false
group_list.delete ''
if group_list.include?(true)
# group_list contains "true" so only a system admin may continue.
unless system_admin?
if show_denial_reason?
flash[:info] = 'The requested path is only available to system administrators.'
end
raise_authorize_failure "Your are not authorized to access '#{request.fullpath}'.",
'requires system administrator'
end
log_authorize_success 'user is system admin'
elsif group_list.blank?
# group_list is empty or contained nothing but empty strings and boolean false.
# everyone can continue.
log_authorize_success 'only requires authenticated user'
else
# the group list contains one or more authorized groups.
# we want them to all be uppercase strings.
group_list = group_list.map{|v| v.to_s.upcase}.sort
result = current_user.has_any_group?(*group_list)
unless result
message = group_list.join(', ')
if show_denial_reason?
flash[:info] = "The requested path requires one of these groups: #{message}"
end
raise_authorize_failure "You are not authorized to access '#{request.fullpath}'.",
"requires one of: #{message}"
end
log_authorize_success "user has '#{result}' group"
end
rescue BarkestCore::AuthorizeFailure => err
flash[:danger] = err.message
redirect_to root_url and return false
end
true
end | [
"def",
"authorize!",
"(",
"*",
"group_list",
")",
"begin",
"unless",
"logged_in?",
"store_location",
"raise_not_logged_in",
"\"You need to login to access '#{request.fullpath}'.\"",
",",
"'nobody is logged in'",
"end",
"group_list",
"||=",
"[",
"]",
"group_list",
".",
"delete",
"false",
"group_list",
".",
"delete",
"''",
"if",
"group_list",
".",
"include?",
"(",
"true",
")",
"unless",
"system_admin?",
"if",
"show_denial_reason?",
"flash",
"[",
":info",
"]",
"=",
"'The requested path is only available to system administrators.'",
"end",
"raise_authorize_failure",
"\"Your are not authorized to access '#{request.fullpath}'.\"",
",",
"'requires system administrator'",
"end",
"log_authorize_success",
"'user is system admin'",
"elsif",
"group_list",
".",
"blank?",
"log_authorize_success",
"'only requires authenticated user'",
"else",
"group_list",
"=",
"group_list",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"to_s",
".",
"upcase",
"}",
".",
"sort",
"result",
"=",
"current_user",
".",
"has_any_group?",
"(",
"*",
"group_list",
")",
"unless",
"result",
"message",
"=",
"group_list",
".",
"join",
"(",
"', '",
")",
"if",
"show_denial_reason?",
"flash",
"[",
":info",
"]",
"=",
"\"The requested path requires one of these groups: #{message}\"",
"end",
"raise_authorize_failure",
"\"You are not authorized to access '#{request.fullpath}'.\"",
",",
"\"requires one of: #{message}\"",
"end",
"log_authorize_success",
"\"user has '#{result}' group\"",
"end",
"rescue",
"BarkestCore",
"::",
"AuthorizeFailure",
"=>",
"err",
"flash",
"[",
":danger",
"]",
"=",
"err",
".",
"message",
"redirect_to",
"root_url",
"and",
"return",
"false",
"end",
"true",
"end"
] | Authorize the current action.
* If +group_list+ is not provided or only contains +false+ then any authenticated user will be authorized.
* If +group_list+ contains +true+ then only system administrators will be authorized.
* Otherwise the +group_list+ contains a list of accepted groups that will be authorized.
Any user with one or more groups from the list will be granted access. | [
"Authorize",
"the",
"current",
"action",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/controllers/barkest_core/application_controller_base.rb#L30-L83 | train |
flyingmachine/higml | lib/higml/applier.rb | Higml.Applier.selector_matches? | def selector_matches?(selector)
selector.any? do |group|
group.keys.all? do |key|
input_has_key?(key) && (@input[key] == group[key] || group[key].nil?)
end
end
end | ruby | def selector_matches?(selector)
selector.any? do |group|
group.keys.all? do |key|
input_has_key?(key) && (@input[key] == group[key] || group[key].nil?)
end
end
end | [
"def",
"selector_matches?",
"(",
"selector",
")",
"selector",
".",
"any?",
"do",
"|",
"group",
"|",
"group",
".",
"keys",
".",
"all?",
"do",
"|",
"key",
"|",
"input_has_key?",
"(",
"key",
")",
"&&",
"(",
"@input",
"[",
"key",
"]",
"==",
"group",
"[",
"key",
"]",
"||",
"group",
"[",
"key",
"]",
".",
"nil?",
")",
"end",
"end",
"end"
] | REFACTOR to selector class | [
"REFACTOR",
"to",
"selector",
"class"
] | 0c83d236c8911fb8ce23fcd82b5691f9189f41ef | https://github.com/flyingmachine/higml/blob/0c83d236c8911fb8ce23fcd82b5691f9189f41ef/lib/higml/applier.rb#L43-L49 | train |
danlewis/encryptbot | lib/encryptbot/cert.rb | Encryptbot.Cert.ready_for_challenge | def ready_for_challenge(domain, dns_challenge)
record = "#{dns_challenge.record_name}.#{domain}"
challenge_value = dns_challenge.record_content
txt_value = Resolv::DNS.open do |dns|
records = dns.getresources(record, Resolv::DNS::Resource::IN::TXT);
records.empty? ? nil : records.map(&:data).join(" ")
end
txt_value == challenge_value
end | ruby | def ready_for_challenge(domain, dns_challenge)
record = "#{dns_challenge.record_name}.#{domain}"
challenge_value = dns_challenge.record_content
txt_value = Resolv::DNS.open do |dns|
records = dns.getresources(record, Resolv::DNS::Resource::IN::TXT);
records.empty? ? nil : records.map(&:data).join(" ")
end
txt_value == challenge_value
end | [
"def",
"ready_for_challenge",
"(",
"domain",
",",
"dns_challenge",
")",
"record",
"=",
"\"#{dns_challenge.record_name}.#{domain}\"",
"challenge_value",
"=",
"dns_challenge",
".",
"record_content",
"txt_value",
"=",
"Resolv",
"::",
"DNS",
".",
"open",
"do",
"|",
"dns",
"|",
"records",
"=",
"dns",
".",
"getresources",
"(",
"record",
",",
"Resolv",
"::",
"DNS",
"::",
"Resource",
"::",
"IN",
"::",
"TXT",
")",
";",
"records",
".",
"empty?",
"?",
"nil",
":",
"records",
".",
"map",
"(",
"&",
":data",
")",
".",
"join",
"(",
"\" \"",
")",
"end",
"txt_value",
"==",
"challenge_value",
"end"
] | Check if TXT value has been set correctly | [
"Check",
"if",
"TXT",
"value",
"has",
"been",
"set",
"correctly"
] | 2badb7cfe3f7c3b416d7aa74bd3e339cc859edb2 | https://github.com/danlewis/encryptbot/blob/2badb7cfe3f7c3b416d7aa74bd3e339cc859edb2/lib/encryptbot/cert.rb#L95-L103 | train |
kenjij/kajiki | lib/kajiki/handler.rb | Kajiki.Handler.check_existing_pid | def check_existing_pid
return false unless pid_file_exists?
pid = read_pid
fail 'Existing process found.' if pid > 0 && pid_exists?(pid)
delete_pid
end | ruby | def check_existing_pid
return false unless pid_file_exists?
pid = read_pid
fail 'Existing process found.' if pid > 0 && pid_exists?(pid)
delete_pid
end | [
"def",
"check_existing_pid",
"return",
"false",
"unless",
"pid_file_exists?",
"pid",
"=",
"read_pid",
"fail",
"'Existing process found.'",
"if",
"pid",
">",
"0",
"&&",
"pid_exists?",
"(",
"pid",
")",
"delete_pid",
"end"
] | Check if process exists then fail, otherwise clean up.
@return [Boolean] `false` if no PID file exists, `true` if it cleaned up. | [
"Check",
"if",
"process",
"exists",
"then",
"fail",
"otherwise",
"clean",
"up",
"."
] | 9b036f2741d515e9bfd158571a813987516d89ed | https://github.com/kenjij/kajiki/blob/9b036f2741d515e9bfd158571a813987516d89ed/lib/kajiki/handler.rb#L7-L12 | train |
kenjij/kajiki | lib/kajiki/handler.rb | Kajiki.Handler.trap_default_signals | def trap_default_signals
Signal.trap('INT') do
puts 'Interrupted. Terminating process...'
exit
end
Signal.trap('HUP') do
puts 'SIGHUP - Terminating process...'
exit
end
Signal.trap('TERM') do
puts 'SIGTERM - Terminating process...'
exit
end
end | ruby | def trap_default_signals
Signal.trap('INT') do
puts 'Interrupted. Terminating process...'
exit
end
Signal.trap('HUP') do
puts 'SIGHUP - Terminating process...'
exit
end
Signal.trap('TERM') do
puts 'SIGTERM - Terminating process...'
exit
end
end | [
"def",
"trap_default_signals",
"Signal",
".",
"trap",
"(",
"'INT'",
")",
"do",
"puts",
"'Interrupted. Terminating process...'",
"exit",
"end",
"Signal",
".",
"trap",
"(",
"'HUP'",
")",
"do",
"puts",
"'SIGHUP - Terminating process...'",
"exit",
"end",
"Signal",
".",
"trap",
"(",
"'TERM'",
")",
"do",
"puts",
"'SIGTERM - Terminating process...'",
"exit",
"end",
"end"
] | Trap common signals as default. | [
"Trap",
"common",
"signals",
"as",
"default",
"."
] | 9b036f2741d515e9bfd158571a813987516d89ed | https://github.com/kenjij/kajiki/blob/9b036f2741d515e9bfd158571a813987516d89ed/lib/kajiki/handler.rb#L71-L84 | train |
cbetta/snapshotify | lib/snapshotify/document.rb | Snapshotify.Document.links | def links
# Find all anchor elements
doc.xpath('//a').map do |element|
# extract all the href attributes
element.attribute('href')
end.compact.map(&:value).map do |href|
# return them as new document objects
Snapshotify::Document.new(href, url)
end.compact
end | ruby | def links
# Find all anchor elements
doc.xpath('//a').map do |element|
# extract all the href attributes
element.attribute('href')
end.compact.map(&:value).map do |href|
# return them as new document objects
Snapshotify::Document.new(href, url)
end.compact
end | [
"def",
"links",
"doc",
".",
"xpath",
"(",
"'//a'",
")",
".",
"map",
"do",
"|",
"element",
"|",
"element",
".",
"attribute",
"(",
"'href'",
")",
"end",
".",
"compact",
".",
"map",
"(",
"&",
":value",
")",
".",
"map",
"do",
"|",
"href",
"|",
"Snapshotify",
"::",
"Document",
".",
"new",
"(",
"href",
",",
"url",
")",
"end",
".",
"compact",
"end"
] | Initialize the document with a URL, and
the parent page this URL was included on in case of
assets
Find the links in a page and extract all the hrefs | [
"Initialize",
"the",
"document",
"with",
"a",
"URL",
"and",
"the",
"parent",
"page",
"this",
"URL",
"was",
"included",
"on",
"in",
"case",
"of",
"assets",
"Find",
"the",
"links",
"in",
"a",
"page",
"and",
"extract",
"all",
"the",
"hrefs"
] | 7f5553f4281ffc5bf0e54da1141574bd15af45b6 | https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/document.rb#L18-L27 | train |
cbetta/snapshotify | lib/snapshotify/document.rb | Snapshotify.Document.write! | def write!
writer = Snapshotify::Writer.new(self)
writer.emitter = emitter
writer.write
end | ruby | def write!
writer = Snapshotify::Writer.new(self)
writer.emitter = emitter
writer.write
end | [
"def",
"write!",
"writer",
"=",
"Snapshotify",
"::",
"Writer",
".",
"new",
"(",
"self",
")",
"writer",
".",
"emitter",
"=",
"emitter",
"writer",
".",
"write",
"end"
] | Write a document to file | [
"Write",
"a",
"document",
"to",
"file"
] | 7f5553f4281ffc5bf0e54da1141574bd15af45b6 | https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/document.rb#L35-L39 | train |
jgoizueta/sys_cmd | lib/sys_cmd.rb | SysCmd.Definition.option | def option(option, *args)
options = args.pop if args.last.is_a?(Hash)
options ||= {}
raise "Invalid number of arguments (0 or 1 expected)" if args.size > 1
return unless @shell.applicable?(options)
value = args.shift || options[:value]
if options[:os_prefix]
option = @shell.option_switch + option
else
option = option.dup
end
if @shell.requires_escaping?(option)
option = @shell.escape_value(option)
end
option << ' ' << @shell.escape_value(value) if value
option << @shell.escape_value(options[:join_value]) if options[:join_value]
option << '=' << @shell.escape_value(options[:equal_value]) if options[:equal_value]
if file = options[:file]
file_sep = ' '
elsif file = options[:join_file]
file_sep = ''
elsif file = options[:equal_file]
file_sep = '='
end
if file
option << file_sep << @shell.escape_filename(file)
end
@command << ' ' << option
@last_arg = :option
end | ruby | def option(option, *args)
options = args.pop if args.last.is_a?(Hash)
options ||= {}
raise "Invalid number of arguments (0 or 1 expected)" if args.size > 1
return unless @shell.applicable?(options)
value = args.shift || options[:value]
if options[:os_prefix]
option = @shell.option_switch + option
else
option = option.dup
end
if @shell.requires_escaping?(option)
option = @shell.escape_value(option)
end
option << ' ' << @shell.escape_value(value) if value
option << @shell.escape_value(options[:join_value]) if options[:join_value]
option << '=' << @shell.escape_value(options[:equal_value]) if options[:equal_value]
if file = options[:file]
file_sep = ' '
elsif file = options[:join_file]
file_sep = ''
elsif file = options[:equal_file]
file_sep = '='
end
if file
option << file_sep << @shell.escape_filename(file)
end
@command << ' ' << option
@last_arg = :option
end | [
"def",
"option",
"(",
"option",
",",
"*",
"args",
")",
"options",
"=",
"args",
".",
"pop",
"if",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"options",
"||=",
"{",
"}",
"raise",
"\"Invalid number of arguments (0 or 1 expected)\"",
"if",
"args",
".",
"size",
">",
"1",
"return",
"unless",
"@shell",
".",
"applicable?",
"(",
"options",
")",
"value",
"=",
"args",
".",
"shift",
"||",
"options",
"[",
":value",
"]",
"if",
"options",
"[",
":os_prefix",
"]",
"option",
"=",
"@shell",
".",
"option_switch",
"+",
"option",
"else",
"option",
"=",
"option",
".",
"dup",
"end",
"if",
"@shell",
".",
"requires_escaping?",
"(",
"option",
")",
"option",
"=",
"@shell",
".",
"escape_value",
"(",
"option",
")",
"end",
"option",
"<<",
"' '",
"<<",
"@shell",
".",
"escape_value",
"(",
"value",
")",
"if",
"value",
"option",
"<<",
"@shell",
".",
"escape_value",
"(",
"options",
"[",
":join_value",
"]",
")",
"if",
"options",
"[",
":join_value",
"]",
"option",
"<<",
"'='",
"<<",
"@shell",
".",
"escape_value",
"(",
"options",
"[",
":equal_value",
"]",
")",
"if",
"options",
"[",
":equal_value",
"]",
"if",
"file",
"=",
"options",
"[",
":file",
"]",
"file_sep",
"=",
"' '",
"elsif",
"file",
"=",
"options",
"[",
":join_file",
"]",
"file_sep",
"=",
"''",
"elsif",
"file",
"=",
"options",
"[",
":equal_file",
"]",
"file_sep",
"=",
"'='",
"end",
"if",
"file",
"option",
"<<",
"file_sep",
"<<",
"@shell",
".",
"escape_filename",
"(",
"file",
")",
"end",
"@command",
"<<",
"' '",
"<<",
"option",
"@last_arg",
"=",
":option",
"end"
] | Add an option to the command.
option '-x' # flag-style option
option '--y' # long option
option '/z' # Windows-style option
options 'abc' # unprefixed option
If the option +:os_prefix+ is true
then the default system option switch will be used.
option 'x', os_prefix: true # will produce -x or /x
A value can be given as an option and will be space-separated from
the option name:
option '-x', value: 123 # -x 123
To avoid spacing the value use the +:join_value+ option
option '-x', join_value: 123 # -x123
And to use an equal sign as separator, use +:equal_value+
option '-x', equal_value: 123 # -x=123
If the option value is a file name, use the analogous
+:file+, +:join_file+ or +:equal_file+ options:
option '-i', file: 'path/filename'
Several of this options can be given simoultaneusly:
option '-d', join_value: 'x', equal_value: '1' # -dx=1 | [
"Add",
"an",
"option",
"to",
"the",
"command",
"."
] | b7f0cb67502be7755679562f318c3aa66510ec63 | https://github.com/jgoizueta/sys_cmd/blob/b7f0cb67502be7755679562f318c3aa66510ec63/lib/sys_cmd.rb#L70-L99 | train |
jgoizueta/sys_cmd | lib/sys_cmd.rb | SysCmd.Definition.os_option | def os_option(option, *args)
options = args.pop if args.last.is_a?(Hash)
options ||= {}
args.push options.merge(os_prefix: true)
option option, *args
end | ruby | def os_option(option, *args)
options = args.pop if args.last.is_a?(Hash)
options ||= {}
args.push options.merge(os_prefix: true)
option option, *args
end | [
"def",
"os_option",
"(",
"option",
",",
"*",
"args",
")",
"options",
"=",
"args",
".",
"pop",
"if",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"options",
"||=",
"{",
"}",
"args",
".",
"push",
"options",
".",
"merge",
"(",
"os_prefix",
":",
"true",
")",
"option",
"option",
",",
"*",
"args",
"end"
] | An +os_option+ has automatically a OS-dependent prefix | [
"An",
"+",
"os_option",
"+",
"has",
"automatically",
"a",
"OS",
"-",
"dependent",
"prefix"
] | b7f0cb67502be7755679562f318c3aa66510ec63 | https://github.com/jgoizueta/sys_cmd/blob/b7f0cb67502be7755679562f318c3aa66510ec63/lib/sys_cmd.rb#L102-L107 | train |
jgoizueta/sys_cmd | lib/sys_cmd.rb | SysCmd.Definition.argument | def argument(value, options = {})
return unless @shell.applicable?(options)
value = value.to_s
if @shell.requires_escaping?(value)
value = @shell.escape_value(value)
end
@command << ' ' << value
@last_arg = :argument
end | ruby | def argument(value, options = {})
return unless @shell.applicable?(options)
value = value.to_s
if @shell.requires_escaping?(value)
value = @shell.escape_value(value)
end
@command << ' ' << value
@last_arg = :argument
end | [
"def",
"argument",
"(",
"value",
",",
"options",
"=",
"{",
"}",
")",
"return",
"unless",
"@shell",
".",
"applicable?",
"(",
"options",
")",
"value",
"=",
"value",
".",
"to_s",
"if",
"@shell",
".",
"requires_escaping?",
"(",
"value",
")",
"value",
"=",
"@shell",
".",
"escape_value",
"(",
"value",
")",
"end",
"@command",
"<<",
"' '",
"<<",
"value",
"@last_arg",
"=",
":argument",
"end"
] | Add an unquoted argument to the command.
This is not useful for commands executed directly, since the arguments
are note interpreted by a shell in that case. | [
"Add",
"an",
"unquoted",
"argument",
"to",
"the",
"command",
".",
"This",
"is",
"not",
"useful",
"for",
"commands",
"executed",
"directly",
"since",
"the",
"arguments",
"are",
"note",
"interpreted",
"by",
"a",
"shell",
"in",
"that",
"case",
"."
] | b7f0cb67502be7755679562f318c3aa66510ec63 | https://github.com/jgoizueta/sys_cmd/blob/b7f0cb67502be7755679562f318c3aa66510ec63/lib/sys_cmd.rb#L185-L193 | train |
jgoizueta/sys_cmd | lib/sys_cmd.rb | SysCmd.Command.run | def run(options = {})
@output = @status = @error_output = @error = nil
if options[:direct]
command = @shell.split(@command)
else
command = [@command]
end
stdin_data = options[:stdin_data] || @input
if stdin_data
command << { stdin_data: stdin_data }
end
begin
case options[:error_output]
when :mix # mix stderr with stdout
@output, @status = Open3.capture2e(*command)
when :separate
@output, @error_output, @status = Open3.capture3(*command)
else # :console (do not capture stderr output)
@output, @status = Open3.capture2(*command)
end
rescue => error
@error = error.dup
end
case options[:return]
when :status
@status
when :status_value
status_value
when :output
@output
when :error_output
@error_output
when :command
self
else
@error ? nil : @status.success? ? true : false
end
end | ruby | def run(options = {})
@output = @status = @error_output = @error = nil
if options[:direct]
command = @shell.split(@command)
else
command = [@command]
end
stdin_data = options[:stdin_data] || @input
if stdin_data
command << { stdin_data: stdin_data }
end
begin
case options[:error_output]
when :mix # mix stderr with stdout
@output, @status = Open3.capture2e(*command)
when :separate
@output, @error_output, @status = Open3.capture3(*command)
else # :console (do not capture stderr output)
@output, @status = Open3.capture2(*command)
end
rescue => error
@error = error.dup
end
case options[:return]
when :status
@status
when :status_value
status_value
when :output
@output
when :error_output
@error_output
when :command
self
else
@error ? nil : @status.success? ? true : false
end
end | [
"def",
"run",
"(",
"options",
"=",
"{",
"}",
")",
"@output",
"=",
"@status",
"=",
"@error_output",
"=",
"@error",
"=",
"nil",
"if",
"options",
"[",
":direct",
"]",
"command",
"=",
"@shell",
".",
"split",
"(",
"@command",
")",
"else",
"command",
"=",
"[",
"@command",
"]",
"end",
"stdin_data",
"=",
"options",
"[",
":stdin_data",
"]",
"||",
"@input",
"if",
"stdin_data",
"command",
"<<",
"{",
"stdin_data",
":",
"stdin_data",
"}",
"end",
"begin",
"case",
"options",
"[",
":error_output",
"]",
"when",
":mix",
"@output",
",",
"@status",
"=",
"Open3",
".",
"capture2e",
"(",
"*",
"command",
")",
"when",
":separate",
"@output",
",",
"@error_output",
",",
"@status",
"=",
"Open3",
".",
"capture3",
"(",
"*",
"command",
")",
"else",
"@output",
",",
"@status",
"=",
"Open3",
".",
"capture2",
"(",
"*",
"command",
")",
"end",
"rescue",
"=>",
"error",
"@error",
"=",
"error",
".",
"dup",
"end",
"case",
"options",
"[",
":return",
"]",
"when",
":status",
"@status",
"when",
":status_value",
"status_value",
"when",
":output",
"@output",
"when",
":error_output",
"@error_output",
"when",
":command",
"self",
"else",
"@error",
"?",
"nil",
":",
"@status",
".",
"success?",
"?",
"true",
":",
"false",
"end",
"end"
] | Execute the command.
By default the command is executed by a shell. In this case,
unquoted arguments are interpreted by the shell, e.g.
SysCmd.command('echo $BASH').run # /bin/bash
When the +:direct+ option is set to true, no shell is used and
the command is directly executed; in this case unquoted arguments
are not interpreted:
SysCmd.command('echo $BASH').run # $BASH
The exit status of the command is retained in the +status+ attribute
(and its numeric value in the +status_value+ attribute).
The standard output of the command is captured and retained in the
+output+ attribute.
By default, the standar error output of the command is not
captured, so it will be shown on the console unless redirected.
Standard error can be captured and interleaved with the standard
output passing the option
error_output: :mix
Error output can be captured and keep separate inthe +error_output+
attribute with this option:
error_output: :separate
The value returned is by defaut, like in Kernel#system,
true if the command gives zero exit status, false for non zero exit status,
and nil if command execution fails.
The +:return+ option can be used to make this method return other
attribute of the executed command.
The +:stdin_data+ option can be used to pass a String as the
command's standar input. | [
"Execute",
"the",
"command",
"."
] | b7f0cb67502be7755679562f318c3aa66510ec63 | https://github.com/jgoizueta/sys_cmd/blob/b7f0cb67502be7755679562f318c3aa66510ec63/lib/sys_cmd.rb#L267-L304 | train |
gera-gas/iparser | lib/iparser/machine.rb | Iparser.Machine.interactive_parser | def interactive_parser ( )
puts 'Press <Enter> to exit...'
# Цикл обработки ввода.
loop do
str = interactive_input( )
break if str == ""
# Цикл посимвольной классификаци.
str.bytes.each do |c|
parse( c.chr )
puts 'parser: ' + @parserstate
puts 'symbol: ' + interactive_output( c.chr ).to_s
puts 'state: ' + @chain.last.statename
puts
end
end
end | ruby | def interactive_parser ( )
puts 'Press <Enter> to exit...'
# Цикл обработки ввода.
loop do
str = interactive_input( )
break if str == ""
# Цикл посимвольной классификаци.
str.bytes.each do |c|
parse( c.chr )
puts 'parser: ' + @parserstate
puts 'symbol: ' + interactive_output( c.chr ).to_s
puts 'state: ' + @chain.last.statename
puts
end
end
end | [
"def",
"interactive_parser",
"(",
")",
"puts",
"'Press <Enter> to exit...'",
"loop",
"do",
"str",
"=",
"interactive_input",
"(",
")",
"break",
"if",
"str",
"==",
"\"\"",
"str",
".",
"bytes",
".",
"each",
"do",
"|",
"c",
"|",
"parse",
"(",
"c",
".",
"chr",
")",
"puts",
"'parser: '",
"+",
"@parserstate",
"puts",
"'symbol: '",
"+",
"interactive_output",
"(",
"c",
".",
"chr",
")",
".",
"to_s",
"puts",
"'state: '",
"+",
"@chain",
".",
"last",
".",
"statename",
"puts",
"end",
"end",
"end"
] | Run parser machine for check in interactive mode. | [
"Run",
"parser",
"machine",
"for",
"check",
"in",
"interactive",
"mode",
"."
] | bef722594541a406d361c6ff6dac8c15a7aa6d2a | https://github.com/gera-gas/iparser/blob/bef722594541a406d361c6ff6dac8c15a7aa6d2a/lib/iparser/machine.rb#L144-L161 | train |
MBO/attrtastic | lib/attrtastic/semantic_attributes_builder.rb | Attrtastic.SemanticAttributesBuilder.attributes | def attributes(*args, &block)
options = args.extract_options!
options[:html] ||= {}
if args.first and args.first.is_a? String
options[:name] = args.shift
end
if options[:for].blank?
attributes_for(record, args, options, &block)
else
for_value = if options[:for].is_a? Symbol
record.send(options[:for])
else
options[:for]
end
[*for_value].map do |value|
value_options = options.clone
value_options[:html][:class] = [ options[:html][:class], value.class.to_s.underscore ].compact.join(" ")
attributes_for(value, args, options, &block)
end.join.html_safe
end
end | ruby | def attributes(*args, &block)
options = args.extract_options!
options[:html] ||= {}
if args.first and args.first.is_a? String
options[:name] = args.shift
end
if options[:for].blank?
attributes_for(record, args, options, &block)
else
for_value = if options[:for].is_a? Symbol
record.send(options[:for])
else
options[:for]
end
[*for_value].map do |value|
value_options = options.clone
value_options[:html][:class] = [ options[:html][:class], value.class.to_s.underscore ].compact.join(" ")
attributes_for(value, args, options, &block)
end.join.html_safe
end
end | [
"def",
"attributes",
"(",
"*",
"args",
",",
"&",
"block",
")",
"options",
"=",
"args",
".",
"extract_options!",
"options",
"[",
":html",
"]",
"||=",
"{",
"}",
"if",
"args",
".",
"first",
"and",
"args",
".",
"first",
".",
"is_a?",
"String",
"options",
"[",
":name",
"]",
"=",
"args",
".",
"shift",
"end",
"if",
"options",
"[",
":for",
"]",
".",
"blank?",
"attributes_for",
"(",
"record",
",",
"args",
",",
"options",
",",
"&",
"block",
")",
"else",
"for_value",
"=",
"if",
"options",
"[",
":for",
"]",
".",
"is_a?",
"Symbol",
"record",
".",
"send",
"(",
"options",
"[",
":for",
"]",
")",
"else",
"options",
"[",
":for",
"]",
"end",
"[",
"*",
"for_value",
"]",
".",
"map",
"do",
"|",
"value",
"|",
"value_options",
"=",
"options",
".",
"clone",
"value_options",
"[",
":html",
"]",
"[",
":class",
"]",
"=",
"[",
"options",
"[",
":html",
"]",
"[",
":class",
"]",
",",
"value",
".",
"class",
".",
"to_s",
".",
"underscore",
"]",
".",
"compact",
".",
"join",
"(",
"\" \"",
")",
"attributes_for",
"(",
"value",
",",
"args",
",",
"options",
",",
"&",
"block",
")",
"end",
".",
"join",
".",
"html_safe",
"end",
"end"
] | Creates block of attributes with optional header. Attributes are surrounded with ordered list.
@overload attributes(options = {}, &block)
Creates attributes list without header, yields block to include each attribute
@param [Hash] options Options for formating attributes block
@option options [String] :name (nil) Optional header of attributes section
@option options [String] :class ('') Name of html class to add to attributes block
@option options [String] :header_class ('') Name of html class to add to header
@yield Block which can call #attribute to include attribute value
@example
<%= attr.attributes do %>
<%= attr.attribute :name %>
<%= attr.attribute :email %>
<% end %>
@example
<%= attr.attributes :name => "User" do %>
<%= attr.attribute :name %>
<%= attr.attribute :email %>
<% end %>
@example
<%= attr.attributes :for => :user do |user| %>
<%= user.attribute :name %>
<%= user.attribute :email %>
<%= user.attribute :profile do %>
<%= link_to h(user.record.name), user_path(user.record) %>
<% end %>
<% end %>
@example
<%= attr.attributes :for => @user do |user| %>
<%= user.attribute :name %>
<%= user.attribute :email %>
<%= user.attribute :profile do %>
<%= link_to h(@user.name), user_path(@user) %>
<% end %>
<% end %>
@example
<%= attr.attributes :for => :posts do |post| %>
<%= post.attribute :author %>
<%= post.attribute :title %>
<% end %>
@example
<%= attr.attributes :for => @posts do |post| %>
<%= post.attribute :author %>
<%= post.attribute :title %>
<% end %>
@example
<%= attr.attributes :for => @posts do |post| %>
<%= post.attribute :birthday, :format => false %>
<% end %>
@example
<%= attr.attributes :for => @posts do |post| %>
<%= post.attribute :birthday, :format => :my_fancy_birthday_formatter %>
<% end %>
@overload attributes(header, options = {}, &block)
Creates attributes list with header and yields block to include each attribute
@param [String] header Header of attributes section
@param [Hash] options Options for formating attributes block
@option options [String] :class ('') Name of html class to add to attributes block
@option options [String] :header_class ('') Name of html class to add to header
@option optinos [Symbol,Object] :for Optional new record for new builder
passed as argument block. This new record can be symbol of method name for actual
record, or any other object which is passed as new record for builder.
@yield Block which can call #attribute to include attribute value
@yieldparam builder Builder instance holding actual record (retivable via #record)
@example
<%= attr.attributes "User info" do %>
<%= attr.attribute :name" %>
<%= attr.attribute :email %>
<% end %>
@example
<%= attr.attributes "User", :for => :user do |user| %>
<%= user.attribute :name %>
<%= user.attribute :email %>
<%= user.attribute :profile do %>
<%= link_to h(user.record.name), user_path(user.record) %>
<% end %>
<% end %>
@example
<% attr.attributes "User", :for => @user do |user| %>
<%= user.attribute :name %>
<%= user.attribute :email %>
<%= user.attribute :profile do %>
<%= link_to h(@user.name), user_path(@user) %>
<% end %>
<% end %>
@example
<%= attr.attributes "Post", :for => :posts do |post| %>
<%= post.attribute :author %>
<%= post.attribute :title %>
<% end %>
@example
<%= attr.attributes "Post", :for => @posts do |post| %>
<%= post.attribute :author %>
<%= post.attribute :title %>
<% end %>
@overload attributes(*symbols, options = {})
Creates attributes list without header, attributes are given as list of symbols (record properties)
@param [Symbol, ...] symbols List of attributes
@param [Hash] options Options for formating attributes block
@option options [String] :name (nil) Optional header of attributes section
@option options [String] :class ('') Name of html class to add to attributes block
@option options [String] :header_class ('') Name of html class to add to header
@example
<%= attr.attributes :name, :email %>
@example
<%= attr.attributes :name, :email, :for => :author %>
@example
<%= attr.attributes :name, :email, :for => @user %>
@example
<%= attr.attributes :title, :for => :posts %>
@example
<%= attr.attributes :title, :for => @posts %>
@overload attributes(header, *symbols, options = {})
Creates attributes list with header, attributes are given as list of symbols (record properties)
@param [String] header Header of attributes section
@param [Symbol, ...] symbols Optional list of attributes
@param [Hash] options Options for formating attributes block
@option options [String] :class ('') Name of html class to add to attributes block
@option options [String] :header_class ('') Name of html class to add to header
@example
<%= attr.attributes "User info" :name, :email %>
@example
<%= attr.attributes "Author", :name, :email, :for => :author %>
@example
<%= attr.attributes "Author", :name, :email, :for => @user %>
@example
<%= attr.attributes "Post", :title, :for => :posts %>
@example
<%= attr.attributes "Post", :title, :for => @posts %>
@example All together
<%= attr.attributes "User info", :name, :email, :class => "user_info", :header_class => "header important" %>
@example With block
<%= attr.attributes "User info" :class => "user_info", :header_class => "header important" do %>
<%= attr.attribute :name %>
<%= attr.attribute :email %>
<% end %>
@see #attribute | [
"Creates",
"block",
"of",
"attributes",
"with",
"optional",
"header",
".",
"Attributes",
"are",
"surrounded",
"with",
"ordered",
"list",
"."
] | c024a1c42b665eed590004236e2d067d1ca59a4e | https://github.com/MBO/attrtastic/blob/c024a1c42b665eed590004236e2d067d1ca59a4e/lib/attrtastic/semantic_attributes_builder.rb#L187-L212 | train |
MBO/attrtastic | lib/attrtastic/semantic_attributes_builder.rb | Attrtastic.SemanticAttributesBuilder.attribute | def attribute(*args, &block)
options = args.extract_options!
options.reverse_merge!(Attrtastic.default_options)
options[:html] ||= {}
method = args.shift
html_label_class = [ "label", options[:html][:label_class] ].compact.join(" ")
html_value_class = [ "value", options[:html][:value_class] ].compact.join(" ")
html_class = [ "attribute", options[:html][:class] ].compact.join(" ")
label = options.key?(:label) ? options[:label] : label_for_attribute(method)
if block_given?
output = template.tag(:li, {:class => html_class}, true)
output << template.content_tag(:span, label, :class => html_label_class)
output << template.tag(:span, {:class => html_value_class}, true)
output << template.capture(&block)
output.safe_concat("</span>")
output.safe_concat("</li>")
else
value = if options.key?(:value)
case options[:value]
when Symbol
attribute_value = value_of_attribute(method)
case attribute_value
when Hash
attribute_value[options[:value]]
else
attribute_value.send(options[:value])
end
else
options[:value]
end
else
value_of_attribute(method)
end
value = case options[:format]
when false
value
when nil
format_attribute_value(value)
else
format_attribute_value(value, options[:format])
end
if value.present? || options[:display_empty]
output = template.tag(:li, {:class => html_class}, true)
output << template.content_tag(:span, label, :class => html_label_class)
output << template.content_tag(:span, value, :class => html_value_class)
output.safe_concat("</li>")
end
end
end | ruby | def attribute(*args, &block)
options = args.extract_options!
options.reverse_merge!(Attrtastic.default_options)
options[:html] ||= {}
method = args.shift
html_label_class = [ "label", options[:html][:label_class] ].compact.join(" ")
html_value_class = [ "value", options[:html][:value_class] ].compact.join(" ")
html_class = [ "attribute", options[:html][:class] ].compact.join(" ")
label = options.key?(:label) ? options[:label] : label_for_attribute(method)
if block_given?
output = template.tag(:li, {:class => html_class}, true)
output << template.content_tag(:span, label, :class => html_label_class)
output << template.tag(:span, {:class => html_value_class}, true)
output << template.capture(&block)
output.safe_concat("</span>")
output.safe_concat("</li>")
else
value = if options.key?(:value)
case options[:value]
when Symbol
attribute_value = value_of_attribute(method)
case attribute_value
when Hash
attribute_value[options[:value]]
else
attribute_value.send(options[:value])
end
else
options[:value]
end
else
value_of_attribute(method)
end
value = case options[:format]
when false
value
when nil
format_attribute_value(value)
else
format_attribute_value(value, options[:format])
end
if value.present? || options[:display_empty]
output = template.tag(:li, {:class => html_class}, true)
output << template.content_tag(:span, label, :class => html_label_class)
output << template.content_tag(:span, value, :class => html_value_class)
output.safe_concat("</li>")
end
end
end | [
"def",
"attribute",
"(",
"*",
"args",
",",
"&",
"block",
")",
"options",
"=",
"args",
".",
"extract_options!",
"options",
".",
"reverse_merge!",
"(",
"Attrtastic",
".",
"default_options",
")",
"options",
"[",
":html",
"]",
"||=",
"{",
"}",
"method",
"=",
"args",
".",
"shift",
"html_label_class",
"=",
"[",
"\"label\"",
",",
"options",
"[",
":html",
"]",
"[",
":label_class",
"]",
"]",
".",
"compact",
".",
"join",
"(",
"\" \"",
")",
"html_value_class",
"=",
"[",
"\"value\"",
",",
"options",
"[",
":html",
"]",
"[",
":value_class",
"]",
"]",
".",
"compact",
".",
"join",
"(",
"\" \"",
")",
"html_class",
"=",
"[",
"\"attribute\"",
",",
"options",
"[",
":html",
"]",
"[",
":class",
"]",
"]",
".",
"compact",
".",
"join",
"(",
"\" \"",
")",
"label",
"=",
"options",
".",
"key?",
"(",
":label",
")",
"?",
"options",
"[",
":label",
"]",
":",
"label_for_attribute",
"(",
"method",
")",
"if",
"block_given?",
"output",
"=",
"template",
".",
"tag",
"(",
":li",
",",
"{",
":class",
"=>",
"html_class",
"}",
",",
"true",
")",
"output",
"<<",
"template",
".",
"content_tag",
"(",
":span",
",",
"label",
",",
":class",
"=>",
"html_label_class",
")",
"output",
"<<",
"template",
".",
"tag",
"(",
":span",
",",
"{",
":class",
"=>",
"html_value_class",
"}",
",",
"true",
")",
"output",
"<<",
"template",
".",
"capture",
"(",
"&",
"block",
")",
"output",
".",
"safe_concat",
"(",
"\"</span>\"",
")",
"output",
".",
"safe_concat",
"(",
"\"</li>\"",
")",
"else",
"value",
"=",
"if",
"options",
".",
"key?",
"(",
":value",
")",
"case",
"options",
"[",
":value",
"]",
"when",
"Symbol",
"attribute_value",
"=",
"value_of_attribute",
"(",
"method",
")",
"case",
"attribute_value",
"when",
"Hash",
"attribute_value",
"[",
"options",
"[",
":value",
"]",
"]",
"else",
"attribute_value",
".",
"send",
"(",
"options",
"[",
":value",
"]",
")",
"end",
"else",
"options",
"[",
":value",
"]",
"end",
"else",
"value_of_attribute",
"(",
"method",
")",
"end",
"value",
"=",
"case",
"options",
"[",
":format",
"]",
"when",
"false",
"value",
"when",
"nil",
"format_attribute_value",
"(",
"value",
")",
"else",
"format_attribute_value",
"(",
"value",
",",
"options",
"[",
":format",
"]",
")",
"end",
"if",
"value",
".",
"present?",
"||",
"options",
"[",
":display_empty",
"]",
"output",
"=",
"template",
".",
"tag",
"(",
":li",
",",
"{",
":class",
"=>",
"html_class",
"}",
",",
"true",
")",
"output",
"<<",
"template",
".",
"content_tag",
"(",
":span",
",",
"label",
",",
":class",
"=>",
"html_label_class",
")",
"output",
"<<",
"template",
".",
"content_tag",
"(",
":span",
",",
"value",
",",
":class",
"=>",
"html_value_class",
")",
"output",
".",
"safe_concat",
"(",
"\"</li>\"",
")",
"end",
"end",
"end"
] | Creates list entry for single record attribute
@overload attribute(method, options = {})
Creates entry for record attribute
@param [Symbol] method Attribute name of given record
@param [Hash] options Options
@option options [Hash] :html ({}) Hash with optional :class, :label_class and :value_class names of class for html
@option options [String] :label Label for attribute entry, overrides default label name from symbol
@option options [Symbol,Object] :value If it's Symbol, then it's used as either name of hash key to use on attribute
(if it's hash) or method name to call on attribute. Otherwise it's used as value to use instead of
actual attribute's.
@option options [Boolean] :display_empty (false) Indicates if print value of given attribute even if it is blank?
@option options [Symbol,false,nil] :format (nil) Type of formatter to use to display attribute's value. If it's false,
then don't format at all (just call #to_s). If it's nil, then use default formatting (#l for dates,
#number_with_precision/#number_with_delimiter for floats/integers). If it's Symbol, then use it to select
view helper method and pass aattribute's value to it to format.
@example
<%= attr.attribute :name %>
@example
<%= attr.attribute :name, :label => "Full user name" %>
@example
<%= attr.attribute :name, :value => @user.full_name %>
@example
<%= attr.attribute :address, :value => :street %>
@example
<%= attr.attribute :avatar, :value => :url, :format => :image_tag %>
@overload attribute(method, options = {}, &block)
Creates entry for attribute given with block
@param [Symbol] method Attribute name of given record
@param [Hash] options Options
@option options [Hash] :html ({}) Hash with optional :class, :label_class and :value_class names of classes for html
@option options [String] :label Label for attribute entry, overrides default label name from symbol
@yield Block which is executed in place of value for attribute
@example
<%= attr.attribute :name do %>
<%= link_to @user.full_name, user_path(@user) %>
@overload attribute(options = {}, &block)
Creates entry for attribute with given block, options[:label] is mandatory in this case.
@param [:Hash] options Options
@option options [Hash] :html ({}) Hash with optional :class, :label_class and :value_class names of classes for html
@option options [String] :label Mandatory label for attribute entry
@yield Block which is executed in place of value for attribute
@example
<%= attr.attribute :label => "User link" do %>
<%= link_to @user.full_name, user_path(@user) %>
@example
<%= attr.attribute :name, :display_empty => true %>
@example
<%= attr.attribute :label => "User link" do %>
<%= link_to @user.full_name, user_path(@user) %>
Options can be set globally with Attrtastic.default_options | [
"Creates",
"list",
"entry",
"for",
"single",
"record",
"attribute"
] | c024a1c42b665eed590004236e2d067d1ca59a4e | https://github.com/MBO/attrtastic/blob/c024a1c42b665eed590004236e2d067d1ca59a4e/lib/attrtastic/semantic_attributes_builder.rb#L281-L335 | train |
slate-studio/mongosteen | lib/mongosteen/base_helpers.rb | Mongosteen.BaseHelpers.collection | def collection
get_collection_ivar || begin
chain = end_of_association_chain
# scopes
chain = apply_scopes(chain)
# search
if params[:search]
chain = chain.search(params[:search].to_s.downcase, match: :all)
end
# pagination
if params[:page]
per_page = params[:perPage] || 20
chain = chain.page(params[:page]).per(per_page)
else
chain = chain.all
end
set_collection_ivar(chain)
end
end | ruby | def collection
get_collection_ivar || begin
chain = end_of_association_chain
# scopes
chain = apply_scopes(chain)
# search
if params[:search]
chain = chain.search(params[:search].to_s.downcase, match: :all)
end
# pagination
if params[:page]
per_page = params[:perPage] || 20
chain = chain.page(params[:page]).per(per_page)
else
chain = chain.all
end
set_collection_ivar(chain)
end
end | [
"def",
"collection",
"get_collection_ivar",
"||",
"begin",
"chain",
"=",
"end_of_association_chain",
"chain",
"=",
"apply_scopes",
"(",
"chain",
")",
"if",
"params",
"[",
":search",
"]",
"chain",
"=",
"chain",
".",
"search",
"(",
"params",
"[",
":search",
"]",
".",
"to_s",
".",
"downcase",
",",
"match",
":",
":all",
")",
"end",
"if",
"params",
"[",
":page",
"]",
"per_page",
"=",
"params",
"[",
":perPage",
"]",
"||",
"20",
"chain",
"=",
"chain",
".",
"page",
"(",
"params",
"[",
":page",
"]",
")",
".",
"per",
"(",
"per_page",
")",
"else",
"chain",
"=",
"chain",
".",
"all",
"end",
"set_collection_ivar",
"(",
"chain",
")",
"end",
"end"
] | add support for scopes, search and pagination | [
"add",
"support",
"for",
"scopes",
"search",
"and",
"pagination"
] | f9745fcef269a1eb501b3d0d69b75cfc432d135d | https://github.com/slate-studio/mongosteen/blob/f9745fcef269a1eb501b3d0d69b75cfc432d135d/lib/mongosteen/base_helpers.rb#L7-L29 | train |
slate-studio/mongosteen | lib/mongosteen/base_helpers.rb | Mongosteen.BaseHelpers.get_resource_version | def get_resource_version
resource = get_resource_ivar
version = params[:version].try(:to_i)
if version && version > 0 && version < resource.version
resource.undo(nil, from: version + 1, to: resource.version)
resource.version = version
end
return resource
end | ruby | def get_resource_version
resource = get_resource_ivar
version = params[:version].try(:to_i)
if version && version > 0 && version < resource.version
resource.undo(nil, from: version + 1, to: resource.version)
resource.version = version
end
return resource
end | [
"def",
"get_resource_version",
"resource",
"=",
"get_resource_ivar",
"version",
"=",
"params",
"[",
":version",
"]",
".",
"try",
"(",
":to_i",
")",
"if",
"version",
"&&",
"version",
">",
"0",
"&&",
"version",
"<",
"resource",
".",
"version",
"resource",
".",
"undo",
"(",
"nil",
",",
"from",
":",
"version",
"+",
"1",
",",
"to",
":",
"resource",
".",
"version",
")",
"resource",
".",
"version",
"=",
"version",
"end",
"return",
"resource",
"end"
] | add support for history | [
"add",
"support",
"for",
"history"
] | f9745fcef269a1eb501b3d0d69b75cfc432d135d | https://github.com/slate-studio/mongosteen/blob/f9745fcef269a1eb501b3d0d69b75cfc432d135d/lib/mongosteen/base_helpers.rb#L32-L43 | train |
notCalle/ruby-keytree | lib/key_tree/path.rb | KeyTree.Path.- | def -(other)
other = other.to_key_path
raise KeyError unless prefix?(other)
super(other.length)
end | ruby | def -(other)
other = other.to_key_path
raise KeyError unless prefix?(other)
super(other.length)
end | [
"def",
"-",
"(",
"other",
")",
"other",
"=",
"other",
".",
"to_key_path",
"raise",
"KeyError",
"unless",
"prefix?",
"(",
"other",
")",
"super",
"(",
"other",
".",
"length",
")",
"end"
] | Returns a key path without the leading +prefix+
:call-seq:
Path - other => Path | [
"Returns",
"a",
"key",
"path",
"without",
"the",
"leading",
"+",
"prefix",
"+"
] | 1a88c902c8b5d14f21fd350338776fc094eae8e3 | https://github.com/notCalle/ruby-keytree/blob/1a88c902c8b5d14f21fd350338776fc094eae8e3/lib/key_tree/path.rb#L68-L73 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.